@shumai-one/shumai-agent 0.2.2 → 0.2.3
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/bin/shumai-agent-app.js +1 -1
- package/package.json +8 -8
package/bin/shumai-agent-app.js
CHANGED
|
@@ -1299,7 +1299,7 @@ ${$}`:w}function aM0(W){let $=W.replace(/\/+$/,""),w=$.lastIndexOf("/");return w
|
|
|
1299
1299
|
`,J=Q.filter((O)=>O.type==="symlink"),X=[];if(J.length>0){let O=J.map((B)=>B.targetId).filter((B)=>!!B);if(O.length>0)X=(await this.prismaClient.asset.findMany({where:{id:{in:O},isDeleted:!1}})).map((L)=>({id:L.id,name:L.name,type:L.type,parentId:L.parentId,storageKeyId:L.storageKeyId,sortIndex:L.sortIndex,targetId:L.targetId}))}let Y=[...Q.filter((O)=>O.type!=="symlink"),...X].filter((O)=>O.type!=="folder"&&O.type!=="root"&&O.type!=="share_root"&&O.type!=="share"),K=new Set(Y.filter((O)=>O.type==="version_stack").map((O)=>O.id)),V=new Map,z=[];for(let O of Y){if(O.type==="version_stack")continue;if(O.parentId&&K.has(O.parentId)){let B=V.get(O.parentId)||[];B.push(O),V.set(O.parentId,B)}else z.push(O)}let H=[];for(let O of V.values())if(O.sort((B,L)=>{if(!B.sortIndex||!L.sortIndex)return 0;return B.sortIndex<L.sortIndex?-1:B.sortIndex>L.sortIndex?1:0}),O.length>0)H.push(O[0]);let G=[...z,...H],M=new Map;for(let O of G)M.set(O.id,O);let U=Array.from(M.values()),N=U.map((O)=>O.storageKeyId).filter((O)=>!!O),D=await this.prismaClient.storageKey.findMany({where:{id:{in:N}}}),R=new Map(D.map((O)=>[O.id,O.key]));return(await Promise.all(U.map(async(O)=>{let B=O.storageKeyId?R.get(O.storageKeyId):null;if(!B)return null;let L=await t0.presign(process.env.S3_BUCKET||"shumai",B,"GET",!0);return{id:O.id,name:O.name,url:L}}))).filter((O)=>!!O)}async getDownloadUrl(W,$){let w=await this.prismaClient.asset.findUnique({where:{id:W},select:{storageKey:{select:{key:!0}}}});if(!w?.storageKey?.key)throw Error("Asset not found or has no storage key");let Q=w.storageKey.key,J=Q.substring(0,Q.lastIndexOf("/")+1);if($.includes("..")||!$.startsWith(J))throw Error("Key does not belong to this asset");return t0.presign(process.env.S3_BUCKET||"shumai",$,"GET",!0)}async toPreviewInfo(W){if(!W.media)return null;let $=W.media?.proxyType||null,w=void 0;if($==="image"&&W.media.thumbnail?.key)w=await t0.presign(process.env.S3_BUCKET||"shumai",W.media.thumbnail.key,"GET");else if(W.media.poster?.key)w=await t0.presign(process.env.S3_BUCKET||"shumai",W.media.poster.key,"GET");let Q=void 0;if(W.media.sprite?.key)Q=await t0.presign(process.env.S3_BUCKET||"shumai",W.media.sprite.key,"GET");return{proxyType:$,thumbnailUrl:w,originalHeight:W.media.metadata?.originalHeight,originalWidth:W.media.metadata?.originalWidth,spriteUrl:Q,duration:W.media.metadata?.duration,pageCount:W.media.metadata?.totalFrames}}async toCommentInfo(W){let $=[];if("replies"in W&&W.replies)for(let Y of W.replies)$.push(await this.toCommentInfo(Y));let w=[];if(W.attachments){for(let Y of W.attachments)if(Y.asset?.storageKey?.key){let K=await t0.presign(process.env.S3_BUCKET||"shumai",Y.asset.storageKey.key,"GET"),V=Y.asset.media?.proxyType||null;w.push({id:Y.id,assetId:Y.asset.id,url:K,proxyType:V})}}let Q=[],J=(W.message||"").match(/<@([^>]+)>/g);if(J){let Y=J.map((V)=>V.replace("<@","").replace(">","")),K=await this.prismaClient.user.findMany({where:{id:{in:Y}}});for(let V of K)Q.push({id:V.id,name:V.name,image:await h6(V.image)})}let X={id:"",name:""};if(W.sessionId)X.id=W.creatorId||"",X.name=W.creator?.name||"Ai Bot",X.image=await h6(W.creator?.image);else if(W.creator)X.id=W.creator.id,X.name=W.creator.name,X.image=await h6(W.creator.image);let Z=W.completionLastChangedBy?{id:W.completionLastChangedBy.id,name:W.completionLastChangedBy.name,image:await h6(W.completionLastChangedBy.image)}:null;return{id:W.id,assetId:W.assetId,message:W.message,annotations:W.annotation,second:W.second,creator:X,replies:$,attachments:w,mentions:Q,createdAt:W.createdAt.toISOString(),updatedAt:W.updatedAt.toISOString(),sessionId:W.sessionId,isCompleted:W.isCompleted,completionLastChangedBy:Z}}}var Q$=new sp;var tp=[{key:"file_size",scope:"SYSTEM",readOnly:!0,config:{name:"File Size",type:"number",number:{scale:0}}},{key:"resolution_width",scope:"SYSTEM",readOnly:!0,config:{name:"Resolution Width",type:"number",number:{scale:0}}},{key:"resolution_height",scope:"SYSTEM",readOnly:!0,config:{name:"Resolution Height",type:"number",number:{scale:0}}},{key:"name",scope:"SYSTEM",readOnly:!0,config:{name:"Name",type:"text",text:{}}},{key:"rating",scope:"SYSTEM",readOnly:!1,config:{name:"Rating",type:"rating",rating:{maxValue:5}}},{key:"duration",scope:"SYSTEM",readOnly:!0,config:{name:"Duration",type:"number",number:{scale:0}}},{key:"bitRate",scope:"SYSTEM",readOnly:!0,config:{name:"Bit Rate",type:"number",number:{scale:1}}},{key:"frame_rate",scope:"SYSTEM",readOnly:!0,config:{name:"Frame Rate",type:"number",number:{scale:3}}},{key:"keywords",scope:"SYSTEM",readOnly:!1,config:{name:"Keywords",type:"selectMulti",selectMulti:{options:[]}}},{key:"file_type",scope:"SYSTEM",readOnly:!0,config:{name:"File Type",type:"select",select:{options:[{id:"video",displayName:"Video",color:"system"},{id:"audio",displayName:"Audio",color:"system"},{id:"image",displayName:"Image",color:"system"},{id:"document",displayName:"Document",color:"system"},{id:"file",displayName:"File",color:"system"}]}}},{key:"proxy_type",scope:"SYSTEM",readOnly:!0,config:{name:"Proxy Type",type:"select",select:{options:[{id:"image",displayName:"Image",color:"system"},{id:"video",displayName:"Video",color:"system"},{id:"audio",displayName:"Audio",color:"system"},{id:"pdf",displayName:"PDF",color:"system"}]}}},{key:"audio_bit_depth",scope:"SYSTEM",readOnly:!0,config:{name:"Audio Bit Depth",type:"number",number:{scale:0}}},{key:"audio_channels",scope:"SYSTEM",readOnly:!0,config:{name:"Audio Channels",type:"number",number:{scale:0}}},{key:"audio_codec",scope:"SYSTEM",readOnly:!0,config:{name:"Audio Codec",type:"text",text:{}}},{key:"audio_sample_rate",scope:"SYSTEM",readOnly:!0,config:{name:"Audio Sample Rate",type:"number",number:{scale:0}}},{key:"video_codec",scope:"SYSTEM",readOnly:!0,config:{name:"Video Codec",type:"text",text:{}}},{key:"format",scope:"SYSTEM",readOnly:!0,config:{name:"Format",type:"text",text:{}}},{key:"status",scope:"SYSTEM",readOnly:!1,config:{name:"Status",type:"select",select:{options:[{id:"needs_review",displayName:"Needs Review",color:"red"},{id:"in_progress",displayName:"In Progress",color:"yellow"},{id:"approved",displayName:"Approved",color:"green"}]}}}];class ep{client;constructor(W=g){this.client=W}async syncSystemFields(){await this.client.$transaction(async(W)=>{for(let $ of tp)await W.metadataField.upsert({where:{key:$.key},update:{scope:$.scope,readOnly:$.readOnly,config:$.config},create:{key:$.key,scope:$.scope,readOnly:$.readOnly??!1,config:$.config}})})}async createTeamField(W,$){return await this.client.metadataField.create({data:{key:l1(),scope:"TEAM",teamId:W,config:$.config,aiAutofill:$.aiAutofill,description:$.description}})}async listTeamFields(W){return await this.client.metadataField.findMany({where:{OR:[{scope:"SYSTEM"},{AND:[{scope:"TEAM"},{teamId:W}]}]}})}async getFieldByKey(W){return this.client.metadataField.findUnique({where:{key:W}})}async updateTeamField(W,$,w){let Q=await this.client.metadataField.findUnique({where:{key:$}});if(!Q)throw Error("Field not found");if(Q.teamId!==W)throw Error("Field does not belong to this team");return await this.client.metadataField.update({where:{id:Q.id},data:{config:w.config,aiAutofill:w.aiAutofill??Q.aiAutofill,description:w.description??Q.description}})}async deleteTeamField(W,$){let w=await this.client.metadataField.findUnique({where:{key:$}});if(!w)throw Error("Field not found");if(w.teamId!==W)throw Error("Field does not belong to this team");await this.client.metadataField.delete({where:{key:$}})}async createProjectField(W,$){let w=await this.client.project.findUnique({where:{id:W},select:{teamId:!0}});if(!w)throw Error("Project not found");return await this.client.metadataField.create({data:{key:l1(),scope:"PROJECT",projectId:W,teamId:w.teamId,config:$.config,aiAutofill:$.aiAutofill,description:$.description}})}async listProjectFields(W,$){let w=await this.client.project.findUnique({where:{id:$},select:{teamId:!0}});if(!w)throw Error("Project not found");let Q=await this.client.metadataField.findMany({where:{OR:[{scope:"SYSTEM"},{AND:[{scope:"TEAM"},{teamId:w.teamId}]},{AND:[{scope:"PROJECT"},{projectId:$}]}]}}),J=W?await this.getProjectFieldsOrder(W,$):[],X=new Map;J.forEach((K,V)=>{X.set(K.fieldId,V)});let Z=new Map;J.forEach((K)=>{Z.set(K.fieldId,K.visible)});let Y=Q.map((K)=>({field:K,visible:Z.has(K.key)?Z.get(K.key):W===null}));return Y.sort((K,V)=>{let z=X.get(K.field.key),H=X.get(V.field.key);if(z!==void 0&&H!==void 0)return z-H;if(z!==void 0)return-1;if(H!==void 0)return 1;let G=K.field.config?.name||"",M=V.field.config?.name||"";return G.localeCompare(M)}),Y}async getProjectFieldsOrder(W,$){let w=this.getProjectFieldOrderKey(W,$),Q=await this.client.systemSettings.findUnique({where:{key:w}});if(!Q||!Q.value)return[];return Q.value}async updateProjectFieldsOrder(W,$,w){let Q=this.getProjectFieldOrderKey(W,$);await this.client.systemSettings.upsert({where:{key:Q},create:{key:Q,value:w},update:{value:w}})}getProjectFieldOrderKey(W,$){return`project_field_order:${W}:${$}`}async updateProjectField(W,$,w){let Q=await this.client.metadataField.findUnique({where:{key:$}});if(!Q)throw Error("Field not found");if(Q.projectId!==W)throw Error("Field does not belong to this project");return await this.client.metadataField.update({where:{id:Q.id},data:{config:w.config,aiAutofill:w.aiAutofill??Q.aiAutofill,description:w.description??Q.description}})}async deleteProjectField(W,$){let w=await this.client.metadataField.findUnique({where:{key:$}});if(!w)throw Error("Field not found");if(w.projectId!==W)throw Error("Field does not belong to this project");await this.client.metadataField.delete({where:{key:$}})}async updateAssetMetadata(W,$,w=!1){let Q=await Q$.resolveLatestVersionId(W);await this.client.$transaction(async(J)=>{for(let X of $){let Z=await J.metadataField.findUnique({where:{key:X.key}});if(Z?.readOnly&&!w)throw Error(`Field ${Z.key} is read-only`);let Y=X.value,K=null,V=null,z=null,H=null,G=null;if(typeof Y==="string"){let M=new Date(Y);if(!isNaN(M.getTime())&&Y.includes("T")&&Y.includes("-"))G=M;else K=Y}else if(typeof Y==="number")V=Y;else if(typeof Y==="boolean")z=Y;else if(Y instanceof Date)G=Y;else if(Array.isArray(Y))H=Y;else if(Y===null);else if(typeof Y==="object")H=Y;else K=String(Y);await J.assetMetadataValue.upsert({where:{assetId_fieldKey:{assetId:Q,fieldKey:X.key}},create:{assetId:Q,fieldKey:X.key,stringValue:K,numberValue:V,booleanValue:z,jsonValue:H,dateValue:G},update:{stringValue:K,numberValue:V,booleanValue:z,jsonValue:H,dateValue:G}})}await J.asset.update({where:{id:Q},data:{updatedAt:new Date}})})}}var lq=new ep;import{execFile as DT0}from"child_process";class H1 extends Error{constructor(W,$,w,...Q){if(Array.isArray($))$=$.join(" ").trim();super($);if(Error.captureStackTrace!==void 0)Error.captureStackTrace(this,H1);this.code=W;for(let J of Q)for(let X in J){let Z=J[X];this[X]=Buffer.isBuffer(Z)?Z.toString(w.encoding):Z==null?Z:JSON.parse(JSON.stringify(Z))}}}var hY=function(W){return typeof W==="object"&&W!==null&&!Array.isArray(W)};var iq=function(W){let $=[];for(let w=0,Q=W.length;w<Q;w++){let J=W[w];if(J===void 0||J===null||J===!1)$[w]={disabled:!0};else if(typeof J==="string"||typeof J==="number")$[w]={name:`${J}`};else if(hY(J)){if(typeof J.name!=="string")throw new H1("CSV_OPTION_COLUMNS_MISSING_NAME",["Option columns missing name:",`property "name" is required at position ${w}`,"when column is an object literal"]);$[w]=J}else throw new H1("CSV_INVALID_COLUMN_DEFINITION",["Invalid column definition:","expect a string or a literal object,",`got ${JSON.stringify(J)} at position ${w}`])}return $};class Wn{constructor(W=100){this.size=W,this.length=0,this.buf=Buffer.allocUnsafe(W)}prepend(W){if(Buffer.isBuffer(W)){let $=this.length+W.length;if($>=this.size){if(this.resize(),$>=this.size)throw Error("INVALID_BUFFER_STATE")}let w=this.buf;this.buf=Buffer.allocUnsafe(this.size),W.copy(this.buf,0),w.copy(this.buf,W.length),this.length+=W.length}else{let $=this.length++;if($===this.size)this.resize();let w=this.clone();this.buf[0]=W,w.copy(this.buf,1,0,$)}}append(W){let $=this.length++;if($===this.size)this.resize();this.buf[$]=W}clone(){return Buffer.from(this.buf.slice(0,this.length))}resize(){let W=this.length;this.size=this.size*2;let $=Buffer.allocUnsafe(this.size);this.buf.copy($,0,0,W),this.buf=$}toString(W){if(W)return this.buf.slice(0,this.length).toString(W);else return Uint8Array.prototype.slice.call(this.buf.slice(0,this.length))}toJSON(){return this.toString("utf8")}reset(){this.length=0}}var xT=Wn;var $n=function(W){let $=[32,9,10,13,12,11,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288,65279].reduce((Q,J)=>{let X=Buffer.from(String.fromCharCode(J),W.encoding);if(J!==63&&X.length===1&&X[0]===63)return Q;return Q.push(X),Q},[]),w=new Uint8Array(256);for(let Q of $)w[Q[0]]=1;return{bomSkipped:!1,bufBytesStart:0,castField:W.cast_function,commenting:!1,delimiterBufPrevious:void 0,delimiterDiscovered:!1,error:void 0,enabled:W.from_line===1,escaping:!1,escapeIsQuote:Buffer.isBuffer(W.escape)&&Buffer.isBuffer(W.quote)&&Buffer.compare(W.escape,W.quote)===0,expectedRecordLength:Array.isArray(W.columns)?W.columns.length:void 0,field:new xT(20),firstLineToHeaders:W.cast_first_line_to_header,needMoreDataSize:Math.max(W.comment!==null?W.comment.length:0,...W.delimiter?W.delimiter.map((Q)=>Q.length):[],W.delimiter_auto?1:0,W.quote!==null?W.quote.length:0,...$.map((Q)=>Q.length)),previousBuf:void 0,quoting:!1,stop:!1,rawBuffer:new xT(100),record:[],recordHasError:!1,record_length:0,recordDelimiterMaxLength:W.record_delimiter.length===0?0:Math.max(...W.record_delimiter.map((Q)=>Q.length)),trimChars:[Buffer.from(" ",W.encoding)[0],Buffer.from("\t",W.encoding)[0]],wasQuoting:!1,wasRowDelimiter:!1,timchars:$,timcharFirstBytes:w}};var wn=function(W){return W.replace(/([A-Z])/g,function($,w){return"_"+w.toLowerCase()})};var nJ=function(W){let $={};for(let Q in W)$[wn(Q)]=W[Q];if($.encoding===void 0||$.encoding===!0)$.encoding="utf8";else if($.encoding===null||$.encoding===!1)$.encoding=null;else if(typeof $.encoding!=="string"&&$.encoding!==null)throw new H1("CSV_INVALID_OPTION_ENCODING",["Invalid option encoding:","encoding must be a string or null to return a buffer,",`got ${JSON.stringify($.encoding)}`],$);if($.bom===void 0||$.bom===null||$.bom===!1)$.bom=!1;else if($.bom!==!0)throw new H1("CSV_INVALID_OPTION_BOM",["Invalid option bom:","bom must be true,",`got ${JSON.stringify($.bom)}`],$);if($.cast_function=null,$.cast===void 0||$.cast===null||$.cast===!1||$.cast==="")$.cast=void 0;else if(typeof $.cast==="function")$.cast_function=$.cast,$.cast=!0;else if($.cast!==!0)throw new H1("CSV_INVALID_OPTION_CAST",["Invalid option cast:","cast must be true or a function,",`got ${JSON.stringify($.cast)}`],$);if($.cast_date===void 0||$.cast_date===null||$.cast_date===!1||$.cast_date==="")$.cast_date=!1;else if($.cast_date===!0)$.cast_date=function(Q){let J=Date.parse(Q);return!isNaN(J)?new Date(J):Q};else if(typeof $.cast_date!=="function")throw new H1("CSV_INVALID_OPTION_CAST_DATE",["Invalid option cast_date:","cast_date must be true or a function,",`got ${JSON.stringify($.cast_date)}`],$);if($.cast_first_line_to_header=void 0,$.columns===!0)$.cast_first_line_to_header=void 0;else if(typeof $.columns==="function")$.cast_first_line_to_header=$.columns,$.columns=!0;else if(Array.isArray($.columns))$.columns=iq($.columns);else if($.columns===void 0||$.columns===null||$.columns===!1)$.columns=!1;else throw new H1("CSV_INVALID_OPTION_COLUMNS",["Invalid option columns:","expect an array, a function or true,",`got ${JSON.stringify($.columns)}`],$);if($.group_columns_by_name===void 0||$.group_columns_by_name===null||$.group_columns_by_name===!1)$.group_columns_by_name=!1;else if($.group_columns_by_name!==!0)throw new H1("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","expect an boolean,",`got ${JSON.stringify($.group_columns_by_name)}`],$);else if($.columns===!1)throw new H1("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","the `columns` mode must be activated."],$);if($.comment===void 0||$.comment===null||$.comment===!1||$.comment==="")$.comment=null;else{if(typeof $.comment==="string")$.comment=Buffer.from($.comment,$.encoding);if(!Buffer.isBuffer($.comment))throw new H1("CSV_INVALID_OPTION_COMMENT",["Invalid option comment:","comment must be a buffer or a string,",`got ${JSON.stringify($.comment)}`],$)}if($.comment_no_infix===void 0||$.comment_no_infix===null||$.comment_no_infix===!1)$.comment_no_infix=!1;else if($.comment_no_infix!==!0)throw new H1("CSV_INVALID_OPTION_COMMENT",["Invalid option comment_no_infix:","value must be a boolean,",`got ${JSON.stringify($.comment_no_infix)}`],$);if($.delimiter_auto===void 0||$.delimiter_auto===null||$.delimiter_auto===!1)$.delimiter_auto=!1;else if($.delimiter_auto===!0)$.delimiter_auto={};else if(!hY($.delimiter_auto))throw new H1("CSV_INVALID_OPTION_DELIMITER_AUTO",["Invalid option delimiter_auto:","delimiter_auto must be a boolean or a configuration object,",`got ${JSON.stringify($.delimiter_auto)}`],$);if($.delimiter_auto){if($.delimiter_auto.preferred===void 0)$.delimiter_auto.preferred={[44]:1.8,[9]:1.8,[59]:1.6,[32]:1.6,[58]:1.5,[46]:1.4,[47]:1.4};else if(!hY($.delimiter_auto.preferred))throw new H1("CSV_INVALID_OPTION_DELIMITER_AUTO",["Invalid option delimiter_auto:","preferred must be an object,",`got ${JSON.stringify($.delimiter_auto.preferred)}`],$);if($.delimiter_auto.score===void 0)$.delimiter_auto.score=(Q,J)=>{return(Q.total-Q.std)*(J.preferred[Q.char_code]||1)};else if(typeof $.delimiter_auto.score!=="function")throw new H1("CSV_INVALID_OPTION_DELIMITER_AUTO",["Invalid option delimiter_auto:","score must be a function,",`got ${JSON.stringify($.delimiter_auto.score)}`],$);if($.delimiter_auto.size===void 0)$.delimiter_auto.size=2048;else if(typeof $.delimiter_auto.size!=="number")throw new H1("CSV_INVALID_OPTION_DELIMITER_AUTO",["Invalid option delimiter_auto:","size must be a number,",`got ${JSON.stringify($.delimiter_auto.size)}`],$)}let w=JSON.stringify($.delimiter);if($.delimiter_auto!==!1)$.delimiter=[];if(!Array.isArray($.delimiter)){if($.delimiter===void 0||$.delimiter===null||$.delimiter===!1)$.delimiter=Buffer.from(",",$.encoding);$.delimiter=[$.delimiter]}if($.delimiter=$.delimiter.map(function(Q){if(typeof Q==="string")Q=Buffer.from(Q,$.encoding);if(!Buffer.isBuffer(Q)||Q.length===0)throw new H1("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${w}`],$);return Q}),$.escape===void 0||$.escape===!0)$.escape=Buffer.from('"',$.encoding);else if(typeof $.escape==="string")$.escape=Buffer.from($.escape,$.encoding);else if($.escape===null||$.escape===!1)$.escape=null;if($.escape!==null){if(!Buffer.isBuffer($.escape))throw Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify($.escape)}`)}if($.from===void 0||$.from===null)$.from=1;else{if(typeof $.from==="string"&&/\d+/.test($.from))$.from=parseInt($.from);if(Number.isInteger($.from)){if($.from<0)throw Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(W.from)}`)}else throw Error(`Invalid Option: from must be an integer, got ${JSON.stringify($.from)}`)}if($.from_line===void 0||$.from_line===null)$.from_line=1;else{if(typeof $.from_line==="string"&&/\d+/.test($.from_line))$.from_line=parseInt($.from_line);if(Number.isInteger($.from_line)){if($.from_line<=0)throw Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(W.from_line)}`)}else throw Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(W.from_line)}`)}if($.ignore_last_delimiters===void 0||$.ignore_last_delimiters===null)$.ignore_last_delimiters=!1;else if(typeof $.ignore_last_delimiters==="number"){if($.ignore_last_delimiters=Math.floor($.ignore_last_delimiters),$.ignore_last_delimiters===0)$.ignore_last_delimiters=!1}else if(typeof $.ignore_last_delimiters!=="boolean")throw new H1("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS",["Invalid option `ignore_last_delimiters`:","the value must be a boolean value or an integer,",`got ${JSON.stringify($.ignore_last_delimiters)}`],$);if($.ignore_last_delimiters===!0&&$.columns===!1)throw new H1("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS",["The option `ignore_last_delimiters`","requires the activation of the `columns` option"],$);if($.info===void 0||$.info===null||$.info===!1)$.info=!1;else if($.info!==!0)throw Error(`Invalid Option: info must be true, got ${JSON.stringify($.info)}`);if($.max_record_size===void 0||$.max_record_size===null||$.max_record_size===!1)$.max_record_size=0;else if(Number.isInteger($.max_record_size)&&$.max_record_size>=0);else if(typeof $.max_record_size==="string"&&/\d+/.test($.max_record_size))$.max_record_size=parseInt($.max_record_size);else throw Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify($.max_record_size)}`);if($.objname===void 0||$.objname===null||$.objname===!1)$.objname=void 0;else if(Buffer.isBuffer($.objname)){if($.objname.length===0)throw Error("Invalid Option: objname must be a non empty buffer");if($.encoding===null);else $.objname=$.objname.toString($.encoding)}else if(typeof $.objname==="string"){if($.objname.length===0)throw Error("Invalid Option: objname must be a non empty string")}else if(typeof $.objname==="number");else throw Error(`Invalid Option: objname must be a string or a buffer, got ${$.objname}`);if($.objname!==void 0){if(typeof $.objname==="number"){if($.columns!==!1)throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field")}else if($.columns===!1)throw Error("Invalid Option: objname field must be combined with columns or be defined as an index")}if($.on_record===void 0||$.on_record===null)$.on_record=void 0;else if(typeof $.on_record!=="function")throw new H1("CSV_INVALID_OPTION_ON_RECORD",["Invalid option `on_record`:","expect a function,",`got ${JSON.stringify($.on_record)}`],$);if($.on_skip!==void 0&&$.on_skip!==null&&typeof $.on_skip!=="function")throw Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify($.on_skip)}`);if($.quote===null||$.quote===!1||$.quote==="")$.quote=null;else{if($.quote===void 0||$.quote===!0)$.quote=Buffer.from('"',$.encoding);else if(typeof $.quote==="string")$.quote=Buffer.from($.quote,$.encoding);if(!Buffer.isBuffer($.quote))throw Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify($.quote)}`)}if($.raw===void 0||$.raw===null||$.raw===!1)$.raw=!1;else if($.raw!==!0)throw Error(`Invalid Option: raw must be true, got ${JSON.stringify($.raw)}`);if($.record_delimiter===void 0)$.record_delimiter=[];else if(typeof $.record_delimiter==="string"||Buffer.isBuffer($.record_delimiter)){if($.record_delimiter.length===0)throw new H1("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer,",`got ${JSON.stringify($.record_delimiter)}`],$);$.record_delimiter=[$.record_delimiter]}else if(!Array.isArray($.record_delimiter))throw new H1("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer,",`got ${JSON.stringify($.record_delimiter)}`],$);if($.record_delimiter=$.record_delimiter.map(function(Q,J){if(typeof Q!=="string"&&!Buffer.isBuffer(Q))throw new H1("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer",`at index ${J},`,`got ${JSON.stringify(Q)}`],$);else if(Q.length===0)throw new H1("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer",`at index ${J},`,`got ${JSON.stringify(Q)}`],$);if(typeof Q==="string")Q=Buffer.from(Q,$.encoding);return Q}),typeof $.relax_column_count==="boolean");else if($.relax_column_count===void 0||$.relax_column_count===null)$.relax_column_count=!1;else throw Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify($.relax_column_count)}`);if(typeof $.relax_column_count_less==="boolean");else if($.relax_column_count_less===void 0||$.relax_column_count_less===null)$.relax_column_count_less=!1;else throw Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify($.relax_column_count_less)}`);if(typeof $.relax_column_count_more==="boolean");else if($.relax_column_count_more===void 0||$.relax_column_count_more===null)$.relax_column_count_more=!1;else throw Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify($.relax_column_count_more)}`);if(typeof $.relax_quotes==="boolean");else if($.relax_quotes===void 0||$.relax_quotes===null)$.relax_quotes=!1;else throw Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify($.relax_quotes)}`);if(typeof $.skip_empty_lines==="boolean");else if($.skip_empty_lines===void 0||$.skip_empty_lines===null)$.skip_empty_lines=!1;else throw Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify($.skip_empty_lines)}`);if(typeof $.skip_records_with_empty_values==="boolean");else if($.skip_records_with_empty_values===void 0||$.skip_records_with_empty_values===null)$.skip_records_with_empty_values=!1;else throw Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify($.skip_records_with_empty_values)}`);if(typeof $.skip_records_with_error==="boolean");else if($.skip_records_with_error===void 0||$.skip_records_with_error===null)$.skip_records_with_error=!1;else throw Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify($.skip_records_with_error)}`);if($.rtrim===void 0||$.rtrim===null||$.rtrim===!1)$.rtrim=!1;else if($.rtrim!==!0)throw Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify($.rtrim)}`);if($.ltrim===void 0||$.ltrim===null||$.ltrim===!1)$.ltrim=!1;else if($.ltrim!==!0)throw Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify($.ltrim)}`);if($.trim===void 0||$.trim===null||$.trim===!1)$.trim=!1;else if($.trim!==!0)throw Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify($.trim)}`);if($.trim===!0&&W.ltrim!==!1)$.ltrim=!0;else if($.ltrim!==!0)$.ltrim=!1;if($.trim===!0&&W.rtrim!==!1)$.rtrim=!0;else if($.rtrim!==!0)$.rtrim=!1;if($.to===void 0||$.to===null)$.to=-1;else if($.to!==-1){if(typeof $.to==="string"&&/\d+/.test($.to))$.to=parseInt($.to);if(Number.isInteger($.to)){if($.to<=0)throw Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(W.to)}`)}else throw Error(`Invalid Option: to must be an integer, got ${JSON.stringify(W.to)}`)}if($.to_line===void 0||$.to_line===null)$.to_line=-1;else if($.to_line!==-1){if(typeof $.to_line==="string"&&/\d+/.test($.to_line))$.to_line=parseInt($.to_line);if(Number.isInteger($.to_line)){if($.to_line<=0)throw Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(W.to_line)}`)}else throw Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(W.to_line)}`)}return $};var Qn=function(W,$){if(!$)({delimiter_auto:$}=nJ({delimiter_auto:!0}));if(typeof W==="string")W=Buffer.from(W);if(Buffer.isBuffer(W))W=((J)=>{let X=[],Z=oq({delimiter:[]}),Y=(z)=>X.push(z),K=()=>{},V=Z.parse(J,!0,Y,K);if(V!==void 0)throw V;return X})(W);let w=Array(127).fill().map(()=>({lines:[]}));W.map(([J],X)=>{for(let Z=0,Y=J.length;Z<Y;Z++){let K=J.charCodeAt(Z);if(w[K].lines[X]===void 0)w[K].lines[X]=0;w[K].lines[X]++}}),w.map((J,X)=>{J.char_code=X,J.std=MT0(J.lines),J.total=J.lines.reduce((Z,Y)=>Z+Y,0),J.preferred=!!$.preferred[X],J.score=$.score(J,$)});let Q=w.reduce((J,X)=>J.score>X.score?J:X,{});return String.fromCharCode(Q.char_code)},MT0=function(W){let $=W.length;if($===0)return 0;let w=W.reduce((Q,J)=>Q+J)/$;return Math.sqrt(W.map((Q)=>Math.pow(Q-w,2)).reduce((Q,J)=>Q+J)/$)};var Jn=function(W){return W.every(($)=>$==null||$.toString&&$.toString().trim()==="")},NT0=13,UT0=10,lJ={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},oq=function(W={}){let $={bytes:0,bytes_records:0,comment_lines:0,empty_lines:0,invalid_field_length:0,lines:1,records:0},w=nJ(W);return{info:$,original_options:W,options:w,state:$n(w),__needMoreData:function(Q,J,X){if(X)return!1;let{encoding:Z,escape:Y,quote:K}=this.options,{quoting:V,needMoreDataSize:z,recordDelimiterMaxLength:H}=this.state,G=J-Q-1,M=Math.max(z,H===0?Buffer.from(`\r
|
|
1300
1300
|
`,Z).length:H,V?(Y===null?0:Y.length)+K.length:0,V?K.length+H:0);return G<M},parse:function(Q,J,X,Z){let{bom:Y,comment_no_infix:K,delimiter_auto:V,encoding:z,from_line:H,ltrim:G,max_record_size:M,raw:U,relax_quotes:N,rtrim:D,skip_empty_lines:R,to:T,to_line:O}=this.options,{comment:B,escape:L,quote:C,record_delimiter:f}=this.options,{bomSkipped:x,delimiterDiscovered:k,delimiterBufPrevious:v,rawBuffer:u,escapeIsQuote:i}=this.state;if(!k&&V){let n;if(v===void 0)n=Q;else if(v!==void 0&&Q===void 0)n=v;else n=Buffer.concat([v,Q]);if(Q=void 0,J||n.length>V.size)this.options.delimiter=[Buffer.from(Qn(n,this.options.delimiter_auto))],this.state.previousBuf=n,this.state.delimiterBufPrevious=void 0,this.state.delimiterDiscovered=!0;else{this.state.delimiterBufPrevious=n;return}}let{previousBuf:w0}=this.state,s;if(w0===void 0)if(Q===void 0){Z();return}else s=Q;else if(w0!==void 0&&Q===void 0)s=w0;else s=Buffer.concat([w0,Q]);if(x===!1)if(Y===!1)this.state.bomSkipped=!0;else if(s.length<3){if(J===!1){this.state.previousBuf=s;return}}else{for(let n in lJ)if(lJ[n].compare(s,0,lJ[n].length)===0){let G0=lJ[n].length;this.state.bufBytesStart+=G0,s=s.slice(G0);let C0=nJ({...this.original_options,encoding:n});for(let R0 in C0)this.options[R0]=C0[R0];({comment:B,escape:L,quote:C}=this.options);break}this.state.bomSkipped=!0}let e=s.length,r;for(r=0;r<e;r++){if(this.__needMoreData(r,e,J))break;if(this.state.wasRowDelimiter===!0)this.info.lines++,this.state.wasRowDelimiter=!1;if(O!==-1&&this.info.lines>O){this.state.stop=!0,Z();return}if(this.state.quoting===!1&&f.length===0){if(this.__autoDiscoverRecordDelimiter(s,r))f=this.options.record_delimiter}let n=s[r];if(U===!0)u.append(n);if((n===NT0||n===UT0)&&this.state.wasRowDelimiter===!1)this.state.wasRowDelimiter=!0;if(this.state.escaping===!0)this.state.escaping=!1;else{if(L!==null&&this.state.quoting===!0&&this.__isEscape(s,r,n)&&r+L.length<e)if(i){if(this.__isQuote(s,r+L.length)){this.state.escaping=!0,r+=L.length-1;continue}}else{this.state.escaping=!0,r+=L.length-1;continue}if(this.state.commenting===!1&&this.__isQuote(s,r))if(this.state.quoting===!0){let R0=s[r+C.length],P0=D&&this.__isCharTrimable(s,r+C.length),F0=B!==null&&this.__compareBytes(B,s,r+C.length,R0),h0=this.__isDelimiter(s,r+C.length,R0),I0=f.length===0?this.__autoDiscoverRecordDelimiter(s,r+C.length):this.__isRecordDelimiter(R0,s,r+C.length);if(L!==null&&this.__isEscape(s,r,n)&&this.__isQuote(s,r+L.length))r+=L.length-1;else if(!R0||h0||I0||F0||P0){this.state.quoting=!1,this.state.wasQuoting=!0,r+=C.length-1;continue}else if(N===!1){let R5=this.__error(new H1("CSV_INVALID_CLOSING_QUOTE",["Invalid Closing Quote:",`got "${String.fromCharCode(R0)}"`,`at line ${this.info.lines}`,"instead of delimiter, record delimiter, trimable character","(if activated) or comment"],this.options,this.__infoField()));if(R5!==void 0)return R5}else this.state.quoting=!1,this.state.wasQuoting=!0,this.state.field.prepend(C),r+=C.length-1}else if(this.state.field.length!==0){if(N===!1){let R0=this.__infoField(),P0=Object.keys(lJ).map((h0)=>lJ[h0].equals(this.state.field.toString())?h0:!1).filter(Boolean)[0],F0=this.__error(new H1("INVALID_OPENING_QUOTE",["Invalid Opening Quote:",`a quote is found on field ${JSON.stringify(R0.column)} at line ${R0.lines}, value is ${JSON.stringify(this.state.field.toString(z))}`,P0?`(${P0} bom)`:void 0],this.options,R0,{field:this.state.field}));if(F0!==void 0)return F0}}else{this.state.quoting=!0,r+=C.length-1;continue}if(this.state.quoting===!1){let R0=this.__isRecordDelimiter(n,s,r);if(R0!==0){if(this.state.commenting&&this.state.wasQuoting===!1&&this.state.record.length===0&&this.state.field.length===0)this.info.comment_lines++;else{if(this.state.enabled===!1&&this.info.lines+(this.state.wasRowDelimiter===!0?1:0)>=H){this.state.enabled=!0,this.__resetField(),this.__resetRecord(),r+=R0-1;continue}if(R===!0&&this.state.wasQuoting===!1&&this.state.record.length===0&&this.state.field.length===0){this.info.empty_lines++,r+=R0-1;continue}this.info.bytes=this.state.bufBytesStart+r;let h0=this.__onField();if(h0!==void 0)return h0;this.info.bytes=this.state.bufBytesStart+r+R0;let I0=this.__onRecord(X);if(I0!==void 0)return I0;if(T!==-1&&this.info.records>=T){this.state.stop=!0,Z();return}}this.state.commenting=!1,r+=R0-1;continue}if(this.state.commenting)continue;if(B!==null&&(K===!1||this.state.record.length===0&&this.state.field.length===0)){if(this.__compareBytes(B,s,r,n)!==0){this.state.commenting=!0;continue}}let P0=this.__isDelimiter(s,r,n);if(P0!==0){this.info.bytes=this.state.bufBytesStart+r;let F0=this.__onField();if(F0!==void 0)return F0;r+=P0-1;continue}}}if(this.state.commenting===!1){if(M!==0&&this.state.record_length+this.state.field.length>M)return this.__error(new H1("CSV_MAX_RECORD_SIZE",["Max Record Size:","record exceed the maximum number of tolerated bytes",`of ${M}`,`at line ${this.info.lines}`],this.options,this.__infoField()))}let G0=G===!1||this.state.quoting===!0||this.state.field.length!==0||!this.__isCharTrimable(s,r),C0=D===!1||this.state.wasQuoting===!1;if(G0===!0&&C0===!0)this.state.field.append(n);else if(D===!0&&!this.__isCharTrimable(s,r))return this.__error(new H1("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE",["Invalid Closing Quote:","found non trimable byte after quote",`at line ${this.info.lines}`],this.options,this.__infoField()));else{if(G0===!1)r+=this.__isCharTrimable(s,r)-1;continue}}if(J===!0){if(this.state.quoting===!0){let n=this.__error(new H1("CSV_QUOTE_NOT_CLOSED",["Quote Not Closed:",`the parsing is finished with an opening quote at line ${this.info.lines}`],this.options,this.__infoField()));if(n!==void 0)return n}else if(this.state.wasQuoting===!0||this.state.record.length!==0||this.state.field.length!==0){this.info.bytes=this.state.bufBytesStart+r;let n=this.__onField();if(n!==void 0)return n;let G0=this.__onRecord(X);if(G0!==void 0)return G0}else if(this.state.wasRowDelimiter===!0)this.info.empty_lines++;else if(this.state.commenting===!0)this.info.comment_lines++}else this.state.bufBytesStart+=r,this.state.previousBuf=s.slice(r);if(this.state.wasRowDelimiter===!0)this.info.lines++,this.state.wasRowDelimiter=!1},__onRecord:function(Q){let{columns:J,group_columns_by_name:X,encoding:Z,info:Y,from:K,relax_column_count:V,relax_column_count_less:z,relax_column_count_more:H,raw:G,skip_records_with_empty_values:M}=this.options,{enabled:U,record:N}=this.state;if(U===!1)return this.__resetRecord();let D=N.length;if(J===!0){if(M===!0&&Jn(N)){this.__resetRecord();return}return this.__firstLineToColumns(N)}if(J===!1&&this.info.records===0)this.state.expectedRecordLength=D;if(D!==this.state.expectedRecordLength){let R=J===!1?new H1("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH",["Invalid Record Length:",`expect ${this.state.expectedRecordLength},`,`got ${D} on line ${this.info.lines}`],this.options,this.__infoField(),{record:N}):new H1("CSV_RECORD_INCONSISTENT_COLUMNS",["Invalid Record Length:",`columns length is ${J.length},`,`got ${D} on line ${this.info.lines}`],this.options,this.__infoField(),{record:N});if(V===!0||z===!0&&D<this.state.expectedRecordLength||H===!0&&D>this.state.expectedRecordLength)this.info.invalid_field_length++,this.state.error=R;else{let T=this.__error(R);if(T)return T}}if(M===!0&&Jn(N)){this.__resetRecord();return}if(this.state.recordHasError===!0){this.__resetRecord(),this.state.recordHasError=!1;return}if(this.info.records++,K===1||this.info.records>=K){let{objname:R}=this.options;if(J!==!1){let T={};for(let O=0,B=N.length;O<B;O++){if(J[O]===void 0||J[O].disabled)continue;if(X===!0&&T[J[O].name]!==void 0)if(Array.isArray(T[J[O].name]))T[J[O].name]=T[J[O].name].concat(N[O]);else T[J[O].name]=[T[J[O].name],N[O]];else T[J[O].name]=N[O]}if(G===!0||Y===!0){let O=Object.assign({record:T},G===!0?{raw:this.state.rawBuffer.toString(Z)}:{},Y===!0?{info:this.__infoRecord()}:{}),B=this.__push(R===void 0?O:[T[R],O],Q);if(B)return B}else{let O=this.__push(R===void 0?T:[T[R],T],Q);if(O)return O}}else if(G===!0||Y===!0){let T=Object.assign({record:N},G===!0?{raw:this.state.rawBuffer.toString(Z)}:{},Y===!0?{info:this.__infoRecord()}:{}),O=this.__push(R===void 0?T:[N[R],T],Q);if(O)return O}else{let T=this.__push(R===void 0?N:[N[R],N],Q);if(T)return T}}this.__resetRecord()},__firstLineToColumns:function(Q){let{firstLineToHeaders:J}=this.state;try{let X=J===void 0?Q:J.call(null,Q);if(!Array.isArray(X))return this.__error(new H1("CSV_INVALID_COLUMN_MAPPING",["Invalid Column Mapping:","expect an array from column function,",`got ${JSON.stringify(X)}`],this.options,this.__infoField(),{headers:X}));let Z=iq(X);this.state.expectedRecordLength=Z.length,this.options.columns=Z,this.__resetRecord();return}catch(X){return X}},__resetRecord:function(){if(this.options.raw===!0)this.state.rawBuffer.reset();this.state.error=void 0,this.state.record=[],this.state.record_length=0},__onField:function(){let{cast:Q,encoding:J,rtrim:X,max_record_size:Z}=this.options,{enabled:Y,wasQuoting:K}=this.state;if(Y===!1)return this.__resetField();let V=this.state.field.toString(J);if(X===!0&&K===!1)V=V.trimRight();if(Q===!0){let[z,H]=this.__cast(V);if(z!==void 0)return z;V=H}if(this.state.record.push(V),Z!==0&&typeof V==="string")this.state.record_length+=V.length;this.__resetField()},__resetField:function(){this.state.field.reset(),this.state.wasQuoting=!1},__push:function(Q,J){let{on_record:X}=this.options;if(X!==void 0){let Z=this.__infoRecord();try{Q=X.call(null,Q,Z)}catch(Y){return Y}if(Q===void 0||Q===null)return}this.info.bytes_records+=this.info.bytes,J(Q)},__cast:function(Q){let{columns:J,relax_column_count:X}=this.options;if(Array.isArray(J)===!0&&X&&this.options.columns.length<=this.state.record.length)return[void 0,void 0];if(this.state.castField!==null)try{let Y=this.__infoField();return[void 0,this.state.castField.call(null,Q,Y)]}catch(Y){return[Y]}if(this.__isFloat(Q))return[void 0,parseFloat(Q)];else if(this.options.cast_date!==!1){let Y=this.__infoField();return[void 0,this.options.cast_date.call(null,Q,Y)]}return[void 0,Q]},__compareBytes:function(Q,J,X,Z){if(Q[0]!==Z)return 0;let Y=Q.length;for(let K=1;K<Y;K++)if(Q[K]!==J[X+K])return 0;return Y},__isCharTrimable:function(Q,J){let{timchars:X,timcharFirstBytes:Z}=this.state,Y=Q[J];if(Y===void 0||Z[Y]===0)return 0;W:for(let K=0;K<X.length;K++){let V=X[K];for(let z=0;z<V.length;z++)if(V[z]!==Q[J+z])continue W;return V.length}return 0},__isDelimiter:function(Q,J,X){let{delimiter:Z,ignore_last_delimiters:Y}=this.options;if(Y===!0&&this.state.record.length===this.options.columns.length-1)return 0;else if(Y!==!1&&typeof Y==="number"&&this.state.record.length===Y-1)return 0;W:for(let K=0;K<Z.length;K++){let V=Z[K];if(V[0]===X){for(let z=1;z<V.length;z++)if(V[z]!==Q[J+z])continue W;return V.length}}return 0},__isEscape:function(Q,J,X){let{escape:Z}=this.options;if(Z===null)return!1;let Y=Z.length;if(Z[0]===X){for(let K=0;K<Y;K++)if(Z[K]!==Q[J+K])return!1;return!0}return!1},__isFloat:function(Q){return Q-parseFloat(Q)+1>=0},__isQuote:function(Q,J){let{quote:X}=this.options;if(X===null)return!1;let Z=X.length;for(let Y=0;Y<Z;Y++)if(X[Y]!==Q[J+Y])return!1;return!0},__isRecordDelimiter:function(Q,J,X){let{record_delimiter:Z}=this.options,Y=Z.length;W:for(let K=0;K<Y;K++){let V=Z[K],z=V.length;if(V[0]!==Q)continue;for(let H=1;H<z;H++)if(V[H]!==J[X+H])continue W;return V.length}return 0},__autoDiscoverRecordDelimiter:function(Q,J){let{encoding:X}=this.options,Z=[Buffer.from(`\r
|
|
1301
1301
|
`,X),Buffer.from(`
|
|
1302
|
-
`,X),Buffer.from("\r",X)];W:for(let Y=0;Y<Z.length;Y++){let K=Z[Y].length;for(let V=0;V<K;V++)if(Z[Y][V]!==Q[J+V])continue W;return this.options.record_delimiter.push(Z[Y]),this.state.recordDelimiterMaxLength=Z[Y].length,Z[Y].length}return 0},__error:function(Q){let{encoding:J,raw:X,skip_records_with_error:Z}=this.options,Y=typeof Q==="string"?Error(Q):Q;if(Z){if(this.state.recordHasError=!0,this.options.on_skip!==void 0)try{this.options.on_skip(Y,X?this.state.rawBuffer.toString(J):void 0)}catch(K){return K}return}else return Y},__infoDataSet:function(){return{...this.info,columns:this.options.columns}},__infoRecord:function(){let{columns:Q,raw:J,encoding:X}=this.options;return{...this.__infoDataSet(),bytes_records:this.info.bytes,error:this.state.error,header:Q===!0,index:this.state.record.length,raw:J?this.state.rawBuffer.toString(X):void 0}},__infoField:function(){let{columns:Q}=this.options,J=Array.isArray(Q),X=this.info.bytes_records;return{...this.__infoRecord(),bytes_records:X,column:J===!0?Q.length>this.state.record.length?Q[this.state.record.length].name:null:this.state.record.length,quoting:this.state.wasQuoting}}}};var Xn=function(W,$={}){if(typeof W==="string")W=Buffer.from(W);let w=$&&$.objname?Object.create(null):[],Q=oq($),J=(Y)=>{if(Q.options.objname===void 0)w.push(Y);else w[Y[0]]=Y[1]},X=()=>{},Z=Q.parse(W,!0,J,X);if(Z!==void 0)throw Z;return w};import*as g1 from"fs";import*as Vn from"os";import*as UW from"path";import Zn from"pdfkit";import Hw from"sharp";import{promisify as OT0}from"util";var bT={apch:"Apple ProRes 422 High Quality",apcn:"Apple ProRes 422 Standard Definition",apcs:"Apple ProRes 422 LT",apco:"Apple ProRes 422 Proxy",ap4h:"Apple ProRes 4444",jpeg:"JPEG Image","3gvo":"3GPP Video Orientation",a3d1:"Multiview Video Coding",a3d2:"Multiview Video Coding",a3d3:"Multiview Video Coding",a3d4:"Multiview Video Coding",a3ds:"Auro-Cx 3D audio","ac-3":"AC-3 audio","ac-4":"AC-4 audio",alac:"Apple lossless audio codec",alaw:"a-Law",av01:"AV1 video",avc1:"Advanced Video Coding",avc2:"Advanced Video Coding",avc3:"Advanced Video Coding",avc4:"Advanced Video Coding",avcp:"Advanced Video Coding Parameters",dra1:"DRA Audio",drac:"Dirac Video Coder","dts-":"Dependent base layer for DTS layered audio","dts+":"Enhancement layer for DTS layered audio",dtsc:"DTS Coherent Acoustics audio",dtse:"DTS Express low bit rate audio, also known as DTS LBR",dtsh:"DTS-HD High Resolution Audio",dtsl:"DTS-HD Master Audio",dtsx:"DTS:X",dvav:"AVC-based \u201CDolby Vision\u201D",dvhe:"HEVC-based \u201CDolby Vision\u201D","ec-3":"Enhanced AC-3 audio",enca:"Encrypted/Protected audio",encf:"Encrypted/Protected font",encm:"Encrypted/Protected metadata stream",encs:"Encrypted Systems stream",enct:"Encrypted Text",encv:"Encrypted/protected video",fdp:"File delivery hints",fLaC:"Fres Lossless Audio Codec",g719:"ITU-T Recommendation G.719 (2008)",g726:"ITU-T Recommendation G.726 (1990)",hev1:"High Efficiency Video Coding",hvc1:"High Efficiency Video Coding",hvt1:"High Efficiency Video Coding",ixse:"DVB Track Level Index Track",lhe1:"Layered High Efficiency Video Coding",lht1:"Layered High Efficiency Video Coding",lhv1:"Layered High Efficiency Video Coding",m2ts:"MPEG-2 transport stream for DMB",m4ae:"MPEG-4 Audio Enhancement MP4v1/2",mett:"Text timed metadata that is not XML",metx:"XML timed metadata",mha1:"MPEG-H Audio (single stream, uncapsulated)",mha2:"MPEG-H Audio (multi-stream, unencapsulated)",mhm1:"MPEG-H Audio (single stream, MHAS encapsulated)",mhm2:"MPEG-H Audio (multi-stream, MHAS encapsulated)",mjp2:"Motion JPEG 2000",mlix:"DVB Movie level index track",mlpa:"MLP Audio",mp4a:"MPEG-4 Audio",mp4s:"MPEG-4 Systems",mp4v:"MPEG-4 Visual",mvc1:"Multiview coding",mvc2:"Multiview coding",mvc3:"Multiview coding",mvc4:"Multiview coding",mvd1:"Multiview coding",mvd2:"Multiview coding",mvd3:"Multiview coding",mvd4:"Multiview coding",oksd:"OMA Keys",Opus:"Opus audio coding",pm2t:"Protected MPEG-2 Transport",prtp:"Protected RTP Reception",raw:"Uncompressed audio",resv:"Restricted Video",rm2t:"MPEG-2 Transport Reception",rrtp:"RTP reception",rsrp:"SRTP Reception",rtmd:"Real Time Metadata Sample Entry(XAVC Format)",rtp:"RTP Hints",s263:"ITU H.263 video (3GPP format)",samr:"Narrowband AMR voice",sawb:"Wideband AMR voice",sawp:"Extended AMR-WB (AMR-WB+)",sevc:"EVRC Voice",sm2t:"MPEG-2 Transport Server",sqcp:"13K Voice",srtp:"SRTP Hints",ssmv:"SMV Voice",STGS:"Subtitle Sample Entry (HMMP)",stpp:"Subtitles (Timed Text)",svc1:"Scalable Video Coding",svc2:"Scalable Video Coding",svcM:"SVC Metadata",tc64:"64 bit timecode samples",tmcd:"32 bit timecode samples",twos:"Uncompressed 16-bit audio",tx3g:"Timed Text stream",ulaw:"Samples have been compressed using uLaw 2:1.",unid:"Dynamic Range Control (DRC) data",urim:"Binary timed metadata identified by URI","vc-1":"SMPTE VC-1",vp08:"VP8 video",vp09:"VP9 video",wvtt:"WebVTT"};var $6=OT0(DT0);function Yn(){let W=[...process.env.PDF_CJK_FONT_PATH?[{fontPath:process.env.PDF_CJK_FONT_PATH,fontName:process.env.PDF_CJK_FONT_NAME}]:[],{fontPath:"/System/Library/Fonts/Supplemental/Arial Unicode.ttf"},{fontPath:"/Library/Fonts/Arial Unicode.ttf"},{fontPath:"/System/Library/Fonts/PingFang.ttc",fontName:"PingFangSC-Regular"},{fontPath:"/System/Library/Fonts/STHeiti Light.ttc",fontName:"STHeitiSC-Light"},{fontPath:"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",fontName:"NotoSansCJKsc-Regular"},{fontPath:"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",fontName:"NotoSansCJKsc-Regular"},{fontPath:"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",fontName:"WenQuanYiZenHei"},{fontPath:"/usr/share/fonts/truetype/arphic/ukai.ttc",fontName:"AR-PL-UKai-CN"},{fontPath:"/usr/share/fonts/noto/NotoSansCJK-Regular.ttc",fontName:"Noto Sans CJK SC"},{fontPath:"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf"},{fontPath:"/usr/share/fonts/truetype/droid/DroidSansFallback.ttf"},{fontPath:"/usr/share/fonts/google-droid/DroidSansFallback.ttf"},{fontPath:"C:\\Windows\\Fonts\\msyh.ttc",fontName:"MicrosoftYaHei"},{fontPath:"C:\\Windows\\Fonts\\simsun.ttc",fontName:"SimSun"},{fontPath:"C:\\Windows\\Fonts\\simhei.ttf"}];for(let $ of W)if(g1.existsSync($.fontPath))return $;return}function RT0(W){try{return Xn(W,{skip_empty_lines:!0,relax_column_count:!0,relax_quotes:!0,trim:!0,delimiter_auto:!0})}catch{return W.split(/\r?\n/).filter(($)=>$.trim().length>0).map(($)=>$.split(",").map((w)=>w.trim()))}}function Kn(W){if(typeof W==="string"){if(W.toLowerCase().endsWith(".psd"))return!0;if(g1.existsSync(W))try{let $=g1.openSync(W,"r"),w=Buffer.alloc(4);return g1.readSync($,w,0,4,0),g1.closeSync($),w.toString("ascii")==="8BPS"}catch{return!1}return!1}return W.length>=4&&W[0]===56&&W[1]===66&&W[2]===80&&W[3]===83}class zn{prismaClient;constructor(W=g){this.prismaClient=W}async execImageMagick(W){try{return await $6("magick",W)}catch($){if($?.code==="ENOENT")return await $6("convert",W);throw $}}async execImageMagickIdentify(W){let $=`${W}[0]`,w;try{w=(await $6("magick",["identify","-format","%w %h",$])).stdout}catch(Z){if(Z?.code==="ENOENT")w=(await $6("identify",["-format","%w %h",$])).stdout;else throw Z}let Q=w.trim().split(/\s+/),J=parseInt(Q[0],10)||0,X=parseInt(Q[1],10)||0;return{width:J,height:X}}resolveCodecName(W){let $=W.mime_codec_string||W.tags?.mime_codec_string;if($&&typeof $==="string"){let w=$.split(".")[0];if(bT[w])return bT[w]}return W.codec_name}safeParseInt(W){if(W===void 0||W===null)return;let $=typeof W==="string"?parseInt(W,10):W;return Number.isFinite($)?$:void 0}async getVideoInfo(W){let{stdout:$}=await $6("ffprobe",["-v","quiet","-print_format","json","-show_format","-show_streams",W]),w=JSON.parse($),Q=w.streams.find((V)=>V.codec_type==="video"),J=w.streams.find((V)=>V.codec_type==="audio");if(!Q)throw Error("No video stream found");let X=0;if(Q.avg_frame_rate){let V=Q.avg_frame_rate.split("/");if(V.length===2){let z=parseFloat(V[0]),H=parseFloat(V[1]);if(H>0)X=z/H}}if(X===0&&Q.r_frame_rate){let V=Q.r_frame_rate.split("/");if(V.length===2){let z=parseFloat(V[0]),H=parseFloat(V[1]);if(H>0)X=z/H}}let Z=parseFloat(w.format.duration),Y=0;if(Q.nb_frames)Y=parseInt(Q.nb_frames,10);if(!Y&&X>0&&!isNaN(Z))Y=Math.round(Z*X);let K=Q.tags?.timecode||w.format?.tags?.timecode;return{originalWidth:Q.width,originalHeight:Q.height,duration:Z,bitRate:parseFloat(w.format.bit_rate),frameRate:X||30,totalFrames:Y||0,startTimecode:K,hasAudio:!!J,videoCodec:this.resolveCodecName(Q),audioCodec:J?this.resolveCodecName(J):void 0,audioChannels:J?.channels,audioSampleRate:this.safeParseInt(J?.sample_rate),audioBitDepth:this.safeParseInt(J?.bits_per_raw_sample)??this.safeParseInt(J?.bits_per_sample),mimeType:""}}async getImageInfo(W){let $=W,w=null;if(W.startsWith("http")){let J=await fetch(W);if(!J.ok)throw Error(`Failed to fetch image from ${W}: ${J.statusText}`);$=Buffer.from(await J.arrayBuffer())}if(Kn($)){let J;if(typeof $==="string")J=$;else w=this.createTempDir("psd-info-"),J=UW.join(w,"input.psd"),g1.writeFileSync(J,$);try{let{width:X,height:Z}=await this.execImageMagickIdentify(J);return{originalWidth:X,originalHeight:Z,duration:0,bitRate:0,frameRate:0,totalFrames:0,startTimecode:void 0,hasAudio:!1,mimeType:"psd"}}catch(X){console.warn("ImageMagick identify failed for PSD, falling back to sharp:",X)}finally{if(w)this.removeDir(w)}}let Q=await Hw($,{limitInputPixels:!1}).metadata();return{originalWidth:Q.width||0,originalHeight:Q.height||0,duration:0,bitRate:0,frameRate:0,totalFrames:0,startTimecode:void 0,hasAudio:!1,mimeType:Q.format||""}}async transcodeVideo(W){let $=`[0:v]scale=w=${W.width}:h=${W.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`;if(W.frameRate)$+=`,fps=${W.frameRate}`;$+="[vout]";let w=["-i",W.inputFile,"-filter_complex",$,"-map","[vout]"];if(W.frameRate){let Q;if(typeof W.frameRate==="number")Q=W.frameRate;else{let J=W.frameRate.split("/");if(J.length===2)Q=parseFloat(J[0])/parseFloat(J[1]);else Q=parseFloat(W.frameRate)}if(Number.isFinite(Q)&&Q>0){let J=Math.max(1,Math.round(Q));w.push("-r",Q.toString(),"-g",J.toString(),"-force_key_frames","expr:gte(t,n_forced*1)")}}if(!W.disableAudio)w.push("-map","0:a?");if(w.push("-c:v","libx264","-preset","fast","-crf","26"),!W.disableAudio)w.push("-c:a","aac","-b:a","128k");w.push("-movflags","+faststart","-max_muxing_queue_size","1024",W.outputFile),await $6("ffmpeg",["-y","-loglevel","warning",...w])}async transcodeImage(W,$,w,Q,J=null){let X=W;if(typeof W==="string"&&W.startsWith("http")){let z=await fetch(W);if(!z.ok)throw Error(`Failed to fetch image from ${W}: ${z.statusText}`);X=Buffer.from(await z.arrayBuffer())}let Z=7680,Y=w>0?Math.min(w,Z):Z,K=J&&J>0?Math.min(J,Z):Z;if(Kn(X)){let z,H=null;if(typeof X==="string")z=X;else H=this.createTempDir("psd-transcode-"),z=UW.join(H,"input.psd"),g1.writeFileSync(z,X);try{let G=K<Z?`${Y}x${K}>`:`${Y}x${Z}>`;await this.execImageMagick([`${z}[0]`,"-colorspace","sRGB","-resize",G,"-quality",Q.toString(),$]);return}finally{if(H)this.removeDir(H)}}let V=Hw(X,{limitInputPixels:!1});V.toColorspace("srgb").resize(Y,K,{withoutEnlargement:!0,fit:"inside"}),await V.webp({quality:Q}).toFile($)}async generateSprite(W,$,w,Q){let X=`[0:v]fps=${100/Q},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:480:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`;await $6("ffmpeg",["-y","-loglevel","warning",...["-i",W,"-filter_complex",X,"-map","[sprite_out]","-frames:v","1","-c:v","libwebp","-q:v","75",$,"-map","[thumb_out]","-c:v","libwebp","-q:v","75","-frames:v","1","-max_muxing_queue_size","1024",w]])}async generatePdfSprite(W,$,w){let Q=this.createTempDir("pdf-sprite-");try{let J=UW.join(Q,"page");try{await $6("pdftoppm",["-png","-f","1","-l","100",W,J])}catch(M){let U=M?.code,N=M instanceof Error?M.message:String(M),D=N.toLowerCase();if(U==="ENOENT"||D.includes("enoent")||D.includes("not found")&&D.includes("pdftoppm"))throw Error(`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${N})`,{cause:M});throw M}let X=g1.readdirSync(Q).filter((M)=>M.endsWith(".png"));if(X.length===0)throw Error("pdftoppm produced no image outputs");X.sort((M,U)=>{let N=parseInt(M.replace(/[^0-9]/g,""),10),D=parseInt(U.replace(/[^0-9]/g,""),10);return N-D});let Z=X.length,Y=UW.join(Q,X[0]),K=await Hw(Y,{limitInputPixels:!1}).metadata(),V=K.width||800,z=K.height||1000;for(let M=1;M<=100;M++){let U=Math.min(Z-1,Math.floor((M-1)*Z/100)),N=UW.join(Q,X[U]),D=UW.join(Q,`frame_${M}.png`);if(N!==D)g1.copyFileSync(N,D)}let H=["-i",UW.join(Q,"frame_%d.png"),"-filter_complex","scale=w=480:h=-2,tile=10x10","-frames:v","1","-c:v","libwebp","-q:v","75",$];await $6("ffmpeg",["-y","-loglevel","warning",...H]),await Hw(Y,{limitInputPixels:!1}).toColorspace("srgb").resize(480,null,{withoutEnlargement:!0,fit:"inside"}).webp({quality:75}).toFile(w);let G=Z;try{let{stdout:M}=await $6("pdfinfo",[W]),U=M.match(/Pages:\s+(\d+)/);if(U)G=parseInt(U[1],10)}catch{}return{pageCount:G,originalWidth:V,originalHeight:z}}finally{this.removeDir(Q)}}async getPdfInfo(W){let $=this.createTempDir("pdf-info-"),w=800,Q=1000,J=1;try{let X=UW.join($,"page");await $6("pdftoppm",["-png","-f","1","-l","1",W,X]);let Z=g1.readdirSync($).filter((Y)=>Y.endsWith(".png"));if(Z.length>0){let Y=await Hw(UW.join($,Z[0]),{limitInputPixels:!1}).metadata();w=Y.width||800,Q=Y.height||1000}}catch(X){console.warn("pdftoppm not available for PDF dimensions extraction:",X)}try{let{stdout:X}=await $6("pdfinfo",[W]),Z=X.match(/Pages:\s+(\d+)/);if(Z)J=parseInt(Z[1],10)}catch{}finally{this.removeDir($)}return{originalWidth:w,originalHeight:Q,duration:0,bitRate:0,frameRate:0,totalFrames:J,hasAudio:!1,mimeType:"application/pdf"}}async generatePdfFromText(W,$){let w=g1.readFileSync(W,"utf-8"),J=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\uac00-\ud7af]/.test(w)?Yn():void 0;return new Promise((X,Z)=>{let Y=new Zn({size:"A4",margin:40,bufferPages:!0}),K=g1.createWriteStream($);if(Y.pipe(K),J)if(J.fontName!==void 0)Y.font(J.fontPath,J.fontName);else Y.font(J.fontPath);else Y.font("Helvetica");Y.fontSize(10),Y.text(w,{lineGap:3,paragraphGap:4}),Y.end(),K.on("finish",()=>X()),K.on("error",(V)=>Z(V))})}async generatePdfFromCsv(W,$){let w=g1.readFileSync(W,"utf-8"),Q=RT0(w),X=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\uac00-\ud7af]/.test(w)?Yn():void 0;if(Q.length===0)Q.push(["(Empty CSV)"]);let Z=Math.max(...Q.map((K)=>K.length)),Y=Z>5;return new Promise((K,V)=>{let z=new Zn({size:"A4",layout:Y?"landscape":"portrait",margin:30,bufferPages:!0}),H=g1.createWriteStream($);z.pipe(H);let G=()=>{if(X)if(X.fontName!==void 0)z.font(X.fontPath,X.fontName);else z.font(X.fontPath);else z.font("Helvetica");z.fontSize(9)};G();let M=z.page.width-z.page.margins.left-z.page.margins.right,U=Math.max(40,M/Z),N=z.page.margins.left,D=z.page.margins.top,R=20,T=(B,L,C)=>{if(L)z.rect(N,C,U*Z,R).fill("#e0e0e0"),z.fillColor("#000000");for(let f=0;f<Z;f++){let x=B[f]||"",k=N+f*U;z.rect(k,C,U,R).stroke("#cccccc"),z.fillColor("#000000").text(x,k+4,C+5,{width:U-8,height:R-6,ellipsis:!0})}},O=Q[0];T(O,!0,D),D+=R;for(let B=1;B<Q.length;B++){if(D+R>z.page.height-z.page.margins.bottom)z.addPage(),G(),D=z.page.margins.top,T(O,!0,D),D+=R;T(Q[B],!1,D),D+=R}z.end(),H.on("finish",()=>K()),H.on("error",(B)=>V(B))})}async extractAudio(W,$,w){await $6("ffmpeg",["-y","-loglevel","warning",...["-i",W,"-vn","-acodec","libmp3lame","-b:a",w,$]])}async getAudioInfo(W){let{stdout:$}=await $6("ffprobe",["-v","quiet","-print_format","json","-show_format","-show_streams",W]),w=JSON.parse($),Q=w.streams.find((X)=>X.codec_type==="audio");if(!Q)throw Error("No audio stream found");let J=parseFloat(w.format.duration);return{originalWidth:0,originalHeight:0,duration:isNaN(J)?0:J,bitRate:parseFloat(w.format.bit_rate)||0,frameRate:0,totalFrames:0,startTimecode:void 0,hasAudio:!0,videoCodec:void 0,audioCodec:this.resolveCodecName(Q),audioChannels:Q?.channels,audioSampleRate:this.safeParseInt(Q?.sample_rate),audioBitDepth:this.safeParseInt(Q?.bits_per_raw_sample)??this.safeParseInt(Q?.bits_per_sample),mimeType:""}}async transcodeAudio(W){let $=W.bitrate||"128k",w=["-i",W.inputFile,"-vn","-c:a","aac","-b:a",$,"-ac","2",W.outputFile];await $6("ffmpeg",["-y","-loglevel","warning",...w])}async extractVideoFrames(W){if(W.isImage){let Z=UW.join(W.outputDir,"1.webp");return await this.transcodeImage(W.inputFile,Z,-1,80,W.frameHeight),[Z]}let $=await this.getVideoInfo(W.inputFile),w=W.numFrames/$.duration,Q=UW.join(W.outputDir,"%d.webp"),J=["-i",W.inputFile,"-vf",`fps=${w},scale=-2:${W.frameHeight}`,"-c:v","libwebp","-q:v","80",Q];return await $6("ffmpeg",["-y","-loglevel","warning",...J]),g1.readdirSync(W.outputDir).filter((Z)=>Z.endsWith(".webp")).sort((Z,Y)=>{let K=parseInt(UW.basename(Z,".webp")),V=parseInt(UW.basename(Y,".webp"));return K-V}).map((Z)=>UW.join(W.outputDir,Z))}createTempDir(W){return g1.mkdtempSync(UW.join(Vn.tmpdir(),W))}removeDir(W){g1.rmSync(W,{recursive:!0,force:!0})}async createVideoTranscodeTask(W,$,w){return this.prismaClient.workflowTask.create({data:{assetId:W,projectId:$,type:l5.transcode_video,status:v1.pending,payload:{projectId:$,transcode:w}}})}async createImageTranscodeTask(W,$,w){return this.prismaClient.workflowTask.create({data:{assetId:W,projectId:$,type:l5.transcode_image,status:v1.pending,payload:{projectId:$,transcode:w}}})}async takeScreenshots(W){let $=process.env.S3_BUCKET||"shumai",w=this.createTempDir("screenshot-"),Q=UW.join(w,UW.basename(W.assetKey));try{await t0.downloadToFile($,W.assetKey,Q);let J=[];if(W.count<=1)J=[W.start];else{let Y=(W.end-W.start)/W.count;J=Array.from({length:W.count},(K,V)=>W.start+V*Y)}let X=W.commentTimestamp;if(X!==void 0&&X!==null){if(X>=W.start&&X<=W.end){let Y=0,K=Math.abs(J[0]-X);for(let V=1;V<J.length;V++){let z=Math.abs(J[V]-X);if(z<K)K=z,Y=V}J[Y]=X}}let Z=[];for(let Y of J){let K=`shot-${Y.toFixed(3)}-${l1()}.webp`,V=UW.join(w,K),z=["-ss",Y.toFixed(3),"-i",Q,"-vframes","1","-vf","scale=-2:720","-c:v","libwebp","-q:v","80",V];if(await $6("ffmpeg",["-y","-loglevel","warning",...z]),X!==void 0&&X!==null&&Y===X&&W.annotations&&W.annotations.length>0){let M=g1.readFileSync(V),U=await this.overlayAnnotationsOnBuffer(M,W.annotations);g1.writeFileSync(V,U)}let H=`files/${W.assetId}/screenshots/${K}`,G=g1.readFileSync(V);await t0.putObject($,H,G,G.length,"image/webp"),Z.push({key:H,timestamp:Y})}return Z}finally{this.removeDir(w)}}async renderPdfPages(W){let $=process.env.S3_BUCKET||"shumai",w=this.createTempDir("pdf-pages-"),Q=UW.join(w,UW.basename(W.assetKey));try{await t0.downloadToFile($,W.assetKey,Q);let J=UW.join(w,"page");try{await $6("pdftoppm",["-png","-f",W.start.toString(),"-l",W.end.toString(),Q,J])}catch(K){let V=K?.code,z=K instanceof Error?K.message:String(K),H=z.toLowerCase();if(V==="ENOENT"||H.includes("enoent")||H.includes("not found")&&H.includes("pdftoppm"))throw Error(`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${z})`,{cause:K});throw K}let X=g1.readdirSync(w).filter((K)=>K.endsWith(".png"));if(X.length===0)throw Error("pdftoppm produced no image outputs");X.sort((K,V)=>{let z=parseInt(K.replace(/[^0-9]/g,""),10),H=parseInt(V.replace(/[^0-9]/g,""),10);return z-H});let Z=[],Y=jT(W.assetKey);for(let K=0;K<X.length;K++){let V=W.start+K,z=UW.join(w,X[K]),H=`${Y}-page-${V}-${l1()}.webp`,G=await Hw(z,{limitInputPixels:!1}).toColorspace("srgb").resize(1920,1080,{fit:"inside",withoutEnlargement:!1}).webp({quality:85}).toBuffer(),M=W.commentTimestamp!==void 0&&W.commentTimestamp!==null?Math.round(W.commentTimestamp):null;if(M!==null&&V===M&&W.annotations&&W.annotations.length>0)G=await this.overlayAnnotationsOnBuffer(G,W.annotations);let U=`files/${W.assetId}/pdf_pages/${H}`;await t0.putObject($,U,G,G.length,"image/webp"),Z.push({key:U,page:V})}return Z}finally{this.removeDir(w)}}async overlayAnnotationsOnBuffer(W,$){if(!$||$.length===0)return W;let w=await Hw(W,{limitInputPixels:!1}).metadata(),Q=w.width||1920,J=w.height||1080,X=FT0(Q,J,$);return await Hw(W,{limitInputPixels:!1}).composite([{input:Buffer.from(X),top:0,left:0}]).toColorspace("srgb").resize(16383,16383,{fit:"inside",withoutEnlargement:!0}).webp({quality:85}).toBuffer()}async overlayAnnotations(W){let $=process.env.S3_BUCKET||"shumai",w=`annotation-${l1()}.webp`,Q=this.createTempDir("annotation-"),J=UW.join(Q,UW.basename(W.assetKey));try{await t0.downloadToFile($,W.assetKey,J);let X=g1.readFileSync(J),Z=await this.overlayAnnotationsOnBuffer(X,W.annotations),Y=`files/${W.assetId}/annotations/${w}`;return await t0.putObject($,Y,Z,Z.length,"image/webp"),Y}finally{this.removeDir(Q)}}}function FT0(W,$,w){let Q=Math.max(2,Math.round(Math.max(W,$)*0.004)),J=[];for(let X of w){let Z=X.color||"#ff0000";switch(X.type){case"box":{if(X.points.length<2)continue;let[K,V]=X.points,z=Math.min(K[0],V[0])*W,H=Math.min(K[1],V[1])*$,G=Math.abs(V[0]-K[0])*W,M=Math.abs(V[1]-K[1])*$;J.push(`<rect x="${z}" y="${H}" width="${G}" height="${M}" stroke="${Z}" stroke-width="${Q}" fill="none" />`);break}case"line":case"freehand":{if(X.points.length<2)continue;let K=X.points.map(([V,z])=>`${V*W},${z*$}`).join(" ");J.push(`<polyline points="${K}" stroke="${Z}" stroke-width="${Q}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`);break}case"arrow":{if(X.points.length<2)continue;let K=X.points.map(([B,L])=>[B*W,L*$]),V=K.map(([B,L])=>`${B},${L}`).join(" ");J.push(`<polyline points="${V}" stroke="${Z}" stroke-width="${Q}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`);let z=K[K.length-1],H=K[K.length-2],G=z[0]-H[0],M=z[1]-H[1],U=Math.atan2(M,G),N=Math.max(12,Math.max(W,$)*0.015),D=z[0]-N*Math.cos(U-Math.PI/6),R=z[1]-N*Math.sin(U-Math.PI/6),T=z[0]-N*Math.cos(U+Math.PI/6),O=z[1]-N*Math.sin(U+Math.PI/6);J.push(`<polygon points="${z[0]},${z[1]} ${D},${R} ${T},${O}" fill="${Z}" />`);break}}}return`<svg width="${W}" height="${$}" viewBox="0 0 ${W} ${$}" xmlns="http://www.w3.org/2000/svg">${J.join(`
|
|
1302
|
+
`,X),Buffer.from("\r",X)];W:for(let Y=0;Y<Z.length;Y++){let K=Z[Y].length;for(let V=0;V<K;V++)if(Z[Y][V]!==Q[J+V])continue W;return this.options.record_delimiter.push(Z[Y]),this.state.recordDelimiterMaxLength=Z[Y].length,Z[Y].length}return 0},__error:function(Q){let{encoding:J,raw:X,skip_records_with_error:Z}=this.options,Y=typeof Q==="string"?Error(Q):Q;if(Z){if(this.state.recordHasError=!0,this.options.on_skip!==void 0)try{this.options.on_skip(Y,X?this.state.rawBuffer.toString(J):void 0)}catch(K){return K}return}else return Y},__infoDataSet:function(){return{...this.info,columns:this.options.columns}},__infoRecord:function(){let{columns:Q,raw:J,encoding:X}=this.options;return{...this.__infoDataSet(),bytes_records:this.info.bytes,error:this.state.error,header:Q===!0,index:this.state.record.length,raw:J?this.state.rawBuffer.toString(X):void 0}},__infoField:function(){let{columns:Q}=this.options,J=Array.isArray(Q),X=this.info.bytes_records;return{...this.__infoRecord(),bytes_records:X,column:J===!0?Q.length>this.state.record.length?Q[this.state.record.length].name:null:this.state.record.length,quoting:this.state.wasQuoting}}}};var Xn=function(W,$={}){if(typeof W==="string")W=Buffer.from(W);let w=$&&$.objname?Object.create(null):[],Q=oq($),J=(Y)=>{if(Q.options.objname===void 0)w.push(Y);else w[Y[0]]=Y[1]},X=()=>{},Z=Q.parse(W,!0,J,X);if(Z!==void 0)throw Z;return w};import*as g1 from"fs";import*as Vn from"os";import*as UW from"path";import Zn from"pdfkit";import Hw from"sharp";import{promisify as OT0}from"util";var bT={apch:"Apple ProRes 422 High Quality",apcn:"Apple ProRes 422 Standard Definition",apcs:"Apple ProRes 422 LT",apco:"Apple ProRes 422 Proxy",ap4h:"Apple ProRes 4444",jpeg:"JPEG Image","3gvo":"3GPP Video Orientation",a3d1:"Multiview Video Coding",a3d2:"Multiview Video Coding",a3d3:"Multiview Video Coding",a3d4:"Multiview Video Coding",a3ds:"Auro-Cx 3D audio","ac-3":"AC-3 audio","ac-4":"AC-4 audio",alac:"Apple lossless audio codec",alaw:"a-Law",av01:"AV1 video",avc1:"Advanced Video Coding",avc2:"Advanced Video Coding",avc3:"Advanced Video Coding",avc4:"Advanced Video Coding",avcp:"Advanced Video Coding Parameters",dra1:"DRA Audio",drac:"Dirac Video Coder","dts-":"Dependent base layer for DTS layered audio","dts+":"Enhancement layer for DTS layered audio",dtsc:"DTS Coherent Acoustics audio",dtse:"DTS Express low bit rate audio, also known as DTS LBR",dtsh:"DTS-HD High Resolution Audio",dtsl:"DTS-HD Master Audio",dtsx:"DTS:X",dvav:"AVC-based \u201CDolby Vision\u201D",dvhe:"HEVC-based \u201CDolby Vision\u201D","ec-3":"Enhanced AC-3 audio",enca:"Encrypted/Protected audio",encf:"Encrypted/Protected font",encm:"Encrypted/Protected metadata stream",encs:"Encrypted Systems stream",enct:"Encrypted Text",encv:"Encrypted/protected video",fdp:"File delivery hints",fLaC:"Fres Lossless Audio Codec",g719:"ITU-T Recommendation G.719 (2008)",g726:"ITU-T Recommendation G.726 (1990)",hev1:"High Efficiency Video Coding",hvc1:"High Efficiency Video Coding",hvt1:"High Efficiency Video Coding",ixse:"DVB Track Level Index Track",lhe1:"Layered High Efficiency Video Coding",lht1:"Layered High Efficiency Video Coding",lhv1:"Layered High Efficiency Video Coding",m2ts:"MPEG-2 transport stream for DMB",m4ae:"MPEG-4 Audio Enhancement MP4v1/2",mett:"Text timed metadata that is not XML",metx:"XML timed metadata",mha1:"MPEG-H Audio (single stream, uncapsulated)",mha2:"MPEG-H Audio (multi-stream, unencapsulated)",mhm1:"MPEG-H Audio (single stream, MHAS encapsulated)",mhm2:"MPEG-H Audio (multi-stream, MHAS encapsulated)",mjp2:"Motion JPEG 2000",mlix:"DVB Movie level index track",mlpa:"MLP Audio",mp4a:"MPEG-4 Audio",mp4s:"MPEG-4 Systems",mp4v:"MPEG-4 Visual",mvc1:"Multiview coding",mvc2:"Multiview coding",mvc3:"Multiview coding",mvc4:"Multiview coding",mvd1:"Multiview coding",mvd2:"Multiview coding",mvd3:"Multiview coding",mvd4:"Multiview coding",oksd:"OMA Keys",Opus:"Opus audio coding",pm2t:"Protected MPEG-2 Transport",prtp:"Protected RTP Reception",raw:"Uncompressed audio",resv:"Restricted Video",rm2t:"MPEG-2 Transport Reception",rrtp:"RTP reception",rsrp:"SRTP Reception",rtmd:"Real Time Metadata Sample Entry(XAVC Format)",rtp:"RTP Hints",s263:"ITU H.263 video (3GPP format)",samr:"Narrowband AMR voice",sawb:"Wideband AMR voice",sawp:"Extended AMR-WB (AMR-WB+)",sevc:"EVRC Voice",sm2t:"MPEG-2 Transport Server",sqcp:"13K Voice",srtp:"SRTP Hints",ssmv:"SMV Voice",STGS:"Subtitle Sample Entry (HMMP)",stpp:"Subtitles (Timed Text)",svc1:"Scalable Video Coding",svc2:"Scalable Video Coding",svcM:"SVC Metadata",tc64:"64 bit timecode samples",tmcd:"32 bit timecode samples",twos:"Uncompressed 16-bit audio",tx3g:"Timed Text stream",ulaw:"Samples have been compressed using uLaw 2:1.",unid:"Dynamic Range Control (DRC) data",urim:"Binary timed metadata identified by URI","vc-1":"SMPTE VC-1",vp08:"VP8 video",vp09:"VP9 video",wvtt:"WebVTT"};var $6=OT0(DT0);function Yn(){let W=[...process.env.PDF_CJK_FONT_PATH?[{fontPath:process.env.PDF_CJK_FONT_PATH,fontName:process.env.PDF_CJK_FONT_NAME}]:[],{fontPath:"/System/Library/Fonts/Supplemental/Arial Unicode.ttf"},{fontPath:"/Library/Fonts/Arial Unicode.ttf"},{fontPath:"/System/Library/Fonts/PingFang.ttc",fontName:"PingFangSC-Regular"},{fontPath:"/System/Library/Fonts/STHeiti Light.ttc",fontName:"STHeitiSC-Light"},{fontPath:"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",fontName:"NotoSansCJKsc-Regular"},{fontPath:"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",fontName:"NotoSansCJKsc-Regular"},{fontPath:"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",fontName:"WenQuanYiZenHei"},{fontPath:"/usr/share/fonts/truetype/arphic/ukai.ttc",fontName:"AR-PL-UKai-CN"},{fontPath:"/usr/share/fonts/noto/NotoSansCJK-Regular.ttc",fontName:"Noto Sans CJK SC"},{fontPath:"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf"},{fontPath:"/usr/share/fonts/truetype/droid/DroidSansFallback.ttf"},{fontPath:"/usr/share/fonts/google-droid/DroidSansFallback.ttf"},{fontPath:"C:\\Windows\\Fonts\\msyh.ttc",fontName:"MicrosoftYaHei"},{fontPath:"C:\\Windows\\Fonts\\simsun.ttc",fontName:"SimSun"},{fontPath:"C:\\Windows\\Fonts\\simhei.ttf"}];for(let $ of W)if(g1.existsSync($.fontPath))return $;return}function RT0(W){try{return Xn(W,{skip_empty_lines:!0,relax_column_count:!0,relax_quotes:!0,trim:!0,delimiter_auto:!0})}catch{return W.split(/\r?\n/).filter(($)=>$.trim().length>0).map(($)=>$.split(",").map((w)=>w.trim()))}}function Kn(W){if(typeof W==="string"){if(W.toLowerCase().endsWith(".psd"))return!0;if(g1.existsSync(W))try{let $=g1.openSync(W,"r"),w=Buffer.alloc(4);return g1.readSync($,w,0,4,0),g1.closeSync($),w.toString("ascii")==="8BPS"}catch{return!1}return!1}return W.length>=4&&W[0]===56&&W[1]===66&&W[2]===80&&W[3]===83}class zn{prismaClient;constructor(W=g){this.prismaClient=W}async execImageMagick(W){try{return await $6("magick",W)}catch($){if($?.code==="ENOENT")return await $6("convert",W);throw $}}async execImageMagickIdentify(W){let $=`${W}[0]`,w;try{w=(await $6("magick",["identify","-format","%w %h",$])).stdout}catch(Z){if(Z?.code==="ENOENT")w=(await $6("identify",["-format","%w %h",$])).stdout;else throw Z}let Q=w.trim().split(/\s+/),J=parseInt(Q[0],10)||0,X=parseInt(Q[1],10)||0;return{width:J,height:X}}resolveCodecName(W){let $=W.mime_codec_string||W.tags?.mime_codec_string;if($&&typeof $==="string"){let w=$.split(".")[0];if(bT[w])return bT[w]}return W.codec_name}safeParseInt(W){if(W===void 0||W===null)return;let $=typeof W==="string"?parseInt(W,10):W;return Number.isFinite($)?$:void 0}async getVideoInfo(W){let{stdout:$}=await $6("ffprobe",["-v","quiet","-print_format","json","-show_format","-show_streams",W]),w=JSON.parse($),Q=w.streams.find((V)=>V.codec_type==="video"),J=w.streams.find((V)=>V.codec_type==="audio");if(!Q)throw Error("No video stream found");let X=0;if(Q.avg_frame_rate){let V=Q.avg_frame_rate.split("/");if(V.length===2){let z=parseFloat(V[0]),H=parseFloat(V[1]);if(H>0)X=z/H}}if(X===0&&Q.r_frame_rate){let V=Q.r_frame_rate.split("/");if(V.length===2){let z=parseFloat(V[0]),H=parseFloat(V[1]);if(H>0)X=z/H}}let Z=parseFloat(w.format.duration),Y=0;if(Q.nb_frames)Y=parseInt(Q.nb_frames,10);if(!Y&&X>0&&!isNaN(Z))Y=Math.round(Z*X);let K=Q.tags?.timecode||w.format?.tags?.timecode;return{originalWidth:Q.width,originalHeight:Q.height,duration:Z,bitRate:parseFloat(w.format.bit_rate),frameRate:X||30,totalFrames:Y||0,startTimecode:K,hasAudio:!!J,videoCodec:this.resolveCodecName(Q),audioCodec:J?this.resolveCodecName(J):void 0,audioChannels:J?.channels,audioSampleRate:this.safeParseInt(J?.sample_rate),audioBitDepth:this.safeParseInt(J?.bits_per_raw_sample)??this.safeParseInt(J?.bits_per_sample),mimeType:""}}async getImageInfo(W){let $=W,w=null;if(W.startsWith("http")){let J=await fetch(W);if(!J.ok)throw Error(`Failed to fetch image from ${W}: ${J.statusText}`);$=Buffer.from(await J.arrayBuffer())}if(Kn($)){let J;if(typeof $==="string")J=$;else w=this.createTempDir("psd-info-"),J=UW.join(w,"input.psd"),g1.writeFileSync(J,$);try{let{width:X,height:Z}=await this.execImageMagickIdentify(J);return{originalWidth:X,originalHeight:Z,duration:0,bitRate:0,frameRate:0,totalFrames:0,startTimecode:void 0,hasAudio:!1,mimeType:"psd"}}catch(X){console.warn("ImageMagick identify failed for PSD, falling back to sharp:",X)}finally{if(w)this.removeDir(w)}}let Q=await Hw($,{limitInputPixels:!1}).metadata();return{originalWidth:Q.width||0,originalHeight:Q.height||0,duration:0,bitRate:0,frameRate:0,totalFrames:0,startTimecode:void 0,hasAudio:!1,mimeType:Q.format||""}}async transcodeVideo(W){let $=`[0:v]scale=w=${W.width}:h=${W.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`;if(W.frameRate)$+=`,fps=${W.frameRate}`;$+="[vout]";let w=["-i",W.inputFile,"-filter_complex",$,"-map","[vout]"];if(W.frameRate){let Q;if(typeof W.frameRate==="number")Q=W.frameRate;else{let J=W.frameRate.split("/");if(J.length===2)Q=parseFloat(J[0])/parseFloat(J[1]);else Q=parseFloat(W.frameRate)}if(Number.isFinite(Q)&&Q>0){let J=Math.max(1,Math.round(Q));w.push("-r",Q.toString(),"-g",J.toString(),"-force_key_frames","expr:gte(t,n_forced*1)")}}if(!W.disableAudio)w.push("-map","0:a?");if(w.push("-c:v","libx264","-preset","fast","-crf","26"),!W.disableAudio)w.push("-c:a","aac","-b:a","128k");w.push("-movflags","+faststart","-max_muxing_queue_size","1024",W.outputFile),await $6("ffmpeg",["-y","-loglevel","warning",...w])}async transcodeImage(W,$,w,Q,J=null){let X=W;if(typeof W==="string"&&W.startsWith("http")){let z=await fetch(W);if(!z.ok)throw Error(`Failed to fetch image from ${W}: ${z.statusText}`);X=Buffer.from(await z.arrayBuffer())}let Z=7680,Y=w>0?Math.min(w,Z):Z,K=J&&J>0?Math.min(J,Z):Z;if(Kn(X)){let z,H=null;if(typeof X==="string")z=X;else H=this.createTempDir("psd-transcode-"),z=UW.join(H,"input.psd"),g1.writeFileSync(z,X);try{let G=K<Z?`${Y}x${K}>`:`${Y}x${Z}>`;await this.execImageMagick([`${z}[0]`,"-colorspace","sRGB","-resize",G,"-quality",Q.toString(),$]);return}finally{if(H)this.removeDir(H)}}let V=Hw(X,{limitInputPixels:!1});V.toColorspace("srgb").resize(Y,K,{withoutEnlargement:!0,fit:"inside"}),await V.webp({quality:Q}).toFile($)}async generateSprite(W,$,w,Q){let X=`[0:v]fps=${100/Q},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:480:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`;await $6("ffmpeg",["-y","-loglevel","warning",...["-i",W,"-filter_complex",X,"-map","[sprite_out]","-frames:v","1","-c:v","libwebp","-q:v","75",$,"-map","[thumb_out]","-c:v","libwebp","-q:v","75","-frames:v","1","-max_muxing_queue_size","1024",w]])}async generatePdfSprite(W,$,w){let Q=this.createTempDir("pdf-sprite-");try{let J=UW.join(Q,"page");try{await $6("pdftoppm",["-png","-f","1","-l","100",W,J])}catch(M){let U=M?.code,N=M instanceof Error?M.message:String(M),D=N.toLowerCase();if(U==="ENOENT"||D.includes("enoent")||D.includes("not found")&&D.includes("pdftoppm"))throw Error(`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${N})`,{cause:M});throw M}let X=g1.readdirSync(Q).filter((M)=>M.endsWith(".png"));if(X.length===0)throw Error("pdftoppm produced no image outputs");X.sort((M,U)=>{let N=parseInt(M.replace(/[^0-9]/g,""),10),D=parseInt(U.replace(/[^0-9]/g,""),10);return N-D});let Z=X.length,Y=UW.join(Q,X[0]),K=await Hw(Y,{limitInputPixels:!1}).metadata(),V=K.width||800,z=K.height||1000;for(let M=1;M<=100;M++){let U=Math.min(Z-1,Math.floor((M-1)*Z/100)),N=UW.join(Q,X[U]),D=UW.join(Q,`frame_${M}.png`);if(N!==D)g1.copyFileSync(N,D)}let H=["-i",UW.join(Q,"frame_%d.png"),"-filter_complex","scale=w=480:h=-2,tile=10x10","-frames:v","1","-c:v","libwebp","-q:v","75",$];await $6("ffmpeg",["-y","-loglevel","warning",...H]),await Hw(Y,{limitInputPixels:!1}).toColorspace("srgb").resize(480,null,{withoutEnlargement:!0,fit:"inside"}).webp({quality:75}).toFile(w);let G=Z;try{let{stdout:M}=await $6("pdfinfo",[W]),U=M.match(/Pages:\s+(\d+)/);if(U)G=parseInt(U[1],10)}catch{}return{pageCount:G,originalWidth:V,originalHeight:z}}finally{this.removeDir(Q)}}async getPdfInfo(W){let $=this.createTempDir("pdf-info-"),w=800,Q=1000,J=1;try{let X=UW.join($,"page");await $6("pdftoppm",["-png","-f","1","-l","1",W,X]);let Z=g1.readdirSync($).filter((Y)=>Y.endsWith(".png"));if(Z.length>0){let Y=await Hw(UW.join($,Z[0]),{limitInputPixels:!1}).metadata();w=Y.width||800,Q=Y.height||1000}}catch(X){console.warn("pdftoppm not available for PDF dimensions extraction:",X)}try{let{stdout:X}=await $6("pdfinfo",[W]),Z=X.match(/Pages:\s+(\d+)/);if(Z)J=parseInt(Z[1],10)}catch{}finally{this.removeDir($)}return{originalWidth:w,originalHeight:Q,duration:0,bitRate:0,frameRate:0,totalFrames:J,hasAudio:!1,mimeType:"application/pdf"}}async generatePdfFromText(W,$){let w=g1.readFileSync(W,"utf-8"),J=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\uac00-\ud7af]/.test(w)?Yn():void 0;return new Promise((X,Z)=>{let Y=new Zn({size:"A4",margin:40,bufferPages:!0}),K=g1.createWriteStream($);if(Y.pipe(K),J)if(J.fontName!==void 0)Y.font(J.fontPath,J.fontName);else Y.font(J.fontPath);else Y.font("Helvetica");Y.fontSize(10),Y.text(w,{lineGap:3,paragraphGap:4}),Y.end(),K.on("finish",()=>X()),K.on("error",(V)=>Z(V))})}async generatePdfFromCsv(W,$){let w=g1.readFileSync(W,"utf-8"),Q=RT0(w),X=/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\uac00-\ud7af]/.test(w)?Yn():void 0;if(Q.length===0)Q.push(["(Empty CSV)"]);let Z=Math.max(...Q.map((K)=>K.length)),Y=Z>5;return new Promise((K,V)=>{let z=new Zn({size:"A4",layout:Y?"landscape":"portrait",margin:30,bufferPages:!0}),H=g1.createWriteStream($);z.pipe(H);let G=()=>{if(X)if(X.fontName!==void 0)z.font(X.fontPath,X.fontName);else z.font(X.fontPath);else z.font("Helvetica");z.fontSize(9)};G();let M=z.page.width-z.page.margins.left-z.page.margins.right,U=Math.max(40,M/Z),N=z.page.margins.left,D=z.page.margins.top,R=20,T=(B,L,C)=>{if(L)z.rect(N,C,U*Z,R).fill("#e0e0e0"),z.fillColor("#000000");for(let f=0;f<Z;f++){let x=B[f]||"",k=N+f*U;z.rect(k,C,U,R).stroke("#cccccc"),z.fillColor("#000000").text(x,k+4,C+5,{width:U-8,height:R-6,ellipsis:!0})}},O=Q[0];T(O,!0,D),D+=R;for(let B=1;B<Q.length;B++){if(D+R>z.page.height-z.page.margins.bottom)z.addPage(),G(),D=z.page.margins.top,T(O,!0,D),D+=R;T(Q[B],!1,D),D+=R}z.end(),H.on("finish",()=>K()),H.on("error",(B)=>V(B))})}async extractAudio(W,$,w){await $6("ffmpeg",["-y","-loglevel","warning",...["-i",W,"-vn","-acodec","libmp3lame","-b:a",w,$]])}async getAudioInfo(W){let{stdout:$}=await $6("ffprobe",["-v","quiet","-print_format","json","-show_format","-show_streams",W]),w=JSON.parse($),Q=w.streams.find((X)=>X.codec_type==="audio");if(!Q)throw Error("No audio stream found");let J=parseFloat(w.format.duration);return{originalWidth:0,originalHeight:0,duration:isNaN(J)?0:J,bitRate:parseFloat(w.format.bit_rate)||0,frameRate:0,totalFrames:0,startTimecode:void 0,hasAudio:!0,videoCodec:void 0,audioCodec:this.resolveCodecName(Q),audioChannels:Q?.channels,audioSampleRate:this.safeParseInt(Q?.sample_rate),audioBitDepth:this.safeParseInt(Q?.bits_per_raw_sample)??this.safeParseInt(Q?.bits_per_sample),mimeType:""}}async transcodeAudio(W){let $=W.bitrate||"128k",w=["-i",W.inputFile,"-vn","-c:a","aac","-b:a",$,"-ac","2",W.outputFile];await $6("ffmpeg",["-y","-loglevel","warning",...w])}async extractVideoFrames(W){if(W.isImage){let Z=UW.join(W.outputDir,"1.webp");return await this.transcodeImage(W.inputFile,Z,-1,80,W.frameHeight),[Z]}let $=await this.getVideoInfo(W.inputFile),w=W.numFrames/$.duration,Q=UW.join(W.outputDir,"%d.webp"),J=["-i",W.inputFile,"-vf",`fps=${w},scale=-2:${W.frameHeight}`,"-c:v","libwebp","-q:v","80",Q];return await $6("ffmpeg",["-y","-loglevel","warning",...J]),g1.readdirSync(W.outputDir).filter((Z)=>Z.endsWith(".webp")).sort((Z,Y)=>{let K=parseInt(UW.basename(Z,".webp")),V=parseInt(UW.basename(Y,".webp"));return K-V}).map((Z)=>UW.join(W.outputDir,Z))}createTempDir(W){return g1.mkdtempSync(UW.join(Vn.tmpdir(),W))}removeDir(W){g1.rmSync(W,{recursive:!0,force:!0})}async createVideoTranscodeTask(W,$,w){return this.prismaClient.workflowTask.create({data:{assetId:W,projectId:$,type:l5.transcode_video,status:v1.pending,payload:{projectId:$,transcode:w}}})}async createImageTranscodeTask(W,$,w){return this.prismaClient.workflowTask.create({data:{assetId:W,projectId:$,type:l5.transcode_image,status:v1.pending,payload:{projectId:$,transcode:w}}})}async takeScreenshots(W){let $=process.env.S3_BUCKET||"shumai",w=this.createTempDir("screenshot-"),Q=UW.join(w,UW.basename(W.assetKey));try{await t0.downloadToFile($,W.assetKey,Q);let J=[];if(W.count<=1)J=[W.start];else{let K=(W.end-W.start)/W.count;J=Array.from({length:W.count},(V,z)=>W.start+z*K)}let X=W.commentTimestamp,Z=0.1;if(X!==void 0&&X!==null){if(X>=W.start-Z&&X<=W.end+Z){let V=0,z=Math.abs(J[0]-X);for(let H=1;H<J.length;H++){let G=Math.abs(J[H]-X);if(G<z)z=G,V=H}J[V]=X}}let Y=[];for(let K of J){let V=`shot-${K.toFixed(3)}-${l1()}.webp`,z=UW.join(w,V),H=["-ss",K.toFixed(3),"-i",Q,"-vframes","1","-vf","scale=-2:720","-c:v","libwebp","-q:v","80",z];if(await $6("ffmpeg",["-y","-loglevel","warning",...H]),X!==void 0&&X!==null&&Math.abs(K-X)<0.0001&&W.annotations&&W.annotations.length>0){let N=g1.readFileSync(z),D=await this.overlayAnnotationsOnBuffer(N,W.annotations);g1.writeFileSync(z,D)}let M=`files/${W.assetId}/screenshots/${V}`,U=g1.readFileSync(z);await t0.putObject($,M,U,U.length,"image/webp"),Y.push({key:M,timestamp:K})}return Y}finally{this.removeDir(w)}}async renderPdfPages(W){let $=process.env.S3_BUCKET||"shumai",w=this.createTempDir("pdf-pages-"),Q=UW.join(w,UW.basename(W.assetKey));try{await t0.downloadToFile($,W.assetKey,Q);let J=UW.join(w,"page");try{await $6("pdftoppm",["-png","-f",W.start.toString(),"-l",W.end.toString(),Q,J])}catch(K){let V=K?.code,z=K instanceof Error?K.message:String(K),H=z.toLowerCase();if(V==="ENOENT"||H.includes("enoent")||H.includes("not found")&&H.includes("pdftoppm"))throw Error(`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${z})`,{cause:K});throw K}let X=g1.readdirSync(w).filter((K)=>K.endsWith(".png"));if(X.length===0)throw Error("pdftoppm produced no image outputs");X.sort((K,V)=>{let z=parseInt(K.replace(/[^0-9]/g,""),10),H=parseInt(V.replace(/[^0-9]/g,""),10);return z-H});let Z=[],Y=jT(W.assetKey);for(let K=0;K<X.length;K++){let V=W.start+K,z=UW.join(w,X[K]),H=`${Y}-page-${V}-${l1()}.webp`,G=await Hw(z,{limitInputPixels:!1}).toColorspace("srgb").resize(1920,1080,{fit:"inside",withoutEnlargement:!1}).webp({quality:85}).toBuffer(),M=W.commentTimestamp!==void 0&&W.commentTimestamp!==null?Math.round(W.commentTimestamp):null;if(M!==null&&V===M&&W.annotations&&W.annotations.length>0)G=await this.overlayAnnotationsOnBuffer(G,W.annotations);let U=`files/${W.assetId}/pdf_pages/${H}`;await t0.putObject($,U,G,G.length,"image/webp"),Z.push({key:U,page:V})}return Z}finally{this.removeDir(w)}}async overlayAnnotationsOnBuffer(W,$){if(!$||$.length===0)return W;let w=await Hw(W,{limitInputPixels:!1}).metadata(),Q=w.width||1920,J=w.height||1080,X=FT0(Q,J,$);return await Hw(W,{limitInputPixels:!1}).composite([{input:Buffer.from(X),top:0,left:0}]).toColorspace("srgb").resize(16383,16383,{fit:"inside",withoutEnlargement:!0}).webp({quality:85}).toBuffer()}async overlayAnnotations(W){let $=process.env.S3_BUCKET||"shumai",w=`annotation-${l1()}.webp`,Q=this.createTempDir("annotation-"),J=UW.join(Q,UW.basename(W.assetKey));try{await t0.downloadToFile($,W.assetKey,J);let X=g1.readFileSync(J),Z=await this.overlayAnnotationsOnBuffer(X,W.annotations),Y=`files/${W.assetId}/annotations/${w}`;return await t0.putObject($,Y,Z,Z.length,"image/webp"),Y}finally{this.removeDir(Q)}}}function FT0(W,$,w){let Q=Math.max(2,Math.round(Math.max(W,$)*0.004)),J=[];for(let X of w){let Z=X.color||"#ff0000";switch(X.type){case"box":{if(X.points.length<2)continue;let[K,V]=X.points,z=Math.min(K[0],V[0])*W,H=Math.min(K[1],V[1])*$,G=Math.abs(V[0]-K[0])*W,M=Math.abs(V[1]-K[1])*$;J.push(`<rect x="${z}" y="${H}" width="${G}" height="${M}" stroke="${Z}" stroke-width="${Q}" fill="none" />`);break}case"line":case"freehand":{if(X.points.length<2)continue;let K=X.points.map(([V,z])=>`${V*W},${z*$}`).join(" ");J.push(`<polyline points="${K}" stroke="${Z}" stroke-width="${Q}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`);break}case"arrow":{if(X.points.length<2)continue;let K=X.points.map(([B,L])=>[B*W,L*$]),V=K.map(([B,L])=>`${B},${L}`).join(" ");J.push(`<polyline points="${V}" stroke="${Z}" stroke-width="${Q}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`);let z=K[K.length-1],H=K[K.length-2],G=z[0]-H[0],M=z[1]-H[1],U=Math.atan2(M,G),N=Math.max(12,Math.max(W,$)*0.015),D=z[0]-N*Math.cos(U-Math.PI/6),R=z[1]-N*Math.sin(U-Math.PI/6),T=z[0]-N*Math.cos(U+Math.PI/6),O=z[1]-N*Math.sin(U+Math.PI/6);J.push(`<polygon points="${z[0]},${z[1]} ${D},${R} ${T},${O}" fill="${Z}" />`);break}}}return`<svg width="${W}" height="${$}" viewBox="0 0 ${W} ${$}" xmlns="http://www.w3.org/2000/svg">${J.join(`
|
|
1303
1303
|
`)}</svg>`}var gT=new zn;import{ApplicationFailure as Rl5}from"@temporalio/activity";import{execFile as TT0}from"child_process";import{promisify as BT0}from"util";var Bl5=BT0(TT0);import{ApplicationFailure as Cl5}from"@temporalio/workflow";import{ApplicationFailure as ll5}from"@temporalio/workflow";import{ApplicationFailure as sl5}from"@temporalio/workflow";import{ApplicationFailure as Qi5}from"@temporalio/workflow";class rq{db;assetId;teamId;projectId;spec={};constructor(W,$,w,Q){this.db=W;this.assetId=$;this.teamId=w;this.projectId=Q}setStrategy(W){return this.spec.videoStrategy=W,this}withSprite(){return this.spec.sprite=!0,this}withPoster(){return this.spec.poster=!0,this}async submit(){return(await this.db.workflowTask.create({data:{assetId:this.assetId,teamId:this.teamId,projectId:this.projectId,type:l5.transcode_video,status:v1.pending,payload:{projectId:this.projectId,transcode:this.spec}}})).id}}class kT{db;assetId;teamId;projectId;spec={};constructor(W,$,w,Q){this.db=W;this.assetId=$;this.teamId=w;this.projectId=Q}withThumbnail(){return this.spec.thumbnail=!0,this}async submit(){return(await this.db.workflowTask.create({data:{assetId:this.assetId,teamId:this.teamId,projectId:this.projectId,type:l5.transcode_image,status:v1.pending,payload:{projectId:this.projectId,transcode:this.spec}}})).id}}class mT{db;assetId;teamId;projectId;spec={};constructor(W,$,w,Q){this.db=W;this.assetId=$;this.teamId=w;this.projectId=Q}withSprite(){return this.spec.sprite=!0,this}withPoster(){return this.spec.poster=!0,this}async submit(){return(await this.db.workflowTask.create({data:{assetId:this.assetId,teamId:this.teamId,projectId:this.projectId,type:l5.transcode_pdf,status:v1.pending,payload:{projectId:this.projectId,transcode:this.spec}}})).id}}class Gn{prismaClient;constructor(W=g){this.prismaClient=W}async createUploadTask(W,$){let w=$.files.filter((G)=>!G.name.startsWith(".")),Q=w.length===1?w[0].name:`${w.length} Items`,J=0,X=(G)=>{for(let M of G){if(M.name.startsWith("."))continue;if(M.type==="file")J++;else X(M.children)}};X($.files);let Z=await this.prismaClient.task.create({data:{creatorId:W,type:"upload",name:Q,total:J,status:vK.pending}}),Y=await this.prismaClient.asset.findUnique({where:{id:$.parentId},include:{project:!0}});if(!Y)throw Error("Parent asset not found");if(!Y.projectId)throw Error("Parent asset has no project");let K=[],V=Y.type===r0.file,z=V?Y.parentId:Y.id,H=[];return await this.prismaClient.$transaction(async(G)=>{let M=await this.createAssetsRecursively(G,W,Z.id,Y.projectId,z,$.files,K,H);if(V&&M.length>0)for(let U of M)await Q$.reparentAssets({assetIds:[U],newParentId:Y.id,creatorId:W},G);return M}),{taskId:Z.id,presignedUrls:K,createdAssets:H}}async createAssetsRecursively(W,$,w,Q,J,X,Z,Y){let V=(await W.asset.findFirst({where:{parentId:J},orderBy:{sortIndex:"asc"}}))?.sortIndex||void 0,z=[];for(let H of X){if(H.name.startsWith("."))continue;let G=w$(null,V||null);V=G;let M=H.type==="folder"?r0.folder:r0.file,U=null;if(M===r0.file)U=`files/${l1()}/${dJ(H.name)}`;let N=H.mediaType;if(N&&H.name.toLowerCase().endsWith(".wma")&&N.startsWith("video/"))N=N.replace(/^video\//,"audio/");let D=await W.asset.create({data:{name:H.name,type:M,storageKey:U?{create:{key:U}}:void 0,sortIndex:G,mediaType:N,status:M===r0.folder?hw.uploaded:hw.uploading,sizeByte:H.size,creator:$?{connect:{id:$}}:void 0,parent:J?{connect:{id:J}}:void 0,project:{connect:{id:Q}},task:{connect:{id:w}}}});if(z.push(D.id),Y.push({tempId:H.id,assetId:D.id}),M===r0.folder&&J)await W.asset.update({where:{id:J},data:{fileCount:{increment:1}}});if(H.children&&H.children.length>0)await this.createAssetsRecursively(W,$,w,Q,D.id,H.children,Z,Y);else if(M===r0.file&&U){let R=await t0.presign(process.env.S3_BUCKET||"shumai",U,"PUT");Z.push({id:H.id,fileId:D.id,url:R})}}return z}async confirmFileUpload(W,$,w){let Q=await this.prismaClient.asset.findUnique({where:{id:w.fileId},include:{storageKey:!0,project:{include:{team:!0}}}});if(!Q)throw Error("Asset not found");if(!Q.project)throw Error("Project not found for asset");let J=Q.storageKey?.key;if(!J)throw Error("Asset has no key");if(w.errorMessage){if(await this.prismaClient.asset.delete({where:{id:Q.id}}),await this.prismaClient.task.findUnique({where:{id:$}})){let K=await this.prismaClient.task.update({where:{id:$},data:{uploaded:{increment:1}}});if(K.uploaded===K.total)await this.prismaClient.task.update({where:{id:$},data:{status:vK.completed}})}return}let X=await t0.getObjectSize(process.env.S3_BUCKET||"shumai",J),Z=Q.project;await this.prismaClient.$transaction(async(Y)=>{let K=Q.mediaType;if(!K||K==="application/octet-stream")K=Bun.file(Q.name).type||"application/octet-stream";let V=await Y.asset.update({where:{id:Q.id},data:{status:hw.uploaded,sizeByte:X,mediaType:K}});if(Q.parentId)await Y.asset.update({where:{id:Q.parentId},data:{fileCount:{increment:1}}}),await Q$.updateAncestorsSize(Y,Q.parentId,V.sizeByte);let z=await Y.task.update({where:{id:$},data:{uploaded:{increment:1}}});if(z.uploaded===(z.total||0))await Y.task.update({where:{id:$},data:{status:vK.completed}});let H=Z.team;if(!H)return;if(!Q.projectId)throw Error("Asset project ID is missing");await this.triggerPostUploadWorkflows(Y,Q.id,H.id,Q.projectId)})}async triggerPostUploadWorkflows(W,$,w,Q){let J=await W.asset.findUnique({where:{id:$}});if(!J)throw Error("Asset not found");let X=await W.team.findUnique({where:{id:w}});if(!X)throw Error("Team not found");let Z=await W.agent.findFirst({where:{type:"autofill",enabled:!0,user:{teamMembers:{some:{teamId:X.id}}}}}),Y=J.media?.proxyType||PT(J.mediaType,J.name),K=Y==="video",V=Y==="image",z=Y==="audio",H=Y==="pdf";if(Z&&(K||V))await W.workflowTask.create({data:{assetId:J.id,type:l5.ai_metadata_autofill,status:v1.pending,teamId:X.id,projectId:Q,payload:{projectId:Q,agent:{agentId:Z.id}}}});if(!Y)await W.asset.update({where:{id:J.id},data:{status:hw.processed}});else{let G=X.settings;if(K){let M=G?.transcode?.videoStrategy||"best_match";await new rq(W,J.id,X.id,Q).setStrategy(M).withSprite().withPoster().submit()}else if(z)await new rq(W,J.id,X.id,Q).submit();else if(V)await new kT(W,J.id,X.id,Q).withThumbnail().submit();else if(H)await new mT(W,J.id,X.id,Q).withSprite().withPoster().submit()}}async listUploadTasks(W,$){let w={creatorId:W,type:"upload"},{data:Q,pageInfo:J}=await d4(async(Z,Y)=>{return this.prismaClient.task.findMany({where:w,orderBy:{id:"desc"},skip:Z,take:Y})},async()=>this.prismaClient.task.count({where:w}),$);return{data:Q.map((Z)=>({id:Z.id,name:Z.name||"",total:Z.total||0,uploaded:Z.uploaded,createdAt:Z.createdAt.toISOString()})),pageInfo:J}}}var sq=new Gn;function jT0(W){if(!W)return w$(null,null);return w$(W,null)}class tq{prismaClient;constructor(W=g){this.prismaClient=W}async createVersionStack(W){let{fileIds:$,projectId:w,creatorId:Q}=W;if(!$||$.length===0)throw Error("no file ids provided");return await this.prismaClient.$transaction(async(J)=>{let X=await J.asset.findMany({where:{id:{in:$}},include:{parent:!0}});if(X.length!==$.length)throw Error("some files not found");let Z=void 0,Y=0;for(let M of X){if(M.type!==r0.file)throw Error(`asset ${M.id} is not a file`);if(!M.parentId)throw Error(`file ${M.id} does not have a parent`);if(Z===void 0)Z=M.parentId;else if(M.parentId!==Z)throw Error("files do not have the same parent");Y+=M.sizeByte}if(!Z)throw Error("files do not have a parent");if(!await J.asset.findUnique({where:{id:Z}}))throw Error("parent not found");let z=X.find((M)=>M.id===$[0])?.sortIndex||null,H=await J.asset.create({data:{type:r0.version_stack,fileCount:X.length,sizeByte:Y,status:"uploaded",projectId:w,creatorId:Q,parentId:Z,sortIndex:z}}),G=null;for(let M of $)G=jT0(G),await J.asset.update({where:{id:M},data:{parentId:H.id,sortIndex:G}});return await J.asset.update({where:{id:Z},data:{fileCount:{decrement:X.length-1}}}),H})}async changeStackFileVersion(W){let{stackId:$,fileId:w,beforeId:Q}=W;await this.prismaClient.$transaction(async(J)=>{let X=await J.asset.findUnique({where:{id:$}});if(!X)throw Error("stack not found");if(X.type!==r0.version_stack)throw Error("asset is not a version stack");let Z=await J.asset.findUnique({where:{id:w}});if(!Z)throw Error("file not found");if(Z.parentId!==$)throw Error("file is not in the stack");let Y;if(Q==="-1"){let K=await J.asset.findFirst({where:{parentId:$},orderBy:{sortIndex:"desc"}});Y=w$(K?.sortIndex||null,null)}else{let K=await J.asset.findUnique({where:{id:Q}});if(!K)throw Error("before_id file not found");if(K.parentId!==$)throw Error("before_id file is not in the stack");let z=(await J.asset.findFirst({where:{parentId:$,sortIndex:{lt:K.sortIndex}},orderBy:{sortIndex:"desc"}}))?.sortIndex||null;if(z&&z>=K.sortIndex)z=null;Y=w$(z,K.sortIndex)}await J.asset.update({where:{id:w},data:{sortIndex:Y}})})}}var Wo5=new tq;import{ApplicationFailure as PW,Context as Nn}from"@temporalio/activity";class qn{async incrementBucket(W){if(W.userId!==null)await g.aiUsage.upsert({where:{teamId_userId_periodStart:{teamId:W.teamId,userId:W.userId,periodStart:W.periodStart}},update:{inputTokens:{increment:W.inputTokens},outputTokens:{increment:W.outputTokens},cacheReadTokens:{increment:W.cacheReadTokens},totalTokens:{increment:W.totalTokens},cost:{increment:W.cost}},create:{teamId:W.teamId,userId:W.userId,periodStart:W.periodStart,inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens,totalTokens:W.totalTokens,cost:W.cost}});else{let $=await g.aiUsage.findFirst({where:{teamId:W.teamId,userId:null,periodStart:W.periodStart}});if($)await g.aiUsage.update({where:{id:$.id},data:{inputTokens:{increment:W.inputTokens},outputTokens:{increment:W.outputTokens},cacheReadTokens:{increment:W.cacheReadTokens},totalTokens:{increment:W.totalTokens},cost:{increment:W.cost}}});else try{await g.aiUsage.create({data:{teamId:W.teamId,userId:null,periodStart:W.periodStart,inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens,totalTokens:W.totalTokens,cost:W.cost}})}catch(w){if(w instanceof Z0.PrismaClientKnownRequestError&&w.code==="P2002")await g.aiUsage.updateMany({where:{teamId:W.teamId,userId:null,periodStart:W.periodStart},data:{inputTokens:{increment:W.inputTokens},outputTokens:{increment:W.outputTokens},cacheReadTokens:{increment:W.cacheReadTokens},totalTokens:{increment:W.totalTokens},cost:{increment:W.cost}}});else throw w}}}async recordUsage(W){let $=W.timestamp??new Date,w=new Date($);if(w.setMinutes(0,0,0),await this.incrementBucket({teamId:W.teamId,userId:null,periodStart:w,inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens,totalTokens:W.totalTokens,cost:W.cost}),W.userId)await this.incrementBucket({teamId:W.teamId,userId:W.userId,periodStart:w,inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens,totalTokens:W.totalTokens,cost:W.cost})}async getTeamUsageStats(W){let w=new Date(new Date);switch(W.timeframe){case"1h":w.setMinutes(0,0,0);break;case"24h":w.setDate(w.getDate()-1),w.setMinutes(0,0,0);break;case"7d":w.setDate(w.getDate()-7),w.setMinutes(0,0,0);break;case"30d":w.setDate(w.getDate()-30),w.setMinutes(0,0,0);break}if(!W.userId){let Q=await g.aiUsage.findMany({where:{teamId:W.teamId,userId:null,periodStart:{gte:w}}}),J=0,X=0,Z=0,Y=0,K=0;for(let V of Q)J+=V.inputTokens,X+=V.outputTokens,Z+=V.cacheReadTokens,Y+=V.totalTokens,K+=V.cost;return{timeframe:W.timeframe,team:{inputTokens:J,outputTokens:X,cacheReadTokens:Z,totalTokens:Y,cost:Math.round((K+Number.EPSILON)*1e6)/1e6}}}else{let Q=await g.teamMember.findFirst({where:{teamId:W.teamId,userId:W.userId},include:{user:!0}});if(!Q)throw new w1(404,{message:"Team member not found"});let J=await g.aiUsage.findMany({where:{teamId:W.teamId,userId:W.userId,periodStart:{gte:w}}}),X=0,Z=0,Y=0,K=0,V=0;for(let z of J)X+=z.inputTokens,Z+=z.outputTokens,Y+=z.cacheReadTokens,K+=z.totalTokens,V+=z.cost;return{timeframe:W.timeframe,member:{userId:Q.user.id,userName:Q.user.name,userEmail:Q.user.email,userImage:Q.user.image,role:Q.role,inputTokens:X,outputTokens:Z,cacheReadTokens:Y,totalTokens:K,cost:Math.round((V+Number.EPSILON)*1e6)/1e6}}}}}var Mn=new qn;async function Un(W){let{agent:$,dbProviders:w,teamSkills:Q,allowedDomains:J}=W.context;if(!$.provider)throw PW.create({message:"agent has no provider configured",nonRetryable:!0});if(!$.modelRef)throw PW.create({message:"agent has no model configured",nonRetryable:!0});let X=$.provider.name,Z=$.modelRef.modelId,Y=`You are the AI assistant for shumai.
|
|
1304
1304
|
shumai is a professional creative collaboration platform similar to frame.io, where users can upload creative files, manage projects, assign tasks, get precise feedback, and share their work. As the agent, your role is to help users use and manage this platform.
|
|
1305
1305
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shumai-one/shumai-agent",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "AI worker agent for the shumai media workspace",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"@prisma/client": "7.8.0",
|
|
16
16
|
"@prisma/adapter-pg": "7.8.0",
|
|
17
17
|
"pg": "8.21.0",
|
|
18
|
-
"sharp": "0.
|
|
18
|
+
"sharp": "0.35.3",
|
|
19
19
|
"pino": "10.3.1",
|
|
20
20
|
"pino-pretty": "13.1.3",
|
|
21
21
|
"@temporalio/activity": "1.17.2",
|
|
@@ -27,12 +27,12 @@
|
|
|
27
27
|
"zod": "4.4.3"
|
|
28
28
|
},
|
|
29
29
|
"optionalDependencies": {
|
|
30
|
-
"@shumai-one/shumai-agent-darwin-arm64": "0.2.
|
|
31
|
-
"@shumai-one/shumai-agent-darwin-x64": "0.2.
|
|
32
|
-
"@shumai-one/shumai-agent-linux-arm64": "0.2.
|
|
33
|
-
"@shumai-one/shumai-agent-linux-x64": "0.2.
|
|
34
|
-
"@shumai-one/shumai-agent-win32-arm64": "0.2.
|
|
35
|
-
"@shumai-one/shumai-agent-win32-x64": "0.2.
|
|
30
|
+
"@shumai-one/shumai-agent-darwin-arm64": "0.2.3",
|
|
31
|
+
"@shumai-one/shumai-agent-darwin-x64": "0.2.3",
|
|
32
|
+
"@shumai-one/shumai-agent-linux-arm64": "0.2.3",
|
|
33
|
+
"@shumai-one/shumai-agent-linux-x64": "0.2.3",
|
|
34
|
+
"@shumai-one/shumai-agent-win32-arm64": "0.2.3",
|
|
35
|
+
"@shumai-one/shumai-agent-win32-x64": "0.2.3"
|
|
36
36
|
},
|
|
37
37
|
"repository": {
|
|
38
38
|
"type": "git",
|