coze-coding-dev-sdk 0.7.19-beta.13 → 0.7.19-beta.18
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/dist/cjs/cli/index.js +3 -3
- package/dist/cjs/index.js +18 -18
- package/dist/esm/131.mjs +1 -1
- package/dist/esm/cli/index.mjs +8 -8
- package/dist/types/video/client.d.ts +18 -0
- package/dist/types/video/client.d.ts.map +1 -1
- package/dist/types/video/models.d.ts +18 -2
- package/dist/types/video/models.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/esm/131.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
let e,i,n,t,a,r,o,u,s,l,h,g,c,d;import*as p from"buffer";import*as f from"crypto";import*as m from"events";import*as y from"fs";import*as S from"node:fs";import*as b from"node:fs/promises";import*as C from"node:stream";import*as w from"os";import*as T from"path";import*as x from"stream";import*as L from"zlib";import{__webpack_require__ as E}from"./rslib-runtime.mjs";import _ from"axios";import{URL as Y,parse as D}from"url";import{ChatOpenAI as v}from"@langchain/openai";import{AIMessage as A,HumanMessage as N,SystemMessage as P}from"@langchain/core/messages";import Z from"pg";import{exec as R,execSync as M}from"child_process";import{env as J,versions as k}from"process";import{Agent as B,request as H}from"http";import{Agent as F,request as X}from"https";E.add({"./node_modules/dotenv/lib/main.js"(e,i,n){let t=n("fs"),a=n("path"),r=n("os"),o=n("crypto"),u=n("./node_modules/dotenv/package.json").version,s=["\uD83D\uDD10 encrypt with Dotenvx: https://dotenvx.com","\uD83D\uDD10 prevent committing .env to code: https://dotenvx.com/precommit","\uD83D\uDD10 prevent building .env in docker: https://dotenvx.com/prebuild","\uD83D\uDCE1 add observability to secrets: https://dotenvx.com/ops","\uD83D\uDC65 sync secrets across teammates & machines: https://dotenvx.com/ops","\uD83D\uDDC2️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","\uD83D\uDD04 add secrets lifecycle management: https://dotenvx.com/ops","\uD83D\uDD11 add access controls to secrets: https://dotenvx.com/ops","\uD83D\uDEE0️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function _getRandomTip(){return s[Math.floor(Math.random()*s.length)]}function parseBoolean(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}function supportsAnsi(){return process.stdout.isTTY}function dim(e){return supportsAnsi()?`\x1b[2m${e}\x1b[0m`:e}let l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function _warn(e){console.error(`[dotenv@${u}][WARN] ${e}`)}function _debug(e){console.log(`[dotenv@${u}][DEBUG] ${e}`)}function _log(e){console.log(`[dotenv@${u}] ${e}`)}function _dotenvKey(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _instructions(e,i){let n;try{n=new URL(i)}catch(e){if("ERR_INVALID_URL"===e.code){let e=Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}let t=n.password;if(!t){let e=Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}let a=n.searchParams.get("environment");if(!a){let e=Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}let r=`DOTENV_VAULT_${a.toUpperCase()}`,o=e.parsed[r];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:o,key:t}}function _vaultPath(e){let i=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)t.existsSync(n)&&(i=n.endsWith(".vault")?n:`${n}.vault`);else i=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else i=a.resolve(process.cwd(),".env.vault");return t.existsSync(i)?i:null}function _resolveHome(e){return"~"===e[0]?a.join(r.homedir(),e.slice(1)):e}let h={configDotenv:function(e){let i,n=a.resolve(process.cwd(),".env"),r="utf8",o=process.env;e&&null!=e.processEnv&&(o=e.processEnv);let u=parseBoolean(o.DOTENV_CONFIG_DEBUG||e&&e.debug),s=parseBoolean(o.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?r=e.encoding:u&&_debug("No encoding is specified. UTF-8 is used by default");let l=[n];if(e&&e.path)if(Array.isArray(e.path))for(let i of(l=[],e.path))l.push(_resolveHome(i));else l=[_resolveHome(e.path)];let g={};for(let n of l)try{let i=h.parse(t.readFileSync(n,{encoding:r}));h.populate(g,i,e)}catch(e){u&&_debug(`Failed to load ${n} ${e.message}`),i=e}let c=h.populate(o,g,e);if(u=parseBoolean(o.DOTENV_CONFIG_DEBUG||u),s=parseBoolean(o.DOTENV_CONFIG_QUIET||s),u||!s){let e=Object.keys(c).length,n=[];for(let e of l)try{let i=a.relative(process.cwd(),e);n.push(i)}catch(n){u&&_debug(`Failed to load ${e} ${n.message}`),i=n}_log(`injecting env (${e}) from ${n.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`)}return i?{parsed:g,error:i}:{parsed:g}},_configVault:function(e){let i=parseBoolean(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=parseBoolean(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(i||!n)&&_log("Loading env from encrypted .env.vault");let t=h._parseVault(e),a=process.env;return e&&null!=e.processEnv&&(a=e.processEnv),h.populate(a,t,e),{parsed:t}},_parseVault:function(e){let i,n=_vaultPath(e=e||{});e.path=n;let t=h.configDotenv(e);if(!t.parsed){let e=Error(`MISSING_DATA: Cannot parse ${n} for an unknown reason`);throw e.code="MISSING_DATA",e}let a=_dotenvKey(e).split(","),r=a.length;for(let e=0;e<r;e++)try{let n=a[e].trim(),r=_instructions(t,n);i=h.decrypt(r.ciphertext,r.key);break}catch(i){if(e+1>=r)throw i}return h.parse(i)},config:function(e){if(0===_dotenvKey(e).length)return h.configDotenv(e);let i=_vaultPath(e);return i?h._configVault(e):(_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${i}. Did you forget to build it?`),h.configDotenv(e))},decrypt:function(e,i){let n=Buffer.from(i.slice(-64),"hex"),t=Buffer.from(e,"base64"),a=t.subarray(0,12),r=t.subarray(-16);t=t.subarray(12,-16);try{let e=o.createDecipheriv("aes-256-gcm",n,a);return e.setAuthTag(r),`${e.update(t)}${e.final()}`}catch(t){let e=t instanceof RangeError,i="Invalid key length"===t.message,n="Unsupported state or unable to authenticate data"===t.message;if(e||i){let e=Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){let e=Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw t}},parse:function(e){let i,n={},t=e.toString();for(t=t.replace(/\r\n?/mg,"\n");null!=(i=l.exec(t));){let e=i[1],t=i[2]||"",a=(t=t.trim())[0];t=t.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),'"'===a&&(t=(t=t.replace(/\\n/g,"\n")).replace(/\\r/g,"\r")),n[e]=t}return n},populate:function(e,i,n={}){let t=!!(n&&n.debug),a=!!(n&&n.override),r={};if("object"!=typeof i){let e=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(let n of Object.keys(i))Object.prototype.hasOwnProperty.call(e,n)?(!0===a&&(e[n]=i[n],r[n]=i[n]),t&&(!0===a?_debug(`"${n}" is already defined and WAS overwritten`):_debug(`"${n}" is already defined and was NOT overwritten`))):(e[n]=i[n],r[n]=i[n]);return r}};e.exports.configDotenv=h.configDotenv,e.exports._configVault=h._configVault,e.exports._parseVault=h._parseVault,e.exports.config=h.config,e.exports.decrypt=h.decrypt,e.exports.parse=h.parse,e.exports.populate=h.populate,e.exports=h},buffer(e){e.exports=p},crypto(e){e.exports=f},events(e){e.exports=m},fs(e){e.exports=y},"node:fs"(e){e.exports=S},"node:fs/promises"(e){e.exports=b},"node:stream"(e){e.exports=C},os(e){e.exports=w},path(e){e.exports=T},stream(e){e.exports=x},zlib(e){e.exports=L},"./node_modules/dotenv/package.json"(e){e.exports=JSON.parse('{"name":"dotenv","version":"17.2.3","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')}});var I,O,Q,U,G,q,$,K,z,W,j,V,ee,ei,en,et,ea,er,eo,eu,es,el,eh,eg,ec,ed,ep,ef,em={};E.r(em),E.d(em,{T:()=>eC});var ey={};E.r(ey),E.d(ey,{n:()=>e_,p:()=>eY});var eS={};E.r(eS),E.d(eS,{F:()=>mU});var eb={};E.r(eb),E.d(eb,{c:()=>eQ});class eC{apiKey;baseUrl;modelBaseUrl;retryTimes;retryDelay;timeout;constructor(e){this.apiKey=e?.apiKey||process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"",this.baseUrl=e?.baseUrl||process.env.COZE_INTEGRATION_BASE_URL||"",this.modelBaseUrl=e?.modelBaseUrl||process.env.COZE_INTEGRATION_MODEL_BASE_URL||"",this.retryTimes=e?.retryTimes??3,this.retryDelay=e?.retryDelay??1,this.timeout=e?.timeout??9e5}validate(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.")}getHeaders(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.");return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}}class ew extends Error{constructor(e){super(e),this.name="ConfigurationError"}}class eT extends Error{statusCode;response;constructor(e,i,n){super(e),this.name="APIError",this.statusCode=i,this.response=n}}class ex extends Error{originalError;constructor(e,i){super(e),this.originalError=i,this.name="NetworkError"}}class eL extends Error{constructor(e){super(e),this.name="ValidationError"}}class eE{config;axiosInstance;verbose;constructor(e,i,n=!1){this.config=e||new eC,this.verbose=n,this.axiosInstance=_.create({timeout:this.config.timeout,headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...i}})}async request(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a.data}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eT(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(_.isAxiosError(a)&&a.response)throw new eT(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new ex(a.message);throw new ex("Request failed after retries")}async requestWithResponse(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eT(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(_.isAxiosError(a)&&a.response)throw new eT(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new ex(a.message);throw new ex("Request failed after retries")}sanitizeHeaders(e){let i=["authorization","auth","api-key","apikey","api_key","x-api-key","x-auth-token","token","secret","password","passwd","pwd"],n={};for(let[t,a]of Object.entries(e)){let e=t.toLowerCase();i.some(i=>e.includes(i))?n[t]="***":n[t]=a}return n}logRequest(e,i,n,t){console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE4 HTTP Request"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Method: ${e}`),console.log(`URL: ${i}`);let a={};Object.assign(a,this.axiosInstance.defaults.headers.common||{},this.axiosInstance.defaults.headers[e.toLowerCase()]||{},t?.headers||{});let r=this.sanitizeHeaders(a);for(let[e,i]of(console.log("\nHeaders:"),Object.entries(r)))console.log(` ${e}: ${i}`);n&&(console.log("\nBody:"),console.log(JSON.stringify(n,null,2))),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}logResponse(e){if(console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE5 HTTP Response"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Status: ${e.status} ${e.statusText}`),e.headers)for(let[i,n]of(console.log("\nHeaders:"),Object.entries(e.headers)))console.log(` ${i}: ${n}`);if(e.data){console.log("\nBody:");let i="string"==typeof e.data?e.data:JSON.stringify(e.data,null,2);console.log(i.length>1e3?i.substring(0,1e3)+"\n... (truncated)":i)}console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}sleep(e){return new Promise(i=>setTimeout(i,e))}}let e_=["x-tt-logid","x-tt-env","x-use-ppe","x-tt-env-fe","x-run-mode","rpc-persist-res-rec-biz-scene","rpc-persist-coze-record-root-id","rpc-persist-res-rec-root-entity-type","rpc-persist-res-rec-root-entity-id","rpc-persist-res-rec-ext-info"];class eY{static extractForwardHeaders(e){let i={};return e instanceof Headers?e_.forEach(n=>{let t=e.get(n);t&&(i[n]=t)}):e_.forEach(n=>{let t=e[n]||e[n.toLowerCase()];t&&(i[n]=t)}),i}}let eD=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),ev=new Set(["http:","https:"]),eA=[["code.coze.cn","/api/sandbox/coze_coding/file/proxy"]];class eN extends eL{url;constructor(e,i){super(e),this.name="URLValidationError",this.url=i}}async function url_utils_validateUrl(e,i){let n,{allowHeadCheck:t=!0,timeout:a=5e3}=i||{};if(!e||"string"!=typeof e)throw new eN("URL cannot be empty","string"==typeof e?e:void 0);if(!(e=e.trim()))throw new eN("URL cannot be empty",e);try{n=new Y(e)}catch{if(isLocalPath(e))throw new eN(`The input appears to be a local file path: ${e}. Please upload it using the Storage skill first to get a persistent HTTP URL.`,e);throw new eN(`Invalid URL format: ${e}`,e)}if(!ev.has(n.protocol))throw new eN(`Unsupported scheme '${n.protocol}', only http/https allowed`,e);let r=n.hostname;if(!r)throw new eN(`Cannot extract hostname from URL: ${e}`,e);if(eD.has(r.toLowerCase())||eD.has(r.replace(/^\[|\]$/g,"").toLowerCase()))throw new eN(`Access to local address is not allowed: ${r}`,e);if(isEphemeralUrl(e))throw new eN("This URL appears to be a temporary sandbox proxy URL that may expire. Please download the file and upload it to persistent storage (Storage skill) first.",e);return t&&await headCheck(e,a),e}function isEphemeralUrl(e){try{let i=new Y(e),n=i.hostname.toLowerCase(),t=i.pathname;for(let[e,i]of eA)if(n===e&&t.startsWith(i))return!0}catch{}return!1}function isLocalPath(e){return!!e&&!!(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.length>=3&&/^[a-zA-Z]$/.test(e[0])&&":"===e[1]&&("/"===e[2]||"\\"===e[2]))}function validateUrlSync(e){let i;if(!e||"string"!=typeof e)throw new eN("URL cannot be empty","string"==typeof e?e:void 0);if(!(e=e.trim()))throw new eN("URL cannot be empty",e);try{i=new Y(e)}catch{if(isLocalPath(e))throw new eN(`The input appears to be a local file path: ${e}. Please upload it using the Storage skill first to get a persistent HTTP URL.`,e);throw new eN(`Invalid URL format: ${e}`,e)}if(!ev.has(i.protocol))throw new eN(`Unsupported scheme '${i.protocol}', only http/https allowed`,e);let n=i.hostname;if(!n)throw new eN(`Cannot extract hostname from URL: ${e}`,e);if(eD.has(n.toLowerCase())||eD.has(n.replace(/^\[|\]$/g,"").toLowerCase()))throw new eN(`Access to local address is not allowed: ${n}`,e);return e}async function headCheck(e,i){let n=new AbortController,t=setTimeout(()=>n.abort(),i);try{let a=await fetch(e,{method:"HEAD",signal:n.signal,headers:{"User-Agent":"CozeSDK-URLValidator/1.0"}});if(405===a.status){clearTimeout(t),await rangeCheck(e,i);return}if(!a.ok)throw new eN(`URL is not reachable: HTTP ${a.status}`,e)}catch(n){if(n instanceof eN)throw n;if("AbortError"===n.name)throw new eN(`URL preflight check timed out after ${i}ms`,e);throw new eN(`URL preflight check failed: ${n.message}`,e)}finally{clearTimeout(t)}}async function rangeCheck(e,i){let n=new AbortController,t=setTimeout(()=>n.abort(),i);try{let i=await fetch(e,{method:"GET",signal:n.signal,headers:{"User-Agent":"CozeSDK-URLValidator/1.0",Range:"bytes=0-0"}});if(405===i.status||400===i.status)return;if(i.status>=400)throw new eN(`URL is not reachable: HTTP ${i.status}`,e)}catch(n){if(n instanceof eN)throw n;if("AbortError"===n.name)throw new eN(`URL preflight check timed out after ${i}ms`,e);throw new eN(`URL preflight check failed: ${n.message}`,e)}finally{clearTimeout(t)}}class eP{static DEFAULT_MODEL="doubao-seedream-5-0-260128";static DEFAULT_SIZE="2K";static DEFAULT_CUSTOM_SIZE="2048x2048";static DEFAULT_WATERMARK=!0;static DEFAULT_RESPONSE_FORMAT="url";static DEFAULT_OPTIMIZE_PROMPT_MODE="standard";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION="disabled";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES=15;static MIN_TOTAL_PIXELS=3686400;static MAX_TOTAL_PIXELS=0x1000000;static MIN_ASPECT_RATIO=1/16;static MAX_ASPECT_RATIO=16;static PRESET_SIZES=["2K","4K"]}function validateImageSize(e){if(eP.PRESET_SIZES.includes(e))return e;let i=e.match(/^(\d+)x(\d+)$/);if(!i)throw Error(`Invalid size format. Must be ${JSON.stringify(eP.PRESET_SIZES)} or 'WIDTHxHEIGHT' format (e.g., 2048x2048). Got: ${e}`);let n=parseInt(i[1],10),t=parseInt(i[2],10);if(n<=0||t<=0)throw Error(`Width and height must be positive integers. Got: ${e}`);let a=n*t;if(a<eP.MIN_TOTAL_PIXELS||a>eP.MAX_TOTAL_PIXELS)throw Error(`Total pixels must be between ${eP.MIN_TOTAL_PIXELS.toLocaleString()} and ${eP.MAX_TOTAL_PIXELS.toLocaleString()}. Got: ${a.toLocaleString()} (${n}x${t})`);let r=n/t;if(r<eP.MIN_ASPECT_RATIO||r>eP.MAX_ASPECT_RATIO)throw Error(`Aspect ratio must be between 1:16 and 16:1. Got: ${n}:${t} (${r.toFixed(2)})`);return e}function validateImageSizeOrDefault(e){try{return validateImageSize(e)}catch{return eP.DEFAULT_SIZE}}class eZ{response;constructor(e){this.response=e}get success(){return!this.response.error&&this.response.data.every(e=>!e.error)}get imageUrls(){return this.response.data.filter(e=>e.url).map(e=>e.url)}get imageB64List(){return this.response.data.filter(e=>e.b64_json).map(e=>e.b64_json)}get errorMessages(){let e=[];for(let i of(this.response.error&&e.push(`API Error: ${this.response.error.message||"Unknown error"}`),this.response.data))i.error&&e.push(`Image generation error: ${i.error.message||"Unknown error"}`);return e}}function buildImageGenerationApiRequest(e,i){let n=validateImageSizeOrDefault(e.size||eP.DEFAULT_SIZE);return{model:i,prompt:e.prompt,size:n,watermark:e.watermark??eP.DEFAULT_WATERMARK,image:e.image,response_format:e.responseFormat||eP.DEFAULT_RESPONSE_FORMAT,optimize_prompt_options:{mode:e.optimizePromptMode||eP.DEFAULT_OPTIMIZE_PROMPT_MODE},sequential_image_generation:e.sequentialImageGeneration||eP.DEFAULT_SEQUENTIAL_IMAGE_GENERATION,sequential_image_generation_options:{max_images:e.sequentialImageGenerationMaxImages||eP.DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES}}}class eR extends eE{constructor(e,i,n=!1){super(e,i,n)}async generate(e){if(e.image)if(Array.isArray(e.image))for(let i=0;i<e.image.length;i++)e.image[i]=await url_utils_validateUrl(e.image[i]);else e.image=await url_utils_validateUrl(e.image);let i=e.model||eP.DEFAULT_MODEL,n=buildImageGenerationApiRequest(e,i),t=await this.request("POST",`${this.config.baseUrl}/api/v3/images/generations`,n);if(t.error)throw new eT(`API returned error: ${t.error.message||"Unknown error"}`,t.error.code?parseInt(t.error.code):500,t.error);for(let e of t.data)if(e.error)throw new eT(`Image generation failed: ${e.error.message||"Unknown error"}`,e.error.code?parseInt(e.error.code):500,e.error);return t}async batchGenerate(e){return Promise.all(e.map(e=>this.generate(e)))}getResponseHelper(e){return new eZ(e)}}function convertToApiFormat(e){let i={};return e.query&&(i.Query=e.query),e.search_type&&(i.SearchType=e.search_type),void 0!==e.count&&(i.Count=e.count),void 0!==e.need_summary&&(i.NeedSummary=e.need_summary),e.time_range&&(i.TimeRange=e.time_range),e.filter&&(i.Filter={NeedContent:e.filter.need_content||!1,NeedUrl:e.filter.need_url||!1,Sites:e.filter.sites,BlockHosts:e.filter.block_hosts}),i}function convertFromApiFormat(e){let i={};return void 0!==e.Id&&(i.id=e.Id),void 0!==e.SortId&&(i.sort_id=e.SortId),void 0!==e.Title&&(i.title=e.Title),void 0!==e.SiteName&&(i.site_name=e.SiteName),void 0!==e.Url&&(i.url=e.Url),void 0!==e.Snippet&&(i.snippet=e.Snippet),void 0!==e.Summary&&(i.summary=e.Summary),void 0!==e.Content&&(i.content=e.Content),void 0!==e.PublishTime&&(i.publish_time=e.PublishTime),void 0!==e.LogoUrl&&(i.logo_url=e.LogoUrl),void 0!==e.RankScore&&(i.rank_score=e.RankScore),void 0!==e.AuthInfoDes&&(i.auth_info_des=e.AuthInfoDes),void 0!==e.AuthInfoLevel&&(i.auth_info_level=e.AuthInfoLevel),e.Image&&(i.image={url:e.Image.Url,width:e.Image.Width,height:e.Image.Height,shape:e.Image.Shape}),i}class eM extends eE{constructor(e,i,n=!1){super(e,i,n)}async search(e){let i,n=convertToApiFormat(e),t=await this.request("POST",`${this.config.baseUrl}/api/search_api/web_search`,n),a=t.ResponseMetadata||{};if(a.Error)throw new eT(`Search failed: ${a.Error}`,500,a.Error);let r=t.Result||{},o=[];if(r.WebResults)for(let e of r.WebResults)o.push(convertFromApiFormat(e));let u=[];if(r.ImageResults)for(let e of r.ImageResults)u.push(convertFromApiFormat(e));return r.Choices&&r.Choices.length>0&&(i=r.Choices[0].Message?.Content),{web_items:o,image_items:u,summary:i}}async webSearch(e,i=10,n=!0){return this.search({query:e,search_type:"web",count:i,need_summary:n})}async webSearchWithSummary(e,i=10){return this.search({query:e,search_type:"web_summary",count:i,need_summary:!0})}async imageSearch(e,i=10){return this.search({query:e,search_type:"image",count:i,need_summary:!1})}async advancedSearch(e,i={}){let n={need_content:i.needContent,need_url:i.needUrl,sites:i.sites,block_hosts:i.blockHosts};return this.search({query:e,search_type:i.searchType||"web",count:i.count||10,filter:n,need_summary:void 0===i.needSummary||i.needSummary,time_range:i.timeRange})}}class eJ{static DEFAULT_SPEAKER="zh_female_xiaohe_uranus_bigtts";static DEFAULT_AUDIO_FORMAT="mp3";static DEFAULT_SAMPLE_RATE=24e3;static DEFAULT_SPEECH_RATE=0;static DEFAULT_LOUDNESS_RATE=0}function buildTTSApiRequest(e){let i={user:{uid:e.uid},req_params:{speaker:e.speaker||eJ.DEFAULT_SPEAKER,audio_params:{format:e.audioFormat||eJ.DEFAULT_AUDIO_FORMAT,sample_rate:e.sampleRate||eJ.DEFAULT_SAMPLE_RATE,speech_rate:e.speechRate??eJ.DEFAULT_SPEECH_RATE,loudness_rate:e.loudnessRate??eJ.DEFAULT_LOUDNESS_RATE}}};return e.text?i.req_params.text=e.text:e.ssml&&(i.req_params.ssml=e.ssml),i}function buildASRApiRequest(e){let i={};return e.url?i.url=e.url:e.base64Data&&(i.data=e.base64Data),{user:{uid:e.uid},audio:i}}class ek extends eE{constructor(e,i,n=!1){super(e,i,n)}async synthesize(e){if(!e.text&&!e.ssml)throw new eL("必须提供 text 或 ssml 其中之一");let i=buildTTSApiRequest(e),n={...this.config.getHeaders(),Connection:"keep-alive"};try{let e=await _.post(`${this.config.baseUrl}/api/v3/tts/unidirectional`,i,{headers:n,responseType:"stream",timeout:this.config.timeout});return await this.processStreamResponse(e)}catch(e){if(e.response)throw new eT(`TTS 请求失败: ${e.message}`,e.response.status,e.response.data);throw new eT(`TTS 请求异常: ${e.message}`,500)}}async processStreamResponse(e){return new Promise((i,n)=>{let t="",a=0,r="";e.data.on("data",e=>{let o=(r+=e.toString("utf-8")).split("\n");for(let e of(r=o.pop()||"",o))if(e.trim()&&e.startsWith("data:"))try{let r=e.replace("data:","").trim();if(!r)continue;let o=JSON.parse(r);if(0===o.code&&o.data){let e=Buffer.from(o.data,"base64");a+=e.length}else if(2e7===o.code){o.url&&(t=o.url),i({audioUri:t,audioSize:a});return}else if(o.code>0)return void n(new eT(`合成音频失败: ${o.message||""}`,o.code))}catch(e){n(new eT(`响应解析失败: ${e.message}`,500));return}}),e.data.on("end",()=>{t||0!==a?i({audioUri:t,audioSize:a}):n(new eT("未收到完整的音频数据",500))}),e.data.on("error",e=>{n(new eT(`流处理错误: ${e.message}`,500))})})}}class eB extends eE{constructor(e,i,n=!1){super(e,i,n)}async recognize(e){if(!e.url&&!e.base64Data)throw new eL("必须提供 url 或 base64Data 其中之一");let i=buildASRApiRequest(e);try{let e=await this.requestWithResponse("POST",`${this.config.baseUrl}/api/v3/auc/bigmodel/recognize/flash`,i),n=e.headers["x-api-status-code"]||"0",t=e.headers["x-api-message"]||"";if("20000000"!==n)throw new eT(`ASR 识别失败,状态码: ${n}, 错误信息: ${t}`,e.status,{code:n,message:t});let a=e.data.result||{};return{text:a.text||"",duration:a.duration,utterances:a.utterances,rawData:e.data}}catch(e){if(e instanceof eT)throw e;throw new eT(`ASR 请求异常: ${e.message}`,500)}}}class eH{static DEFAULT_MODEL="doubao-seedance-1-5-pro-251215";static DEFAULT_RESOLUTION="720p";static DEFAULT_RATIO="16:9";static DEFAULT_DURATION=5;static DEFAULT_WATERMARK=!0;static DEFAULT_CAMERA_FIXED=!1;static DEFAULT_GENERATE_AUDIO=!0}class eF extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async videoGeneration(e,i){let n=(i?.maxWaitTime??900)*1e3,t=i?.model||eH.DEFAULT_MODEL;for(let i of e)"image_url"===i.type&&(i.image_url.url=await url_utils_validateUrl(i.image_url.url));let a={model:t,content:e};i?.callbackUrl&&(a.callback_url=i.callbackUrl),i?.returnLastFrame&&(a.return_last_frame=i.returnLastFrame),a.resolution=i?.resolution??eH.DEFAULT_RESOLUTION,a.ratio=i?.ratio??eH.DEFAULT_RATIO,a.duration=i?.duration??eH.DEFAULT_DURATION,a.watermark=i?.watermark??eH.DEFAULT_WATERMARK,i?.seed!==void 0&&(a.seed=i.seed),a.camerafixed=i?.camerafixed??eH.DEFAULT_CAMERA_FIXED,a.generate_audio=i?.generateAudio??eH.DEFAULT_GENERATE_AUDIO;let r=null,o=0;for(;o<3;)try{if(!(r=(await this.request("POST",`${this.baseUrl}/api/v3/contents/generations/tasks`,a)).id))throw new eT("创建视频生成任务失败:响应中缺少任务ID",500);this.verbose&&console.log(`视频生成任务创建成功,任务ID: ${r}`);break}catch(i){o++;let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`创建视频生成任务失败(尝试 ${o}/3): ${e}`),o>=3)throw new eT(`创建视频生成任务失败,已重试3次: ${e}`,500);if(e.toLowerCase().includes("rate limit")||e.includes("429")){let e=Math.min(2**o*1e3,1e4);this.verbose&&console.warn(`遇到速率限制,等待 ${e/1e3} 秒后重试...`),await this.sleep(e)}else if(e.toLowerCase().includes("timeout"))this.verbose&&console.warn("请求超时,等待 2 秒后重试..."),await this.sleep(2e3);else throw i}let u=Date.now(),s=0;for(;Date.now()-u<n;){s++;try{let e=await this.request("GET",`${this.baseUrl}/api/v3/contents/generations/tasks/${r}`),i=e.status;if(this.verbose&&console.log(`任务 ${r} 状态检查 #${s}: ${i}`),"succeeded"===i){let i=e.content?.video_url||null,n=e.content?.last_frame_url||"";if(!i)throw new eT(`视频生成成功但响应中缺少视频URL,任务ID: ${r}`,500);return this.verbose&&console.log(`视频生成成功,任务ID: ${r}, 视频URL: ${i}`),{videoUrl:i,response:e,lastFrameUrl:n}}if("failed"===i){let i=e.error_message||"未知错误";throw this.verbose&&console.error(`视频生成失败,任务ID: ${r}, 错误: ${i}`),new eT(`视频生成失败: ${i}`,500)}if("cancelled"===i)return this.verbose&&console.warn(`视频生成任务被取消,任务ID: ${r}`),{videoUrl:null,response:e,lastFrameUrl:""};else if("queued"===i||"running"===i){await this.sleep(5e3);continue}else{this.verbose&&console.warn(`未知的任务状态: ${i},任务ID: ${r}`),await this.sleep(5e3);continue}}catch(i){let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`查询任务状态失败,任务ID: ${r}, 错误: ${e}`),e.toLowerCase().includes("not found")||e.includes("404"))throw new eT(`任务不存在或已过期,任务ID: ${r}`,404);if(Date.now()-u>=n)throw i;await this.sleep(5e3);continue}}let l=Math.floor((Date.now()-u)/1e3);throw this.verbose&&console.error(`视频生成超时,任务ID: ${r}, 已等待: ${l}秒`),new eT(`视频生成超时,已等待 ${l} 秒,任务ID: ${r}`,408)}async videoGenerationAsync(e,i){return this.videoGeneration(e,i)}}class eX{static DEFAULT_URL_EXPIRE=86400;static MAX_URL_EXPIRE=2592e3;static MIN_URL_EXPIRE=1;static MIN_AUDIO_URL_EXPIRE=3600;static DEFAULT_FONT_TYPE="1525745";static DEFAULT_FONT_SIZE=36;static DEFAULT_FONT_COLOR="#FFFFFFFF";static DEFAULT_BACKGROUND_COLOR="#00000000";static DEFAULT_BACKGROUND_BORDER_WIDTH=0;static DEFAULT_FONT_POS_HEIGHT="10%";static DEFAULT_FONT_POS_X="0";static DEFAULT_FONT_POS_Y="90%";static DEFAULT_FONT_POS_WIDTH="100%";static DEFAULT_SYNC_METHOD="trim";static DEFAULT_SYNC_MODE="video";static DEFAULT_SUBTITLE_TYPE="srt";static DEFAULT_AUDIO_FORMAT="m4a"}class eI extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async extractByKeyFrame(e){e=await url_utils_validateUrl(e);let i=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_key_frame`,{url:e});if(0!==i.code)throw new eT(`Key frame extraction failed: ${i.msg||"Unknown error"}`,i.code);return i}async extractByInterval(e,i){e=await url_utils_validateUrl(e);let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_interval`,{url:e,interval_ms:i});if(0!==n.code)throw new eT(`Interval frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}async extractByCount(e,i){e=await url_utils_validateUrl(e);let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_count`,{url:e,count:i});if(0!==n.code)throw new eT(`Count-based frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}}class eO extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}validateUrlExpire(e,i=eX.MIN_URL_EXPIRE){if(void 0===e)return eX.DEFAULT_URL_EXPIRE;if(e<i||e>eX.MAX_URL_EXPIRE)throw new eT(`url_expire must be between ${i} and ${eX.MAX_URL_EXPIRE} seconds`,400);return e}async addSubtitles(e,i,n){e=await url_utils_validateUrl(e),n?.subtitleUrl&&(n.subtitleUrl=await url_utils_validateUrl(n.subtitleUrl));let t=this.validateUrlExpire(n?.urlExpire),a={video:e,subtitle_config:{background_border_width:i.background_border_width??eX.DEFAULT_BACKGROUND_BORDER_WIDTH,font_type:i.font_type??eX.DEFAULT_FONT_TYPE,font_pos_config:{height:i.font_pos_config.height??eX.DEFAULT_FONT_POS_HEIGHT,pos_x:i.font_pos_config.pos_x??eX.DEFAULT_FONT_POS_X,pos_y:i.font_pos_config.pos_y??eX.DEFAULT_FONT_POS_Y,width:i.font_pos_config.width??eX.DEFAULT_FONT_POS_WIDTH}},url_expire:t};void 0!==i.border_width&&(a.subtitle_config.border_width=i.border_width),void 0!==i.font_color&&(a.subtitle_config.font_color=i.font_color),void 0!==i.font_size&&(a.subtitle_config.font_size=i.font_size),void 0!==i.background_color&&(a.subtitle_config.background_color=i.background_color),void 0!==i.border_color&&(a.subtitle_config.border_color=i.border_color),n?.subtitleUrl&&(a.subtitle_url=n.subtitleUrl),n?.textList&&n.textList.length>0&&(a.text_list=n.textList.map(e=>({end_time:e.end_time,start_time:e.start_time,text:e.text})));let r=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=add_subtitles`,a),o=r.headers["x-api-status-code"]||"0",u=r.headers["x-api-message"]||"";if("0"!==o)throw new eT(`Add subtitles failed, status code: ${o}, error: ${u}`,parseInt(o)||500);if(!r.data.url)throw new eT("Add subtitles failed: returned URL is empty",500);return r.data}async concatVideos(e,i){if(!e||0===e.length)throw new eT("videos list cannot be empty",400);for(let i=0;i<e.length;i++)e[i]=await url_utils_validateUrl(e[i]);let n={videos:e,url_expire:this.validateUrlExpire(i?.urlExpire)};i?.transitions&&i.transitions.length>0&&(n.transitions=i.transitions);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=concat_videos`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eT(`Concat videos failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eT("Concat videos failed: returned URL is empty",500);return t.data}async compileVideoAudio(e,i,n){e=await url_utils_validateUrl(e),i=await url_utils_validateUrl(i);let t=this.validateUrlExpire(n?.urlExpire),a={video:e,audio:i,url_expire:t};n?.isVideoAudioSync!==void 0&&(a.is_video_audio_sync=n.isVideoAudioSync),n?.outputSync&&(a.output_sync={sync_method:n.outputSync.sync_method??eX.DEFAULT_SYNC_METHOD,sync_mode:n.outputSync.sync_mode??eX.DEFAULT_SYNC_MODE}),n?.isAudioReserve!==void 0&&(a.is_audio_reserve=n.isAudioReserve);let r=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=compile_video_audio`,a),o=r.headers["x-api-status-code"]||"0",u=r.headers["x-api-message"]||"";if("0"!==o)throw new eT(`Compile video audio failed, status code: ${o}, error: ${u}`,parseInt(o)||500);if(!r.data.url)throw new eT("Compile video audio failed: returned URL is empty",500);return r.data}async audioToSubtitle(e,i){e=await url_utils_validateUrl(e);let n=this.validateUrlExpire(i?.urlExpire),t={source:e,url_expire:n};i?.subtitleType&&(t.subtitle_type=i.subtitleType);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_to_subtitle`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eT(`Audio to subtitle failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eT("Audio to subtitle failed: returned URL is empty",500);return a.data}async extractAudio(e,i){e=await url_utils_validateUrl(e);let n=this.validateUrlExpire(i?.urlExpire,eX.MIN_AUDIO_URL_EXPIRE),t={video:e,url_expire:n};i?.format&&(t.format=i.format);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_extract`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eT(`Extract audio failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eT("Extract audio failed: returned URL is empty",500);return a.data}async videoTrim(e,i){e=await url_utils_validateUrl(e);let n=this.validateUrlExpire(i?.urlExpire);if(i?.startTime!==void 0&&i.startTime<0)throw new eT("start_time must be greater than or equal to 0",400);if(i?.endTime!==void 0&&i.endTime<0)throw new eT("end_time must be greater than or equal to 0",400);let t={video:e,url_expire:n};i?.startTime!==void 0&&(t.start_time=i.startTime),i?.endTime!==void 0&&(t.end_time=i.endTime);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=video_trim`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eT(`Video trim failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eT("Video trim failed: returned URL is empty",500);return a.data}}let eQ={MODEL:"doubao-seed-1-8-251228",THINKING:"disabled",CACHING:"disabled",TEMPERATURE:1,STREAMING:!0};class eU{config;customHeaders;constructor(e,i){this.config=e||new eC,this.customHeaders=i}createLLM(e,i,n){let t={};t.thinking={type:e.thinking??eQ.THINKING},e.caching&&"disabled"!==e.caching&&(t.caching={type:e.caching});let a={Authorization:`Bearer ${this.config.apiKey}`,"X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...this.customHeaders,...n};return i&&(a["X-Previous-Response-Id"]=i),new v({model:e.model||eQ.MODEL,apiKey:this.config.apiKey,configuration:{baseURL:this.config.modelBaseUrl,defaultHeaders:a},streaming:void 0!==e.streaming?e.streaming:eQ.STREAMING,temperature:void 0!==e.temperature?e.temperature:eQ.TEMPERATURE,modelKwargs:Object.keys(t).length>0?t:void 0})}convertMessages(e){return e.map(e=>{let i=this.convertContent(e.content);switch(e.role){case"system":return new P(i);case"user":return new N(i);case"assistant":return new A(i);default:throw Error(`Unknown message role: ${e.role}`)}})}convertContent(e){return"string"==typeof e?e:e.map(e=>{if("text"===e.type)return{type:"text",text:e.text};if("image_url"===e.type){let i={url:e.image_url.url};return e.image_url.detail&&(i.detail=e.image_url.detail),{type:"image_url",image_url:i}}if("video_url"===e.type){let i={url:e.video_url.url};return void 0!==e.video_url.fps&&(i.fps=e.video_url.fps),{type:"video_url",video_url:i}}return e})}async *stream(e,i={},n,t){if(!e.some(e=>"user"===e.role))throw Error('messages must contain at least one message with role: "user", otherwise the API request will fail validation.');for(let i of e)if(Array.isArray(i.content))for(let e of i.content)"image_url"===e.type&&e.image_url?e.image_url.url=await url_utils_validateUrl(e.image_url.url):"video_url"===e.type&&e.video_url&&(e.video_url.url=await url_utils_validateUrl(e.video_url.url));let a=this.createLLM(i,n,t),r=this.convertMessages(e);for await(let e of(await a.stream(r)))yield e}async invoke(e,i={},n,t){let a="";for await(let r of this.stream(e,i,n,t))r.content&&(a+=r.content.toString());return{content:a}}}var eG=((I={})[I.TEXT=0]="TEXT",I[I.URL=1]="URL",I[I.URI=2]="URI",I);class e$ extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async search(e,i,n=5,t=0,a){let r={query:e,top_k:n,min_score:t};i&&(r.dataset=i);let o=`${this.baseUrl}/v1/knowledge_base/recall`,u={...a};this.config.apiKey&&(u["x-coze-token"]=`Bearer ${this.config.apiKey}`);let s=await this.request("POST",o,r,{headers:u});return{chunks:(s.data||[]).map(e=>({content:e.slice||"",score:e.score||0,chunk_id:e.chunk_id,doc_id:e.doc_id})),code:s.code||0,msg:s.msg||""}}async addDocuments(e,i,n,t){let a={dataset:i,data:e};n&&(a.chunk_config=Object.fromEntries(Object.entries(n).filter(([e,i])=>void 0!==i)));let r=`${this.baseUrl}/v1/knowledge_base/batch_import`,o={...t};this.config.apiKey&&(o["x-coze-token"]=`Bearer ${this.config.apiKey}`);let u=await this.request("POST",r,a,{headers:o}),s=u.msg||"";return 0===u.code&&(s="成功!文档正在异步导入中,请稍候。您可以查看数据库中的 'knowledge' schema 来验证导入状态。"),{doc_ids:u.doc_ids,code:u.code||0,msg:s}}}let eK=Symbol.for("drizzle:entityKind");function entity_is(e,i){if(!e||"object"!=typeof e)return!1;if(e instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,eK))throw Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(eK in n&&n[eK]===i[eK])return!0;n=Object.getPrototypeOf(n)}return!1}Symbol.for("drizzle:hasOwnEntityKind");class ez{static [eK]="ConsoleLogWriter";write(e){console.log(e)}}class eW{static [eK]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new ez}logQuery(e,i){let n=i.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),t=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${e}${t}`)}}class ej{static [eK]="NoopLogger";logQuery(){}}class eV{constructor(e,i){this.table=e,this.config=i,this.name=i.name,this.keyAsName=i.keyAsName,this.notNull=i.notNull,this.default=i.default,this.defaultFn=i.defaultFn,this.onUpdateFn=i.onUpdateFn,this.hasDefault=i.hasDefault,this.primary=i.primaryKey,this.isUnique=i.isUnique,this.uniqueName=i.uniqueName,this.uniqueType=i.uniqueType,this.dataType=i.dataType,this.columnType=i.columnType,this.generated=i.generated,this.generatedIdentity=i.generatedIdentity}static [eK]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}class e0{static [eK]="ColumnBuilder";config;constructor(e,i,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:i,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}let e1=Symbol.for("drizzle:Name");class e3{static [eK]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,i){this.reference=()=>{let{name:i,columns:n,foreignColumns:t}=e();return{name:i,columns:n,foreignTable:t[0].table,foreignColumns:t}},i&&(this._onUpdate=i.onUpdate,this._onDelete=i.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new e2(e,this)}}class e2{constructor(e,i){this.table=e,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static [eK]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:i,foreignColumns:n}=this.reference(),t=i.map(e=>e.name),a=n.map(e=>e.name),r=[this.table[e1],...t,n[0].table[e1],...a];return e??`${r.join("_")}_fk`}}function iife(e,...i){return e(...i)}function uniqueKeyName(e,i){return`${e[e1]}_${i.join("_")}_unique`}class e4{constructor(e,i){this.name=i,this.columns=e}static [eK]=null;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new e6(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class e8{static [eK]=null;name;constructor(e){this.name=e}on(...e){return new e4(e,this.name)}}class e6{constructor(e,i,n,t){this.table=e,this.columns=i,this.name=t??uniqueKeyName(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static [eK]=null;columns;name;nullsNotDistinct=!1;getName(){return this.name}}function parsePgArrayValue(e,i,n){for(let t=i;t<e.length;t++){let a=e[t];if("\\"===a){t++;continue}if('"'===a)return[e.slice(i,t).replace(/\\/g,""),t+1];if(!n&&(","===a||"}"===a))return[e.slice(i,t).replace(/\\/g,""),t]}return[e.slice(i).replace(/\\/g,""),e.length]}function parsePgNestedArray(e,i=0){let n=[],t=i,a=!1;for(;t<e.length;){let r=e[t];if(","===r){(a||t===i)&&n.push(""),a=!0,t++;continue}if(a=!1,"\\"===r){t+=2;continue}if('"'===r){let[i,a]=parsePgArrayValue(e,t+1,!0);n.push(i),t=a;continue}if("}"===r)return[n,t+1];if("{"===r){let[i,a]=parsePgNestedArray(e,t+1);n.push(i),t=a;continue}let[o,u]=parsePgArrayValue(e,t,!1);n.push(o),t=u}return[n,t]}function parsePgArray(e){let[i]=parsePgNestedArray(e,1);return i}function makePgArray(e){return`{${e.map(e=>Array.isArray(e)?makePgArray(e):"string"==typeof e?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}class e5 extends e0{foreignKeyConfigs=[];static [eK]="PgColumnBuilder";array(e){return new it(this.config.name,this,e)}references(e,i={}){return this.foreignKeyConfigs.push({ref:e,actions:i}),this}unique(e,i){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=i?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,i){return this.foreignKeyConfigs.map(({ref:n,actions:t})=>iife((n,t)=>{let a=new e3(()=>({columns:[e],foreignColumns:[n()]}));return t.onUpdate&&a.onUpdate(t.onUpdate),t.onDelete&&a.onDelete(t.onDelete),a.build(i)},n,t))}buildExtraConfigColumn(e){return new e9(e,this.config)}}class e7 extends eV{constructor(e,i){i.uniqueName||(i.uniqueName=uniqueKeyName(e,[i.name])),super(e,i),this.table=e}static [eK]="PgColumn"}class e9 extends e7{static [eK]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}}class ie{static [eK]=null;constructor(e,i,n,t){this.name=e,this.keyAsName=i,this.type=n,this.indexConfig=t}name;keyAsName;type;indexConfig}class it extends e5{static [eK]="PgArrayBuilder";constructor(e,i,n){super(e,"array","PgArray"),this.config.baseBuilder=i,this.config.size=n}build(e){let i=this.config.baseBuilder.build(e);return new ia(e,this.config,i)}}class ia extends e7{constructor(e,i,n,t){super(e,i),this.baseColumn=n,this.range=t,this.size=i.size}size;static [eK]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=parsePgArray(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,i=!1){let n=e.map(e=>null===e?null:entity_is(this.baseColumn,ia)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return i?n:makePgArray(n)}}class ir extends e5{static [eK]="PgEnumObjectColumnBuilder";constructor(e,i){super(e,"string","PgEnumObjectColumn"),this.config.enum=i}build(e){return new io(e,this.config)}}class io extends e7{static [eK]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}let iu=Symbol.for("drizzle:isPgEnum");function isPgEnum(e){return!!e&&"function"==typeof e&&iu in e&&!0===e[iu]}class is extends e5{static [eK]="PgEnumColumnBuilder";constructor(e,i){super(e,"string","PgEnumColumn"),this.config.enum=i}build(e){return new il(e,this.config)}}class il extends e7{static [eK]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}class ih{static [eK]="Subquery";constructor(e,i,n,t=!1,a=[]){this._={brand:"Subquery",sql:e,selectedFields:i,alias:n,isWith:t,usedTables:a}}}class ig extends ih{static [eK]="WithSubquery"}let ic=(n,t)=>e?(i||(i=e.trace.getTracer("drizzle-orm","0.45.1")),iife((e,i)=>i.startActiveSpan(n,i=>{try{return t(i)}catch(n){throw i.setStatus({code:e.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{i.end()}}),e,i)):t(),id=Symbol.for("drizzle:ViewBaseConfig"),ip=Symbol.for("drizzle:Schema"),im=Symbol.for("drizzle:Columns"),iy=Symbol.for("drizzle:ExtraConfigColumns"),iS=Symbol.for("drizzle:OriginalName"),ib=Symbol.for("drizzle:BaseName"),iC=Symbol.for("drizzle:IsAlias"),iw=Symbol.for("drizzle:ExtraConfigBuilder"),iT=Symbol.for("drizzle:IsDrizzleTable");class ix{static [eK]="Table";static Symbol={Name:e1,Schema:ip,OriginalName:iS,Columns:im,ExtraConfigColumns:iy,BaseName:ib,IsAlias:iC,ExtraConfigBuilder:iw};[e1];[iS];[ip];[im];[iy];[ib];[iC]=!1;[iT]=!0;[iw]=void 0;constructor(e,i,n){this[e1]=this[iS]=e,this[ip]=i,this[ib]=n}}function getTableUniqueName(e){return`${e[ip]??"public"}.${e[e1]}`}class iL{static [eK]=null}function isSQLWrapper(e){return null!=e&&"function"==typeof e.getSQL}function mergeQueries(e){let i={sql:"",params:[]};for(let n of e)i.sql+=n.sql,i.params.push(...n.params),n.typings?.length&&(i.typings||(i.typings=[]),i.typings.push(...n.typings));return i}class iE{static [eK]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new i_([this])}}class i_{constructor(e){for(let i of(this.queryChunks=e,e))if(entity_is(i,ix)){let e=i[ix.Symbol.Schema];this.usedTables.push(void 0===e?i[ix.Symbol.Name]:e+"."+i[ix.Symbol.Name])}}static [eK]="SQL";decoder=iD;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return ic("drizzle.buildSQL",i=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return i?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let n=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:t,escapeName:a,escapeParam:r,prepareTyping:o,inlineParams:u,paramStartIndex:s}=n;return mergeQueries(e.map(e=>{if(entity_is(e,iE))return{sql:e.value.join(""),params:[]};if(entity_is(e,iY))return{sql:a(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let i=[new iE("(")];for(let[n,t]of e.entries())i.push(t),n<e.length-1&&i.push(new iE(", "));return i.push(new iE(")")),this.buildQueryFromSourceParams(i,n)}if(entity_is(e,i_))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:u||e.shouldInlineParams});if(entity_is(e,ix)){let i=e[ix.Symbol.Schema],n=e[ix.Symbol.Name];return{sql:void 0===i||e[iC]?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,eV)){let n=t.getColumnCasing(e);if("indexes"===i.invokeSource)return{sql:a(n),params:[]};let r=e.table[ix.Symbol.Schema];return{sql:e.table[iC]||void 0===r?a(e.table[ix.Symbol.Name])+"."+a(n):a(r)+"."+a(e.table[ix.Symbol.Name])+"."+a(n),params:[]}}if(entity_is(e,iM)){let i=e[id].schema,n=e[id].name;return{sql:void 0===i||e[id].isAlias?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,iA)){if(entity_is(e.value,iZ))return{sql:r(s.value++,e),params:[e],typings:["none"]};let i=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(entity_is(i,i_))return this.buildQueryFromSourceParams([i],n);if(u)return{sql:this.mapInlineParam(i,n),params:[]};let t=["none"];return o&&(t=[o(e.encoder)]),{sql:r(s.value++,i),params:[i],typings:t}}return entity_is(e,iZ)?{sql:r(s.value++,e),params:[e],typings:["none"]}:entity_is(e,i_.Aliased)&&void 0!==e.fieldAlias?{sql:a(e.fieldAlias),params:[]}:entity_is(e,ih)?e._.isWith?{sql:a(e._.alias),params:[]}:this.buildQueryFromSourceParams([new iE("("),e._.sql,new iE(") "),new iY(e._.alias)],n):isPgEnum(e)?e.schema?{sql:a(e.schema)+"."+a(e.enumName),params:[]}:{sql:a(e.enumName),params:[]}:isSQLWrapper(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new iE("("),e.getSQL(),new iE(")")],n):u?{sql:this.mapInlineParam(e,n),params:[]}:{sql:r(s.value++,e),params:[e],typings:["none"]}}))}mapInlineParam(e,{escapeString:i}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return i(e);if("object"==typeof e){let n=e.toString();return"[object Object]"===n?i(JSON.stringify(e)):i(n)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new i_.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class iY{constructor(e){this.value=e}static [eK]="Name";brand;getSQL(){return new i_([this])}}function isDriverValueEncoder(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue}let iD={mapFromDriverValue:e=>e},iv={mapToDriverValue:e=>e};({...iD,...iv});class iA{constructor(e,i=iv){this.value=e,this.encoder=i}static [eK]="Param";brand;getSQL(){return new i_([this])}}function sql_sql(e,...i){let n=[];for(let[t,a]of((i.length>0||e.length>0&&""!==e[0])&&n.push(new iE(e[0])),i.entries()))n.push(a,new iE(e[t+1]));return new i_(n)}(O=sql_sql||(sql_sql={})).empty=function(){return new i_([])},O.fromList=function(e){return new i_(e)},O.raw=function(e){return new i_([new iE(e)])},O.join=function(e,i){let n=[];for(let[t,a]of e.entries())t>0&&void 0!==i&&n.push(i),n.push(a);return new i_(n)},O.identifier=function(e){return new iY(e)},O.placeholder=function(e){return new iZ(e)},O.param=function(e,i){return new iA(e,i)};var iN=i_||(i_={});class iP{constructor(e,i){this.sql=e,this.fieldAlias=i}static [eK]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new iP(this.sql,this.fieldAlias)}}iN.Aliased=iP;class iZ{constructor(e){this.name=e}static [eK]="Placeholder";getSQL(){return new i_([this])}}function fillPlaceholders(e,i){return e.map(e=>{if(entity_is(e,iZ)){if(!(e.name in i))throw Error(`No value for placeholder "${e.name}" was provided`);return i[e.name]}if(entity_is(e,iA)&&entity_is(e.value,iZ)){if(!(e.value.name in i))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(i[e.value.name])}return e})}let iR=Symbol.for("drizzle:IsDrizzleView");class iM{static [eK]="View";[id];[iR]=!0;constructor({name:e,schema:i,selectedFields:n,query:t}){this[id]={name:e,originalName:e,schema:i,selectedFields:n,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new i_([this])}}eV.prototype.getSQL=function(){return new i_([this])},ix.prototype.getSQL=function(){return new i_([this])},ih.prototype.getSQL=function(){return new i_([this])};class iJ{constructor(e){this.table=e}static [eK]="ColumnAliasProxyHandler";get(e,i){return"table"===i?this.table:e[i]}}class ik{constructor(e,i){this.alias=e,this.replaceOriginalName=i}static [eK]="TableAliasProxyHandler";get(e,i){if(i===ix.Symbol.IsAlias)return!0;if(i===ix.Symbol.Name||this.replaceOriginalName&&i===ix.Symbol.OriginalName)return this.alias;if(i===id)return{...e[id],name:this.alias,isAlias:!0};if(i===ix.Symbol.Columns){let i=e[ix.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map(t=>{n[t]=new Proxy(i[t],new iJ(new Proxy(e,this)))}),n}let n=e[i];return entity_is(n,eV)?new Proxy(n,new iJ(new Proxy(e,this))):n}}class iB{constructor(e){this.alias=e}static [eK]=null;get(e,i){return"sourceTable"===i?aliasedTable(e.sourceTable,this.alias):e[i]}}function aliasedTable(e,i){return new Proxy(e,new ik(i,!1))}function aliasedTableColumn(e,i){return new Proxy(e,new iJ(new Proxy(e.table,new ik(i,!1))))}function mapColumnsInAliasedSQLToAlias(e,i){return new i_.Aliased(mapColumnsInSQLToAlias(e.sql,i),e.fieldAlias)}function mapColumnsInSQLToAlias(e,i){return sql_sql.join(e.queryChunks.map(e=>entity_is(e,eV)?aliasedTableColumn(e,i):entity_is(e,i_)?mapColumnsInSQLToAlias(e,i):entity_is(e,i_.Aliased)?mapColumnsInAliasedSQLToAlias(e,i):e))}function toSnakeCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function toCamelCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,i,n)=>e+(0===n?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`),"")}function noopCase(e){return e}class iH{static [eK]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?toSnakeCase:"camelCase"===e?toCamelCase:noopCase}getColumnCasing(e){if(!e.keyAsName)return e.name;let i=e.table[ix.Symbol.Schema]??"public",n=e.table[ix.Symbol.OriginalName],t=`${i}.${n}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let i=e[ix.Symbol.Schema]??"public",n=e[ix.Symbol.OriginalName],t=`${i}.${n}`;if(!this.cachedTables[t]){for(let i of Object.values(e[ix.Symbol.Columns])){let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class iF extends Error{static [eK]="DrizzleError";constructor({message:e,cause:i}){super(e),this.name="DrizzleError",this.cause=i}}class iX extends Error{constructor(e,i,n){super(`Failed query: ${e}
|
|
1
|
+
let e,i,n,t,a,r,o,u,s,l,h,g,c,d;import*as p from"buffer";import*as f from"crypto";import*as m from"events";import*as y from"fs";import*as S from"node:fs";import*as b from"node:fs/promises";import*as C from"node:stream";import*as w from"os";import*as T from"path";import*as x from"stream";import*as L from"zlib";import{__webpack_require__ as E}from"./rslib-runtime.mjs";import _ from"axios";import{URL as Y,parse as D}from"url";import{ChatOpenAI as v}from"@langchain/openai";import{AIMessage as A,HumanMessage as N,SystemMessage as P}from"@langchain/core/messages";import Z from"pg";import{exec as R,execSync as M}from"child_process";import{env as J,versions as k}from"process";import{Agent as B,request as H}from"http";import{Agent as F,request as X}from"https";E.add({"./node_modules/dotenv/lib/main.js"(e,i,n){let t=n("fs"),a=n("path"),r=n("os"),o=n("crypto"),u=n("./node_modules/dotenv/package.json").version,s=["\uD83D\uDD10 encrypt with Dotenvx: https://dotenvx.com","\uD83D\uDD10 prevent committing .env to code: https://dotenvx.com/precommit","\uD83D\uDD10 prevent building .env in docker: https://dotenvx.com/prebuild","\uD83D\uDCE1 add observability to secrets: https://dotenvx.com/ops","\uD83D\uDC65 sync secrets across teammates & machines: https://dotenvx.com/ops","\uD83D\uDDC2️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","\uD83D\uDD04 add secrets lifecycle management: https://dotenvx.com/ops","\uD83D\uDD11 add access controls to secrets: https://dotenvx.com/ops","\uD83D\uDEE0️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function _getRandomTip(){return s[Math.floor(Math.random()*s.length)]}function parseBoolean(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}function supportsAnsi(){return process.stdout.isTTY}function dim(e){return supportsAnsi()?`\x1b[2m${e}\x1b[0m`:e}let l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function _warn(e){console.error(`[dotenv@${u}][WARN] ${e}`)}function _debug(e){console.log(`[dotenv@${u}][DEBUG] ${e}`)}function _log(e){console.log(`[dotenv@${u}] ${e}`)}function _dotenvKey(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _instructions(e,i){let n;try{n=new URL(i)}catch(e){if("ERR_INVALID_URL"===e.code){let e=Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}let t=n.password;if(!t){let e=Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}let a=n.searchParams.get("environment");if(!a){let e=Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}let r=`DOTENV_VAULT_${a.toUpperCase()}`,o=e.parsed[r];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:o,key:t}}function _vaultPath(e){let i=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)t.existsSync(n)&&(i=n.endsWith(".vault")?n:`${n}.vault`);else i=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else i=a.resolve(process.cwd(),".env.vault");return t.existsSync(i)?i:null}function _resolveHome(e){return"~"===e[0]?a.join(r.homedir(),e.slice(1)):e}let h={configDotenv:function(e){let i,n=a.resolve(process.cwd(),".env"),r="utf8",o=process.env;e&&null!=e.processEnv&&(o=e.processEnv);let u=parseBoolean(o.DOTENV_CONFIG_DEBUG||e&&e.debug),s=parseBoolean(o.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?r=e.encoding:u&&_debug("No encoding is specified. UTF-8 is used by default");let l=[n];if(e&&e.path)if(Array.isArray(e.path))for(let i of(l=[],e.path))l.push(_resolveHome(i));else l=[_resolveHome(e.path)];let g={};for(let n of l)try{let i=h.parse(t.readFileSync(n,{encoding:r}));h.populate(g,i,e)}catch(e){u&&_debug(`Failed to load ${n} ${e.message}`),i=e}let c=h.populate(o,g,e);if(u=parseBoolean(o.DOTENV_CONFIG_DEBUG||u),s=parseBoolean(o.DOTENV_CONFIG_QUIET||s),u||!s){let e=Object.keys(c).length,n=[];for(let e of l)try{let i=a.relative(process.cwd(),e);n.push(i)}catch(n){u&&_debug(`Failed to load ${e} ${n.message}`),i=n}_log(`injecting env (${e}) from ${n.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`)}return i?{parsed:g,error:i}:{parsed:g}},_configVault:function(e){let i=parseBoolean(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=parseBoolean(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(i||!n)&&_log("Loading env from encrypted .env.vault");let t=h._parseVault(e),a=process.env;return e&&null!=e.processEnv&&(a=e.processEnv),h.populate(a,t,e),{parsed:t}},_parseVault:function(e){let i,n=_vaultPath(e=e||{});e.path=n;let t=h.configDotenv(e);if(!t.parsed){let e=Error(`MISSING_DATA: Cannot parse ${n} for an unknown reason`);throw e.code="MISSING_DATA",e}let a=_dotenvKey(e).split(","),r=a.length;for(let e=0;e<r;e++)try{let n=a[e].trim(),r=_instructions(t,n);i=h.decrypt(r.ciphertext,r.key);break}catch(i){if(e+1>=r)throw i}return h.parse(i)},config:function(e){if(0===_dotenvKey(e).length)return h.configDotenv(e);let i=_vaultPath(e);return i?h._configVault(e):(_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${i}. Did you forget to build it?`),h.configDotenv(e))},decrypt:function(e,i){let n=Buffer.from(i.slice(-64),"hex"),t=Buffer.from(e,"base64"),a=t.subarray(0,12),r=t.subarray(-16);t=t.subarray(12,-16);try{let e=o.createDecipheriv("aes-256-gcm",n,a);return e.setAuthTag(r),`${e.update(t)}${e.final()}`}catch(t){let e=t instanceof RangeError,i="Invalid key length"===t.message,n="Unsupported state or unable to authenticate data"===t.message;if(e||i){let e=Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){let e=Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw t}},parse:function(e){let i,n={},t=e.toString();for(t=t.replace(/\r\n?/mg,"\n");null!=(i=l.exec(t));){let e=i[1],t=i[2]||"",a=(t=t.trim())[0];t=t.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),'"'===a&&(t=(t=t.replace(/\\n/g,"\n")).replace(/\\r/g,"\r")),n[e]=t}return n},populate:function(e,i,n={}){let t=!!(n&&n.debug),a=!!(n&&n.override),r={};if("object"!=typeof i){let e=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(let n of Object.keys(i))Object.prototype.hasOwnProperty.call(e,n)?(!0===a&&(e[n]=i[n],r[n]=i[n]),t&&(!0===a?_debug(`"${n}" is already defined and WAS overwritten`):_debug(`"${n}" is already defined and was NOT overwritten`))):(e[n]=i[n],r[n]=i[n]);return r}};e.exports.configDotenv=h.configDotenv,e.exports._configVault=h._configVault,e.exports._parseVault=h._parseVault,e.exports.config=h.config,e.exports.decrypt=h.decrypt,e.exports.parse=h.parse,e.exports.populate=h.populate,e.exports=h},buffer(e){e.exports=p},crypto(e){e.exports=f},events(e){e.exports=m},fs(e){e.exports=y},"node:fs"(e){e.exports=S},"node:fs/promises"(e){e.exports=b},"node:stream"(e){e.exports=C},os(e){e.exports=w},path(e){e.exports=T},stream(e){e.exports=x},zlib(e){e.exports=L},"./node_modules/dotenv/package.json"(e){e.exports=JSON.parse('{"name":"dotenv","version":"17.2.3","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')}});var I,O,Q,U,G,q,$,K,z,W,j,V,ee,ei,en,et,ea,er,eo,eu,es,el,eh,eg,ec,ed,ep,ef,em={};E.r(em),E.d(em,{T:()=>eC});var ey={};E.r(ey),E.d(ey,{n:()=>e_,p:()=>eY});var eS={};E.r(eS),E.d(eS,{F:()=>mU});var eb={};E.r(eb),E.d(eb,{c:()=>eQ});class eC{apiKey;baseUrl;modelBaseUrl;retryTimes;retryDelay;timeout;constructor(e){this.apiKey=e?.apiKey||process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"",this.baseUrl=e?.baseUrl||process.env.COZE_INTEGRATION_BASE_URL||"",this.modelBaseUrl=e?.modelBaseUrl||process.env.COZE_INTEGRATION_MODEL_BASE_URL||"",this.retryTimes=e?.retryTimes??3,this.retryDelay=e?.retryDelay??1,this.timeout=e?.timeout??9e5}validate(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.")}getHeaders(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.");return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}}class ew extends Error{constructor(e){super(e),this.name="ConfigurationError"}}class eT extends Error{statusCode;response;constructor(e,i,n){super(e),this.name="APIError",this.statusCode=i,this.response=n}}class ex extends Error{originalError;constructor(e,i){super(e),this.originalError=i,this.name="NetworkError"}}class eL extends Error{constructor(e){super(e),this.name="ValidationError"}}class eE{config;axiosInstance;verbose;constructor(e,i,n=!1){this.config=e||new eC,this.verbose=n,this.axiosInstance=_.create({timeout:this.config.timeout,headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...i}})}async request(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a.data}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eT(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(_.isAxiosError(a)&&a.response)throw new eT(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new ex(a.message);throw new ex("Request failed after retries")}async requestWithResponse(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eT(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(_.isAxiosError(a)&&a.response)throw new eT(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new ex(a.message);throw new ex("Request failed after retries")}sanitizeHeaders(e){let i=["authorization","auth","api-key","apikey","api_key","x-api-key","x-auth-token","token","secret","password","passwd","pwd"],n={};for(let[t,a]of Object.entries(e)){let e=t.toLowerCase();i.some(i=>e.includes(i))?n[t]="***":n[t]=a}return n}logRequest(e,i,n,t){console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE4 HTTP Request"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Method: ${e}`),console.log(`URL: ${i}`);let a={};Object.assign(a,this.axiosInstance.defaults.headers.common||{},this.axiosInstance.defaults.headers[e.toLowerCase()]||{},t?.headers||{});let r=this.sanitizeHeaders(a);for(let[e,i]of(console.log("\nHeaders:"),Object.entries(r)))console.log(` ${e}: ${i}`);n&&(console.log("\nBody:"),console.log(JSON.stringify(n,null,2))),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}logResponse(e){if(console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE5 HTTP Response"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Status: ${e.status} ${e.statusText}`),e.headers)for(let[i,n]of(console.log("\nHeaders:"),Object.entries(e.headers)))console.log(` ${i}: ${n}`);if(e.data){console.log("\nBody:");let i="string"==typeof e.data?e.data:JSON.stringify(e.data,null,2);console.log(i.length>1e3?i.substring(0,1e3)+"\n... (truncated)":i)}console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}sleep(e){return new Promise(i=>setTimeout(i,e))}}let e_=["x-tt-logid","x-tt-env","x-use-ppe","x-tt-env-fe","x-run-mode","rpc-persist-res-rec-biz-scene","rpc-persist-coze-record-root-id","rpc-persist-res-rec-root-entity-type","rpc-persist-res-rec-root-entity-id","rpc-persist-res-rec-ext-info"];class eY{static extractForwardHeaders(e){let i={};return e instanceof Headers?e_.forEach(n=>{let t=e.get(n);t&&(i[n]=t)}):e_.forEach(n=>{let t=e[n]||e[n.toLowerCase()];t&&(i[n]=t)}),i}}let eD=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),ev=new Set(["http:","https:"]),eA=[["code.coze.cn","/api/sandbox/coze_coding/file/proxy"]];class eN extends eL{url;constructor(e,i){super(e),this.name="URLValidationError",this.url=i}}async function url_utils_validateUrl(e,i){let n,{allowHeadCheck:t=!0,timeout:a=5e3}=i||{};if(!e||"string"!=typeof e)throw new eN("URL cannot be empty","string"==typeof e?e:void 0);if(!(e=e.trim()))throw new eN("URL cannot be empty",e);try{n=new Y(e)}catch{if(isLocalPath(e))throw new eN(`The input appears to be a local file path: ${e}. Please upload it using the Storage skill first to get a persistent HTTP URL.`,e);throw new eN(`Invalid URL format: ${e}`,e)}if(!ev.has(n.protocol))throw new eN(`Unsupported scheme '${n.protocol}', only http/https allowed`,e);let r=n.hostname;if(!r)throw new eN(`Cannot extract hostname from URL: ${e}`,e);if(eD.has(r.toLowerCase())||eD.has(r.replace(/^\[|\]$/g,"").toLowerCase()))throw new eN(`Access to local address is not allowed: ${r}`,e);if(isEphemeralUrl(e))throw new eN("This URL appears to be a temporary sandbox proxy URL that may expire. Please download the file and upload it to persistent storage (Storage skill) first.",e);return t&&await headCheck(e,a),e}function isEphemeralUrl(e){try{let i=new Y(e),n=i.hostname.toLowerCase(),t=i.pathname;for(let[e,i]of eA)if(n===e&&t.startsWith(i))return!0}catch{}return!1}function isLocalPath(e){return!!e&&!!(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.length>=3&&/^[a-zA-Z]$/.test(e[0])&&":"===e[1]&&("/"===e[2]||"\\"===e[2]))}function validateUrlSync(e){let i;if(!e||"string"!=typeof e)throw new eN("URL cannot be empty","string"==typeof e?e:void 0);if(!(e=e.trim()))throw new eN("URL cannot be empty",e);try{i=new Y(e)}catch{if(isLocalPath(e))throw new eN(`The input appears to be a local file path: ${e}. Please upload it using the Storage skill first to get a persistent HTTP URL.`,e);throw new eN(`Invalid URL format: ${e}`,e)}if(!ev.has(i.protocol))throw new eN(`Unsupported scheme '${i.protocol}', only http/https allowed`,e);let n=i.hostname;if(!n)throw new eN(`Cannot extract hostname from URL: ${e}`,e);if(eD.has(n.toLowerCase())||eD.has(n.replace(/^\[|\]$/g,"").toLowerCase()))throw new eN(`Access to local address is not allowed: ${n}`,e);return e}async function headCheck(e,i){let n=new AbortController,t=setTimeout(()=>n.abort(),i);try{let a=await fetch(e,{method:"HEAD",signal:n.signal,headers:{"User-Agent":"CozeSDK-URLValidator/1.0"}});if(405===a.status){clearTimeout(t),await rangeCheck(e,i);return}if(!a.ok)throw new eN(`URL is not reachable: HTTP ${a.status}`,e)}catch(n){if(n instanceof eN)throw n;if("AbortError"===n.name)throw new eN(`URL is not reachable (request timed out after ${i}ms). Please check if the URL is correct and accessible.`,e);throw new eN(`URL is not reachable (${n.message}). Please check if the URL is correct and accessible.`,e)}finally{clearTimeout(t)}}async function rangeCheck(e,i){let n=new AbortController,t=setTimeout(()=>n.abort(),i);try{let i=await fetch(e,{method:"GET",signal:n.signal,headers:{"User-Agent":"CozeSDK-URLValidator/1.0",Range:"bytes=0-0"}});if(405===i.status||400===i.status)return;if(i.status>=400)throw new eN(`URL is not reachable: HTTP ${i.status}`,e)}catch(n){if(n instanceof eN)throw n;if("AbortError"===n.name)throw new eN(`URL is not reachable (request timed out after ${i}ms). Please check if the URL is correct and accessible.`,e);throw new eN(`URL is not reachable (${n.message}). Please check if the URL is correct and accessible.`,e)}finally{clearTimeout(t)}}class eP{static DEFAULT_MODEL="doubao-seedream-5-0-260128";static DEFAULT_SIZE="2K";static DEFAULT_CUSTOM_SIZE="2048x2048";static DEFAULT_WATERMARK=!0;static DEFAULT_RESPONSE_FORMAT="url";static DEFAULT_OPTIMIZE_PROMPT_MODE="standard";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION="disabled";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES=15;static MIN_TOTAL_PIXELS=3686400;static MAX_TOTAL_PIXELS=0x1000000;static MIN_ASPECT_RATIO=1/16;static MAX_ASPECT_RATIO=16;static PRESET_SIZES=["2K","4K"]}function validateImageSize(e){if(eP.PRESET_SIZES.includes(e))return e;let i=e.match(/^(\d+)x(\d+)$/);if(!i)throw Error(`Invalid size format. Must be ${JSON.stringify(eP.PRESET_SIZES)} or 'WIDTHxHEIGHT' format (e.g., 2048x2048). Got: ${e}`);let n=parseInt(i[1],10),t=parseInt(i[2],10);if(n<=0||t<=0)throw Error(`Width and height must be positive integers. Got: ${e}`);let a=n*t;if(a<eP.MIN_TOTAL_PIXELS||a>eP.MAX_TOTAL_PIXELS)throw Error(`Total pixels must be between ${eP.MIN_TOTAL_PIXELS.toLocaleString()} and ${eP.MAX_TOTAL_PIXELS.toLocaleString()}. Got: ${a.toLocaleString()} (${n}x${t})`);let r=n/t;if(r<eP.MIN_ASPECT_RATIO||r>eP.MAX_ASPECT_RATIO)throw Error(`Aspect ratio must be between 1:16 and 16:1. Got: ${n}:${t} (${r.toFixed(2)})`);return e}function validateImageSizeOrDefault(e){try{return validateImageSize(e)}catch{return eP.DEFAULT_SIZE}}class eZ{response;constructor(e){this.response=e}get success(){return!this.response.error&&this.response.data.every(e=>!e.error)}get imageUrls(){return this.response.data.filter(e=>e.url).map(e=>e.url)}get imageB64List(){return this.response.data.filter(e=>e.b64_json).map(e=>e.b64_json)}get errorMessages(){let e=[];for(let i of(this.response.error&&e.push(`API Error: ${this.response.error.message||"Unknown error"}`),this.response.data))i.error&&e.push(`Image generation error: ${i.error.message||"Unknown error"}`);return e}}function buildImageGenerationApiRequest(e,i){let n=validateImageSizeOrDefault(e.size||eP.DEFAULT_SIZE);return{model:i,prompt:e.prompt,size:n,watermark:e.watermark??eP.DEFAULT_WATERMARK,image:e.image,response_format:e.responseFormat||eP.DEFAULT_RESPONSE_FORMAT,optimize_prompt_options:{mode:e.optimizePromptMode||eP.DEFAULT_OPTIMIZE_PROMPT_MODE},sequential_image_generation:e.sequentialImageGeneration||eP.DEFAULT_SEQUENTIAL_IMAGE_GENERATION,sequential_image_generation_options:{max_images:e.sequentialImageGenerationMaxImages||eP.DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES}}}class eR extends eE{constructor(e,i,n=!1){super(e,i,n)}async generate(e){if(e.image)if(Array.isArray(e.image))for(let i=0;i<e.image.length;i++)e.image[i]=await url_utils_validateUrl(e.image[i]);else e.image=await url_utils_validateUrl(e.image);let i=e.model||eP.DEFAULT_MODEL,n=buildImageGenerationApiRequest(e,i),t=await this.request("POST",`${this.config.baseUrl}/api/v3/images/generations`,n);if(t.error)throw new eT(`API returned error: ${t.error.message||"Unknown error"}`,t.error.code?parseInt(t.error.code):500,t.error);for(let e of t.data)if(e.error)throw new eT(`Image generation failed: ${e.error.message||"Unknown error"}`,e.error.code?parseInt(e.error.code):500,e.error);return t}async batchGenerate(e){return Promise.all(e.map(e=>this.generate(e)))}getResponseHelper(e){return new eZ(e)}}function convertToApiFormat(e){let i={};return e.query&&(i.Query=e.query),e.search_type&&(i.SearchType=e.search_type),void 0!==e.count&&(i.Count=e.count),void 0!==e.need_summary&&(i.NeedSummary=e.need_summary),e.time_range&&(i.TimeRange=e.time_range),e.filter&&(i.Filter={NeedContent:e.filter.need_content||!1,NeedUrl:e.filter.need_url||!1,Sites:e.filter.sites,BlockHosts:e.filter.block_hosts}),i}function convertFromApiFormat(e){let i={};return void 0!==e.Id&&(i.id=e.Id),void 0!==e.SortId&&(i.sort_id=e.SortId),void 0!==e.Title&&(i.title=e.Title),void 0!==e.SiteName&&(i.site_name=e.SiteName),void 0!==e.Url&&(i.url=e.Url),void 0!==e.Snippet&&(i.snippet=e.Snippet),void 0!==e.Summary&&(i.summary=e.Summary),void 0!==e.Content&&(i.content=e.Content),void 0!==e.PublishTime&&(i.publish_time=e.PublishTime),void 0!==e.LogoUrl&&(i.logo_url=e.LogoUrl),void 0!==e.RankScore&&(i.rank_score=e.RankScore),void 0!==e.AuthInfoDes&&(i.auth_info_des=e.AuthInfoDes),void 0!==e.AuthInfoLevel&&(i.auth_info_level=e.AuthInfoLevel),e.Image&&(i.image={url:e.Image.Url,width:e.Image.Width,height:e.Image.Height,shape:e.Image.Shape}),i}class eM extends eE{constructor(e,i,n=!1){super(e,i,n)}async search(e){let i,n=convertToApiFormat(e),t=await this.request("POST",`${this.config.baseUrl}/api/search_api/web_search`,n),a=t.ResponseMetadata||{};if(a.Error)throw new eT(`Search failed: ${a.Error}`,500,a.Error);let r=t.Result||{},o=[];if(r.WebResults)for(let e of r.WebResults)o.push(convertFromApiFormat(e));let u=[];if(r.ImageResults)for(let e of r.ImageResults)u.push(convertFromApiFormat(e));return r.Choices&&r.Choices.length>0&&(i=r.Choices[0].Message?.Content),{web_items:o,image_items:u,summary:i}}async webSearch(e,i=10,n=!0){return this.search({query:e,search_type:"web",count:i,need_summary:n})}async webSearchWithSummary(e,i=10){return this.search({query:e,search_type:"web_summary",count:i,need_summary:!0})}async imageSearch(e,i=10){return this.search({query:e,search_type:"image",count:i,need_summary:!1})}async advancedSearch(e,i={}){let n={need_content:i.needContent,need_url:i.needUrl,sites:i.sites,block_hosts:i.blockHosts};return this.search({query:e,search_type:i.searchType||"web",count:i.count||10,filter:n,need_summary:void 0===i.needSummary||i.needSummary,time_range:i.timeRange})}}class eJ{static DEFAULT_SPEAKER="zh_female_xiaohe_uranus_bigtts";static DEFAULT_AUDIO_FORMAT="mp3";static DEFAULT_SAMPLE_RATE=24e3;static DEFAULT_SPEECH_RATE=0;static DEFAULT_LOUDNESS_RATE=0}function buildTTSApiRequest(e){let i={user:{uid:e.uid},req_params:{speaker:e.speaker||eJ.DEFAULT_SPEAKER,audio_params:{format:e.audioFormat||eJ.DEFAULT_AUDIO_FORMAT,sample_rate:e.sampleRate||eJ.DEFAULT_SAMPLE_RATE,speech_rate:e.speechRate??eJ.DEFAULT_SPEECH_RATE,loudness_rate:e.loudnessRate??eJ.DEFAULT_LOUDNESS_RATE}}};return e.text?i.req_params.text=e.text:e.ssml&&(i.req_params.ssml=e.ssml),i}function buildASRApiRequest(e){let i={};return e.url?i.url=e.url:e.base64Data&&(i.data=e.base64Data),{user:{uid:e.uid},audio:i}}class ek extends eE{constructor(e,i,n=!1){super(e,i,n)}async synthesize(e){if(!e.text&&!e.ssml)throw new eL("必须提供 text 或 ssml 其中之一");let i=buildTTSApiRequest(e),n={...this.config.getHeaders(),Connection:"keep-alive"};try{let e=await _.post(`${this.config.baseUrl}/api/v3/tts/unidirectional`,i,{headers:n,responseType:"stream",timeout:this.config.timeout});return await this.processStreamResponse(e)}catch(e){if(e.response)throw new eT(`TTS 请求失败: ${e.message}`,e.response.status,e.response.data);throw new eT(`TTS 请求异常: ${e.message}`,500)}}async processStreamResponse(e){return new Promise((i,n)=>{let t="",a=0,r="";e.data.on("data",e=>{let o=(r+=e.toString("utf-8")).split("\n");for(let e of(r=o.pop()||"",o))if(e.trim()&&e.startsWith("data:"))try{let r=e.replace("data:","").trim();if(!r)continue;let o=JSON.parse(r);if(0===o.code&&o.data){let e=Buffer.from(o.data,"base64");a+=e.length}else if(2e7===o.code){o.url&&(t=o.url),i({audioUri:t,audioSize:a});return}else if(o.code>0)return void n(new eT(`合成音频失败: ${o.message||""}`,o.code))}catch(e){n(new eT(`响应解析失败: ${e.message}`,500));return}}),e.data.on("end",()=>{t||0!==a?i({audioUri:t,audioSize:a}):n(new eT("未收到完整的音频数据",500))}),e.data.on("error",e=>{n(new eT(`流处理错误: ${e.message}`,500))})})}}class eB extends eE{constructor(e,i,n=!1){super(e,i,n)}async recognize(e){if(!e.url&&!e.base64Data)throw new eL("必须提供 url 或 base64Data 其中之一");let i=buildASRApiRequest(e);try{let e=await this.requestWithResponse("POST",`${this.config.baseUrl}/api/v3/auc/bigmodel/recognize/flash`,i),n=e.headers["x-api-status-code"]||"0",t=e.headers["x-api-message"]||"";if("20000000"!==n)throw new eT(`ASR 识别失败,状态码: ${n}, 错误信息: ${t}`,e.status,{code:n,message:t});let a=e.data.result||{};return{text:a.text||"",duration:a.duration,utterances:a.utterances,rawData:e.data}}catch(e){if(e instanceof eT)throw e;throw new eT(`ASR 请求异常: ${e.message}`,500)}}}class eH{static DEFAULT_MODEL="doubao-seedance-2-0-260128";static DEFAULT_RESOLUTION="720p";static DEFAULT_RATIO="16:9";static DEFAULT_DURATION=5;static DEFAULT_WATERMARK=!0;static DEFAULT_CAMERA_FIXED=!1;static DEFAULT_GENERATE_AUDIO=!0}class eF extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}static validateContentItems(e,i){let n=0,t=0,a=0,r=0,o=0;for(let i of e)"image_url"===i.type?"first_frame"===i.role?n+=1:"last_frame"===i.role?t+=1:"reference_image"===i.role&&(a+=1):"video_url"===i.type?r+=1:"audio_url"===i.type&&(o+=1);let u=n>0||t>0,s=a>0||r>0||o>0;if(u&&s)throw new eT("图生视频-首尾帧 与 多模态参考生视频 为互斥场景,不可混用。请只使用 first_frame/last_frame 角色,或只使用 reference_image/reference_video/reference_audio。如需『首尾帧 + 多模态参考』效果,可在多模态场景中通过提示词指定参考图作为首帧/尾帧。",400);if(s){if("doubao-seedance-2-0-260128"!==i)throw new eT(`多模态参考生视频(reference_image/reference_video/reference_audio)仅支持 doubao-seedance-2-0-260128 模型,当前模型为 ${i}`,400);if(0===a&&0===r)throw new eT("多模态参考生视频至少需要包含 1 个 reference_image 或 reference_video,不可单独输入 reference_audio。",400);if(a>9)throw new eT(`reference_image 数量超出限制:最多 9 个,当前 ${a} 个`,400);if(r>3)throw new eT(`reference_video 数量超出限制:最多 3 个,当前 ${r} 个`,400);if(o>3)throw new eT(`reference_audio 数量超出限制:最多 3 个,当前 ${o} 个`,400)}if(u){if(n>1)throw new eT(`first_frame 角色至多 1 个,当前 ${n} 个`,400);if(t>1)throw new eT(`last_frame 角色至多 1 个,当前 ${t} 个`,400);if(t>0&&0===n)throw new eT("提供 last_frame 时必须同时提供 first_frame",400)}}async videoGeneration(e,i){let n=(i?.maxWaitTime??900)*1e3,t=i?.model||eH.DEFAULT_MODEL;for(let i of(eF.validateContentItems(e,t),e))"image_url"===i.type?i.image_url.url=await url_utils_validateUrl(i.image_url.url):"video_url"===i.type?i.video_url.url=await url_utils_validateUrl(i.video_url.url):"audio_url"===i.type&&(i.audio_url.url=await url_utils_validateUrl(i.audio_url.url));let a={model:t,content:e};i?.callbackUrl&&(a.callback_url=i.callbackUrl),i?.returnLastFrame&&(a.return_last_frame=i.returnLastFrame),a.resolution=i?.resolution??eH.DEFAULT_RESOLUTION,a.ratio=i?.ratio??eH.DEFAULT_RATIO,a.duration=i?.duration??eH.DEFAULT_DURATION,a.watermark=i?.watermark??eH.DEFAULT_WATERMARK,i?.seed!==void 0&&(a.seed=i.seed),a.camerafixed=i?.camerafixed??eH.DEFAULT_CAMERA_FIXED,a.generate_audio=i?.generateAudio??eH.DEFAULT_GENERATE_AUDIO;let r=null,o=0;for(;o<3;)try{if(!(r=(await this.request("POST",`${this.baseUrl}/api/v3/contents/generations/tasks`,a)).id))throw new eT("创建视频生成任务失败:响应中缺少任务ID",500);this.verbose&&console.log(`视频生成任务创建成功,任务ID: ${r}`);break}catch(i){o++;let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`创建视频生成任务失败(尝试 ${o}/3): ${e}`),o>=3)throw new eT(`创建视频生成任务失败,已重试3次: ${e}`,500);if(e.toLowerCase().includes("rate limit")||e.includes("429")){let e=Math.min(2**o*1e3,1e4);this.verbose&&console.warn(`遇到速率限制,等待 ${e/1e3} 秒后重试...`),await this.sleep(e)}else if(e.toLowerCase().includes("timeout"))this.verbose&&console.warn("请求超时,等待 2 秒后重试..."),await this.sleep(2e3);else throw i}let u=Date.now(),s=0;for(;Date.now()-u<n;){s++;try{let e=await this.request("GET",`${this.baseUrl}/api/v3/contents/generations/tasks/${r}`),i=e.status;if(this.verbose&&console.log(`任务 ${r} 状态检查 #${s}: ${i}`),"succeeded"===i){let i=e.content?.video_url||null,n=e.content?.last_frame_url||"";if(!i)throw new eT(`视频生成成功但响应中缺少视频URL,任务ID: ${r}`,500);return this.verbose&&console.log(`视频生成成功,任务ID: ${r}, 视频URL: ${i}`),{videoUrl:i,response:e,lastFrameUrl:n}}if("failed"===i){let i=e.error_message||"未知错误";throw this.verbose&&console.error(`视频生成失败,任务ID: ${r}, 错误: ${i}`),new eT(`视频生成失败: ${i}`,500)}if("cancelled"===i)return this.verbose&&console.warn(`视频生成任务被取消,任务ID: ${r}`),{videoUrl:null,response:e,lastFrameUrl:""};else if("queued"===i||"running"===i){await this.sleep(5e3);continue}else{this.verbose&&console.warn(`未知的任务状态: ${i},任务ID: ${r}`),await this.sleep(5e3);continue}}catch(i){let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`查询任务状态失败,任务ID: ${r}, 错误: ${e}`),e.toLowerCase().includes("not found")||e.includes("404"))throw new eT(`任务不存在或已过期,任务ID: ${r}`,404);if(Date.now()-u>=n)throw i;await this.sleep(5e3);continue}}let l=Math.floor((Date.now()-u)/1e3);throw this.verbose&&console.error(`视频生成超时,任务ID: ${r}, 已等待: ${l}秒`),new eT(`视频生成超时,已等待 ${l} 秒,任务ID: ${r}`,408)}async videoGenerationAsync(e,i){return this.videoGeneration(e,i)}}class eX{static DEFAULT_URL_EXPIRE=86400;static MAX_URL_EXPIRE=2592e3;static MIN_URL_EXPIRE=1;static MIN_AUDIO_URL_EXPIRE=3600;static DEFAULT_FONT_TYPE="1525745";static DEFAULT_FONT_SIZE=36;static DEFAULT_FONT_COLOR="#FFFFFFFF";static DEFAULT_BACKGROUND_COLOR="#00000000";static DEFAULT_BACKGROUND_BORDER_WIDTH=0;static DEFAULT_FONT_POS_HEIGHT="10%";static DEFAULT_FONT_POS_X="0";static DEFAULT_FONT_POS_Y="90%";static DEFAULT_FONT_POS_WIDTH="100%";static DEFAULT_SYNC_METHOD="trim";static DEFAULT_SYNC_MODE="video";static DEFAULT_SUBTITLE_TYPE="srt";static DEFAULT_AUDIO_FORMAT="m4a"}class eI extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async extractByKeyFrame(e){e=await url_utils_validateUrl(e);let i=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_key_frame`,{url:e});if(0!==i.code)throw new eT(`Key frame extraction failed: ${i.msg||"Unknown error"}`,i.code);return i}async extractByInterval(e,i){e=await url_utils_validateUrl(e);let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_interval`,{url:e,interval_ms:i});if(0!==n.code)throw new eT(`Interval frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}async extractByCount(e,i){e=await url_utils_validateUrl(e);let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_count`,{url:e,count:i});if(0!==n.code)throw new eT(`Count-based frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}}class eO extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}validateUrlExpire(e,i=eX.MIN_URL_EXPIRE){if(void 0===e)return eX.DEFAULT_URL_EXPIRE;if(e<i||e>eX.MAX_URL_EXPIRE)throw new eT(`url_expire must be between ${i} and ${eX.MAX_URL_EXPIRE} seconds`,400);return e}async addSubtitles(e,i,n){e=await url_utils_validateUrl(e),n?.subtitleUrl&&(n.subtitleUrl=await url_utils_validateUrl(n.subtitleUrl));let t=this.validateUrlExpire(n?.urlExpire),a={video:e,subtitle_config:{background_border_width:i.background_border_width??eX.DEFAULT_BACKGROUND_BORDER_WIDTH,font_type:i.font_type??eX.DEFAULT_FONT_TYPE,font_pos_config:{height:i.font_pos_config.height??eX.DEFAULT_FONT_POS_HEIGHT,pos_x:i.font_pos_config.pos_x??eX.DEFAULT_FONT_POS_X,pos_y:i.font_pos_config.pos_y??eX.DEFAULT_FONT_POS_Y,width:i.font_pos_config.width??eX.DEFAULT_FONT_POS_WIDTH}},url_expire:t};void 0!==i.border_width&&(a.subtitle_config.border_width=i.border_width),void 0!==i.font_color&&(a.subtitle_config.font_color=i.font_color),void 0!==i.font_size&&(a.subtitle_config.font_size=i.font_size),void 0!==i.background_color&&(a.subtitle_config.background_color=i.background_color),void 0!==i.border_color&&(a.subtitle_config.border_color=i.border_color),n?.subtitleUrl&&(a.subtitle_url=n.subtitleUrl),n?.textList&&n.textList.length>0&&(a.text_list=n.textList.map(e=>({end_time:e.end_time,start_time:e.start_time,text:e.text})));let r=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=add_subtitles`,a),o=r.headers["x-api-status-code"]||"0",u=r.headers["x-api-message"]||"";if("0"!==o)throw new eT(`Add subtitles failed, status code: ${o}, error: ${u}`,parseInt(o)||500);if(!r.data.url)throw new eT("Add subtitles failed: returned URL is empty",500);return r.data}async concatVideos(e,i){if(!e||0===e.length)throw new eT("videos list cannot be empty",400);for(let i=0;i<e.length;i++)e[i]=await url_utils_validateUrl(e[i]);let n={videos:e,url_expire:this.validateUrlExpire(i?.urlExpire)};i?.transitions&&i.transitions.length>0&&(n.transitions=i.transitions);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=concat_videos`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eT(`Concat videos failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eT("Concat videos failed: returned URL is empty",500);return t.data}async compileVideoAudio(e,i,n){e=await url_utils_validateUrl(e),i=await url_utils_validateUrl(i);let t=this.validateUrlExpire(n?.urlExpire),a={video:e,audio:i,url_expire:t};n?.isVideoAudioSync!==void 0&&(a.is_video_audio_sync=n.isVideoAudioSync),n?.outputSync&&(a.output_sync={sync_method:n.outputSync.sync_method??eX.DEFAULT_SYNC_METHOD,sync_mode:n.outputSync.sync_mode??eX.DEFAULT_SYNC_MODE}),n?.isAudioReserve!==void 0&&(a.is_audio_reserve=n.isAudioReserve);let r=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=compile_video_audio`,a),o=r.headers["x-api-status-code"]||"0",u=r.headers["x-api-message"]||"";if("0"!==o)throw new eT(`Compile video audio failed, status code: ${o}, error: ${u}`,parseInt(o)||500);if(!r.data.url)throw new eT("Compile video audio failed: returned URL is empty",500);return r.data}async audioToSubtitle(e,i){e=await url_utils_validateUrl(e);let n=this.validateUrlExpire(i?.urlExpire),t={source:e,url_expire:n};i?.subtitleType&&(t.subtitle_type=i.subtitleType);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_to_subtitle`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eT(`Audio to subtitle failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eT("Audio to subtitle failed: returned URL is empty",500);return a.data}async extractAudio(e,i){e=await url_utils_validateUrl(e);let n=this.validateUrlExpire(i?.urlExpire,eX.MIN_AUDIO_URL_EXPIRE),t={video:e,url_expire:n};i?.format&&(t.format=i.format);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_extract`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eT(`Extract audio failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eT("Extract audio failed: returned URL is empty",500);return a.data}async videoTrim(e,i){e=await url_utils_validateUrl(e);let n=this.validateUrlExpire(i?.urlExpire);if(i?.startTime!==void 0&&i.startTime<0)throw new eT("start_time must be greater than or equal to 0",400);if(i?.endTime!==void 0&&i.endTime<0)throw new eT("end_time must be greater than or equal to 0",400);let t={video:e,url_expire:n};i?.startTime!==void 0&&(t.start_time=i.startTime),i?.endTime!==void 0&&(t.end_time=i.endTime);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=video_trim`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eT(`Video trim failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eT("Video trim failed: returned URL is empty",500);return a.data}}let eQ={MODEL:"doubao-seed-1-8-251228",THINKING:"disabled",CACHING:"disabled",TEMPERATURE:1,STREAMING:!0};class eU{config;customHeaders;constructor(e,i){this.config=e||new eC,this.customHeaders=i}createLLM(e,i,n){let t={};t.thinking={type:e.thinking??eQ.THINKING},e.caching&&"disabled"!==e.caching&&(t.caching={type:e.caching});let a={Authorization:`Bearer ${this.config.apiKey}`,"X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...this.customHeaders,...n};return i&&(a["X-Previous-Response-Id"]=i),new v({model:e.model||eQ.MODEL,apiKey:this.config.apiKey,configuration:{baseURL:this.config.modelBaseUrl,defaultHeaders:a},streaming:void 0!==e.streaming?e.streaming:eQ.STREAMING,temperature:void 0!==e.temperature?e.temperature:eQ.TEMPERATURE,modelKwargs:Object.keys(t).length>0?t:void 0})}convertMessages(e){return e.map(e=>{let i=this.convertContent(e.content);switch(e.role){case"system":return new P(i);case"user":return new N(i);case"assistant":return new A(i);default:throw Error(`Unknown message role: ${e.role}`)}})}convertContent(e){return"string"==typeof e?e:e.map(e=>{if("text"===e.type)return{type:"text",text:e.text};if("image_url"===e.type){let i={url:e.image_url.url};return e.image_url.detail&&(i.detail=e.image_url.detail),{type:"image_url",image_url:i}}if("video_url"===e.type){let i={url:e.video_url.url};return void 0!==e.video_url.fps&&(i.fps=e.video_url.fps),{type:"video_url",video_url:i}}return e})}async *stream(e,i={},n,t){if(!e.some(e=>"user"===e.role))throw Error('messages must contain at least one message with role: "user", otherwise the API request will fail validation.');for(let i of e)if(Array.isArray(i.content))for(let e of i.content)"image_url"===e.type&&e.image_url?e.image_url.url=await url_utils_validateUrl(e.image_url.url):"video_url"===e.type&&e.video_url&&(e.video_url.url=await url_utils_validateUrl(e.video_url.url));let a=this.createLLM(i,n,t),r=this.convertMessages(e);for await(let e of(await a.stream(r)))yield e}async invoke(e,i={},n,t){let a="";for await(let r of this.stream(e,i,n,t))r.content&&(a+=r.content.toString());return{content:a}}}var eG=((I={})[I.TEXT=0]="TEXT",I[I.URL=1]="URL",I[I.URI=2]="URI",I);class e$ extends eE{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async search(e,i,n=5,t=0,a){let r={query:e,top_k:n,min_score:t};i&&(r.dataset=i);let o=`${this.baseUrl}/v1/knowledge_base/recall`,u={...a};this.config.apiKey&&(u["x-coze-token"]=`Bearer ${this.config.apiKey}`);let s=await this.request("POST",o,r,{headers:u});return{chunks:(s.data||[]).map(e=>({content:e.slice||"",score:e.score||0,chunk_id:e.chunk_id,doc_id:e.doc_id})),code:s.code||0,msg:s.msg||""}}async addDocuments(e,i,n,t){let a={dataset:i,data:e};n&&(a.chunk_config=Object.fromEntries(Object.entries(n).filter(([e,i])=>void 0!==i)));let r=`${this.baseUrl}/v1/knowledge_base/batch_import`,o={...t};this.config.apiKey&&(o["x-coze-token"]=`Bearer ${this.config.apiKey}`);let u=await this.request("POST",r,a,{headers:o}),s=u.msg||"";return 0===u.code&&(s="成功!文档正在异步导入中,请稍候。您可以查看数据库中的 'knowledge' schema 来验证导入状态。"),{doc_ids:u.doc_ids,code:u.code||0,msg:s}}}let eK=Symbol.for("drizzle:entityKind");function entity_is(e,i){if(!e||"object"!=typeof e)return!1;if(e instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,eK))throw Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(eK in n&&n[eK]===i[eK])return!0;n=Object.getPrototypeOf(n)}return!1}Symbol.for("drizzle:hasOwnEntityKind");class ez{static [eK]="ConsoleLogWriter";write(e){console.log(e)}}class eW{static [eK]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new ez}logQuery(e,i){let n=i.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),t=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${e}${t}`)}}class ej{static [eK]="NoopLogger";logQuery(){}}class eV{constructor(e,i){this.table=e,this.config=i,this.name=i.name,this.keyAsName=i.keyAsName,this.notNull=i.notNull,this.default=i.default,this.defaultFn=i.defaultFn,this.onUpdateFn=i.onUpdateFn,this.hasDefault=i.hasDefault,this.primary=i.primaryKey,this.isUnique=i.isUnique,this.uniqueName=i.uniqueName,this.uniqueType=i.uniqueType,this.dataType=i.dataType,this.columnType=i.columnType,this.generated=i.generated,this.generatedIdentity=i.generatedIdentity}static [eK]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}class e0{static [eK]="ColumnBuilder";config;constructor(e,i,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:i,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}let e1=Symbol.for("drizzle:Name");class e3{static [eK]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,i){this.reference=()=>{let{name:i,columns:n,foreignColumns:t}=e();return{name:i,columns:n,foreignTable:t[0].table,foreignColumns:t}},i&&(this._onUpdate=i.onUpdate,this._onDelete=i.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new e2(e,this)}}class e2{constructor(e,i){this.table=e,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static [eK]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:i,foreignColumns:n}=this.reference(),t=i.map(e=>e.name),a=n.map(e=>e.name),r=[this.table[e1],...t,n[0].table[e1],...a];return e??`${r.join("_")}_fk`}}function iife(e,...i){return e(...i)}function uniqueKeyName(e,i){return`${e[e1]}_${i.join("_")}_unique`}class e4{constructor(e,i){this.name=i,this.columns=e}static [eK]=null;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new e6(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class e8{static [eK]=null;name;constructor(e){this.name=e}on(...e){return new e4(e,this.name)}}class e6{constructor(e,i,n,t){this.table=e,this.columns=i,this.name=t??uniqueKeyName(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static [eK]=null;columns;name;nullsNotDistinct=!1;getName(){return this.name}}function parsePgArrayValue(e,i,n){for(let t=i;t<e.length;t++){let a=e[t];if("\\"===a){t++;continue}if('"'===a)return[e.slice(i,t).replace(/\\/g,""),t+1];if(!n&&(","===a||"}"===a))return[e.slice(i,t).replace(/\\/g,""),t]}return[e.slice(i).replace(/\\/g,""),e.length]}function parsePgNestedArray(e,i=0){let n=[],t=i,a=!1;for(;t<e.length;){let r=e[t];if(","===r){(a||t===i)&&n.push(""),a=!0,t++;continue}if(a=!1,"\\"===r){t+=2;continue}if('"'===r){let[i,a]=parsePgArrayValue(e,t+1,!0);n.push(i),t=a;continue}if("}"===r)return[n,t+1];if("{"===r){let[i,a]=parsePgNestedArray(e,t+1);n.push(i),t=a;continue}let[o,u]=parsePgArrayValue(e,t,!1);n.push(o),t=u}return[n,t]}function parsePgArray(e){let[i]=parsePgNestedArray(e,1);return i}function makePgArray(e){return`{${e.map(e=>Array.isArray(e)?makePgArray(e):"string"==typeof e?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}class e5 extends e0{foreignKeyConfigs=[];static [eK]="PgColumnBuilder";array(e){return new it(this.config.name,this,e)}references(e,i={}){return this.foreignKeyConfigs.push({ref:e,actions:i}),this}unique(e,i){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=i?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,i){return this.foreignKeyConfigs.map(({ref:n,actions:t})=>iife((n,t)=>{let a=new e3(()=>({columns:[e],foreignColumns:[n()]}));return t.onUpdate&&a.onUpdate(t.onUpdate),t.onDelete&&a.onDelete(t.onDelete),a.build(i)},n,t))}buildExtraConfigColumn(e){return new e9(e,this.config)}}class e7 extends eV{constructor(e,i){i.uniqueName||(i.uniqueName=uniqueKeyName(e,[i.name])),super(e,i),this.table=e}static [eK]="PgColumn"}class e9 extends e7{static [eK]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}}class ie{static [eK]=null;constructor(e,i,n,t){this.name=e,this.keyAsName=i,this.type=n,this.indexConfig=t}name;keyAsName;type;indexConfig}class it extends e5{static [eK]="PgArrayBuilder";constructor(e,i,n){super(e,"array","PgArray"),this.config.baseBuilder=i,this.config.size=n}build(e){let i=this.config.baseBuilder.build(e);return new ia(e,this.config,i)}}class ia extends e7{constructor(e,i,n,t){super(e,i),this.baseColumn=n,this.range=t,this.size=i.size}size;static [eK]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=parsePgArray(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,i=!1){let n=e.map(e=>null===e?null:entity_is(this.baseColumn,ia)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return i?n:makePgArray(n)}}class ir extends e5{static [eK]="PgEnumObjectColumnBuilder";constructor(e,i){super(e,"string","PgEnumObjectColumn"),this.config.enum=i}build(e){return new io(e,this.config)}}class io extends e7{static [eK]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}let iu=Symbol.for("drizzle:isPgEnum");function isPgEnum(e){return!!e&&"function"==typeof e&&iu in e&&!0===e[iu]}class is extends e5{static [eK]="PgEnumColumnBuilder";constructor(e,i){super(e,"string","PgEnumColumn"),this.config.enum=i}build(e){return new il(e,this.config)}}class il extends e7{static [eK]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}class ih{static [eK]="Subquery";constructor(e,i,n,t=!1,a=[]){this._={brand:"Subquery",sql:e,selectedFields:i,alias:n,isWith:t,usedTables:a}}}class ig extends ih{static [eK]="WithSubquery"}let ic=(n,t)=>e?(i||(i=e.trace.getTracer("drizzle-orm","0.45.1")),iife((e,i)=>i.startActiveSpan(n,i=>{try{return t(i)}catch(n){throw i.setStatus({code:e.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{i.end()}}),e,i)):t(),id=Symbol.for("drizzle:ViewBaseConfig"),ip=Symbol.for("drizzle:Schema"),im=Symbol.for("drizzle:Columns"),iy=Symbol.for("drizzle:ExtraConfigColumns"),iS=Symbol.for("drizzle:OriginalName"),ib=Symbol.for("drizzle:BaseName"),iC=Symbol.for("drizzle:IsAlias"),iw=Symbol.for("drizzle:ExtraConfigBuilder"),iT=Symbol.for("drizzle:IsDrizzleTable");class ix{static [eK]="Table";static Symbol={Name:e1,Schema:ip,OriginalName:iS,Columns:im,ExtraConfigColumns:iy,BaseName:ib,IsAlias:iC,ExtraConfigBuilder:iw};[e1];[iS];[ip];[im];[iy];[ib];[iC]=!1;[iT]=!0;[iw]=void 0;constructor(e,i,n){this[e1]=this[iS]=e,this[ip]=i,this[ib]=n}}function getTableUniqueName(e){return`${e[ip]??"public"}.${e[e1]}`}class iL{static [eK]=null}function isSQLWrapper(e){return null!=e&&"function"==typeof e.getSQL}function mergeQueries(e){let i={sql:"",params:[]};for(let n of e)i.sql+=n.sql,i.params.push(...n.params),n.typings?.length&&(i.typings||(i.typings=[]),i.typings.push(...n.typings));return i}class iE{static [eK]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new i_([this])}}class i_{constructor(e){for(let i of(this.queryChunks=e,e))if(entity_is(i,ix)){let e=i[ix.Symbol.Schema];this.usedTables.push(void 0===e?i[ix.Symbol.Name]:e+"."+i[ix.Symbol.Name])}}static [eK]="SQL";decoder=iD;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return ic("drizzle.buildSQL",i=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return i?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let n=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:t,escapeName:a,escapeParam:r,prepareTyping:o,inlineParams:u,paramStartIndex:s}=n;return mergeQueries(e.map(e=>{if(entity_is(e,iE))return{sql:e.value.join(""),params:[]};if(entity_is(e,iY))return{sql:a(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let i=[new iE("(")];for(let[n,t]of e.entries())i.push(t),n<e.length-1&&i.push(new iE(", "));return i.push(new iE(")")),this.buildQueryFromSourceParams(i,n)}if(entity_is(e,i_))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:u||e.shouldInlineParams});if(entity_is(e,ix)){let i=e[ix.Symbol.Schema],n=e[ix.Symbol.Name];return{sql:void 0===i||e[iC]?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,eV)){let n=t.getColumnCasing(e);if("indexes"===i.invokeSource)return{sql:a(n),params:[]};let r=e.table[ix.Symbol.Schema];return{sql:e.table[iC]||void 0===r?a(e.table[ix.Symbol.Name])+"."+a(n):a(r)+"."+a(e.table[ix.Symbol.Name])+"."+a(n),params:[]}}if(entity_is(e,iM)){let i=e[id].schema,n=e[id].name;return{sql:void 0===i||e[id].isAlias?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,iA)){if(entity_is(e.value,iZ))return{sql:r(s.value++,e),params:[e],typings:["none"]};let i=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(entity_is(i,i_))return this.buildQueryFromSourceParams([i],n);if(u)return{sql:this.mapInlineParam(i,n),params:[]};let t=["none"];return o&&(t=[o(e.encoder)]),{sql:r(s.value++,i),params:[i],typings:t}}return entity_is(e,iZ)?{sql:r(s.value++,e),params:[e],typings:["none"]}:entity_is(e,i_.Aliased)&&void 0!==e.fieldAlias?{sql:a(e.fieldAlias),params:[]}:entity_is(e,ih)?e._.isWith?{sql:a(e._.alias),params:[]}:this.buildQueryFromSourceParams([new iE("("),e._.sql,new iE(") "),new iY(e._.alias)],n):isPgEnum(e)?e.schema?{sql:a(e.schema)+"."+a(e.enumName),params:[]}:{sql:a(e.enumName),params:[]}:isSQLWrapper(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new iE("("),e.getSQL(),new iE(")")],n):u?{sql:this.mapInlineParam(e,n),params:[]}:{sql:r(s.value++,e),params:[e],typings:["none"]}}))}mapInlineParam(e,{escapeString:i}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return i(e);if("object"==typeof e){let n=e.toString();return"[object Object]"===n?i(JSON.stringify(e)):i(n)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new i_.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class iY{constructor(e){this.value=e}static [eK]="Name";brand;getSQL(){return new i_([this])}}function isDriverValueEncoder(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue}let iD={mapFromDriverValue:e=>e},iv={mapToDriverValue:e=>e};({...iD,...iv});class iA{constructor(e,i=iv){this.value=e,this.encoder=i}static [eK]="Param";brand;getSQL(){return new i_([this])}}function sql_sql(e,...i){let n=[];for(let[t,a]of((i.length>0||e.length>0&&""!==e[0])&&n.push(new iE(e[0])),i.entries()))n.push(a,new iE(e[t+1]));return new i_(n)}(O=sql_sql||(sql_sql={})).empty=function(){return new i_([])},O.fromList=function(e){return new i_(e)},O.raw=function(e){return new i_([new iE(e)])},O.join=function(e,i){let n=[];for(let[t,a]of e.entries())t>0&&void 0!==i&&n.push(i),n.push(a);return new i_(n)},O.identifier=function(e){return new iY(e)},O.placeholder=function(e){return new iZ(e)},O.param=function(e,i){return new iA(e,i)};var iN=i_||(i_={});class iP{constructor(e,i){this.sql=e,this.fieldAlias=i}static [eK]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new iP(this.sql,this.fieldAlias)}}iN.Aliased=iP;class iZ{constructor(e){this.name=e}static [eK]="Placeholder";getSQL(){return new i_([this])}}function fillPlaceholders(e,i){return e.map(e=>{if(entity_is(e,iZ)){if(!(e.name in i))throw Error(`No value for placeholder "${e.name}" was provided`);return i[e.name]}if(entity_is(e,iA)&&entity_is(e.value,iZ)){if(!(e.value.name in i))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(i[e.value.name])}return e})}let iR=Symbol.for("drizzle:IsDrizzleView");class iM{static [eK]="View";[id];[iR]=!0;constructor({name:e,schema:i,selectedFields:n,query:t}){this[id]={name:e,originalName:e,schema:i,selectedFields:n,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new i_([this])}}eV.prototype.getSQL=function(){return new i_([this])},ix.prototype.getSQL=function(){return new i_([this])},ih.prototype.getSQL=function(){return new i_([this])};class iJ{constructor(e){this.table=e}static [eK]="ColumnAliasProxyHandler";get(e,i){return"table"===i?this.table:e[i]}}class ik{constructor(e,i){this.alias=e,this.replaceOriginalName=i}static [eK]="TableAliasProxyHandler";get(e,i){if(i===ix.Symbol.IsAlias)return!0;if(i===ix.Symbol.Name||this.replaceOriginalName&&i===ix.Symbol.OriginalName)return this.alias;if(i===id)return{...e[id],name:this.alias,isAlias:!0};if(i===ix.Symbol.Columns){let i=e[ix.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map(t=>{n[t]=new Proxy(i[t],new iJ(new Proxy(e,this)))}),n}let n=e[i];return entity_is(n,eV)?new Proxy(n,new iJ(new Proxy(e,this))):n}}class iB{constructor(e){this.alias=e}static [eK]=null;get(e,i){return"sourceTable"===i?aliasedTable(e.sourceTable,this.alias):e[i]}}function aliasedTable(e,i){return new Proxy(e,new ik(i,!1))}function aliasedTableColumn(e,i){return new Proxy(e,new iJ(new Proxy(e.table,new ik(i,!1))))}function mapColumnsInAliasedSQLToAlias(e,i){return new i_.Aliased(mapColumnsInSQLToAlias(e.sql,i),e.fieldAlias)}function mapColumnsInSQLToAlias(e,i){return sql_sql.join(e.queryChunks.map(e=>entity_is(e,eV)?aliasedTableColumn(e,i):entity_is(e,i_)?mapColumnsInSQLToAlias(e,i):entity_is(e,i_.Aliased)?mapColumnsInAliasedSQLToAlias(e,i):e))}function toSnakeCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function toCamelCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,i,n)=>e+(0===n?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`),"")}function noopCase(e){return e}class iH{static [eK]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?toSnakeCase:"camelCase"===e?toCamelCase:noopCase}getColumnCasing(e){if(!e.keyAsName)return e.name;let i=e.table[ix.Symbol.Schema]??"public",n=e.table[ix.Symbol.OriginalName],t=`${i}.${n}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let i=e[ix.Symbol.Schema]??"public",n=e[ix.Symbol.OriginalName],t=`${i}.${n}`;if(!this.cachedTables[t]){for(let i of Object.values(e[ix.Symbol.Columns])){let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class iF extends Error{static [eK]="DrizzleError";constructor({message:e,cause:i}){super(e),this.name="DrizzleError",this.cause=i}}class iX extends Error{constructor(e,i,n){super(`Failed query: ${e}
|
|
2
2
|
params: ${i}`),this.query=e,this.params=i,this.cause=n,Error.captureStackTrace(this,iX),n&&(this.cause=n)}}class iI extends iF{static [eK]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class iO extends e5{static [eK]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new iQ(e,this.config)}}class iQ extends e7{static [eK]="PgJsonb";constructor(e,i){super(e,i)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}class iU extends e5{static [eK]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new iG(e,this.config)}}class iG extends e7{static [eK]="PgJson";constructor(e,i){super(e,i)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}class iq extends e5{static [eK]="PgNumericBuilder";constructor(e,i,n){super(e,"string","PgNumeric"),this.config.precision=i,this.config.scale=n}build(e){return new i$(e,this.config)}}class i$ extends e7{static [eK]="PgNumeric";precision;scale;constructor(e,i){super(e,i),this.precision=i.precision,this.scale=i.scale}mapFromDriverValue(e){return"string"==typeof e?e:String(e)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class iK extends e5{static [eK]="PgNumericNumberBuilder";constructor(e,i,n){super(e,"number","PgNumericNumber"),this.config.precision=i,this.config.scale=n}build(e){return new iz(e,this.config)}}class iz extends e7{static [eK]="PgNumericNumber";precision;scale;constructor(e,i){super(e,i),this.precision=i.precision,this.scale=i.scale}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class iW extends e5{static [eK]="PgNumericBigIntBuilder";constructor(e,i,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=i,this.config.scale=n}build(e){return new ij(e,this.config)}}class ij extends e7{static [eK]="PgNumericBigInt";precision;scale;constructor(e,i){super(e,i),this.precision=i.precision,this.scale=i.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class iV extends e5{static [eK]="PgDateColumnBaseBuilder";defaultNow(){return this.default(sql_sql`now()`)}}class i0 extends iV{constructor(e,i,n){super(e,"string","PgTime"),this.withTimezone=i,this.precision=n,this.config.withTimezone=i,this.config.precision=n}static [eK]="PgTimeBuilder";build(e){return new i1(e,this.config)}}class i1 extends e7{static [eK]="PgTime";withTimezone;precision;constructor(e,i){super(e,i),this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`time${e}${this.withTimezone?" with time zone":""}`}}class i3 extends iV{static [eK]="PgTimestampBuilder";constructor(e,i,n){super(e,"date","PgTimestamp"),this.config.withTimezone=i,this.config.precision=n}build(e){return new i2(e,this.config)}}class i2 extends e7{static [eK]="PgTimestamp";withTimezone;precision;constructor(e,i){super(e,i),this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){let e=void 0===this.precision?"":` (${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){return"string"==typeof e?new Date(this.withTimezone?e:e+"+0000"):e}mapToDriverValue=e=>e.toISOString()}class i4 extends iV{static [eK]="PgTimestampStringBuilder";constructor(e,i,n){super(e,"string","PgTimestampString"),this.config.withTimezone=i,this.config.precision=n}build(e){return new i8(e,this.config)}}class i8 extends e7{static [eK]="PgTimestampString";withTimezone;precision;constructor(e,i){super(e,i),this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){if("string"==typeof e)return e;let i=e.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let n=e.getTimezoneOffset();return`${i}${n<=0?"+":"-"}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return i}}class i6 extends iV{static [eK]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new i5(e,this.config)}}class i5 extends e7{static [eK]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?new Date(e):e}mapToDriverValue(e){return e.toISOString()}}class i7 extends iV{static [eK]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new i9(e,this.config)}}class i9 extends e7{static [eK]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?e:e.toISOString().slice(0,-14)}}class ni extends e5{static [eK]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(sql_sql`gen_random_uuid()`)}build(e){return new nn(e,this.config)}}class nn extends e7{static [eK]="PgUUID";getSQLType(){return"uuid"}}let nt=Symbol.for("drizzle:PgInlineForeignKeys"),na=Symbol.for("drizzle:EnableRLS");class nr extends ix{static [eK]="PgTable";static Symbol=Object.assign({},ix.Symbol,{InlineForeignKeys:nt,EnableRLS:na});[nt]=[];[na]=!1;[ix.Symbol.ExtraConfigBuilder]=void 0;[ix.Symbol.ExtraConfigColumns]={}}class no{static [eK]="PgPrimaryKeyBuilder";columns;name;constructor(e,i){this.columns=e,this.name=i}build(e){return new nu(e,this.columns,this.name)}}class nu{constructor(e,i,n){this.table=e,this.columns=i,this.name=n}static [eK]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[nr.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}function bindIfParam(e,i){return!isDriverValueEncoder(i)||isSQLWrapper(e)||entity_is(e,iA)||entity_is(e,iZ)||entity_is(e,eV)||entity_is(e,ix)||entity_is(e,iM)?e:new iA(e,i)}let eq=(e,i)=>sql_sql`${e} = ${bindIfParam(i,e)}`,ne=(e,i)=>sql_sql`${e} <> ${bindIfParam(i,e)}`;function and(...e){let i=e.filter(e=>void 0!==e);if(0!==i.length)return new i_(1===i.length?i:[new iE("("),sql_sql.join(i,new iE(" and ")),new iE(")")])}function or(...e){let i=e.filter(e=>void 0!==e);if(0!==i.length)return new i_(1===i.length?i:[new iE("("),sql_sql.join(i,new iE(" or ")),new iE(")")])}function not(e){return sql_sql`not ${e}`}let gt=(e,i)=>sql_sql`${e} > ${bindIfParam(i,e)}`,gte=(e,i)=>sql_sql`${e} >= ${bindIfParam(i,e)}`,lt=(e,i)=>sql_sql`${e} < ${bindIfParam(i,e)}`,lte=(e,i)=>sql_sql`${e} <= ${bindIfParam(i,e)}`;function inArray(e,i){return Array.isArray(i)?0===i.length?sql_sql`false`:sql_sql`${e} in ${i.map(i=>bindIfParam(i,e))}`:sql_sql`${e} in ${bindIfParam(i,e)}`}function notInArray(e,i){return Array.isArray(i)?0===i.length?sql_sql`true`:sql_sql`${e} not in ${i.map(i=>bindIfParam(i,e))}`:sql_sql`${e} not in ${bindIfParam(i,e)}`}function isNull(e){return sql_sql`${e} is null`}function isNotNull(e){return sql_sql`${e} is not null`}function exists(e){return sql_sql`exists ${e}`}function notExists(e){return sql_sql`not exists ${e}`}function between(e,i,n){return sql_sql`${e} between ${bindIfParam(i,e)} and ${bindIfParam(n,e)}`}function notBetween(e,i,n){return sql_sql`${e} not between ${bindIfParam(i,e)} and ${bindIfParam(n,e)}`}function like(e,i){return sql_sql`${e} like ${i}`}function notLike(e,i){return sql_sql`${e} not like ${i}`}function ilike(e,i){return sql_sql`${e} ilike ${i}`}function notIlike(e,i){return sql_sql`${e} not ilike ${i}`}function asc(e){return sql_sql`${e} asc`}function select_desc(e){return sql_sql`${e} desc`}class ns{constructor(e,i,n){this.sourceTable=e,this.referencedTable=i,this.relationName=n,this.referencedTableName=i[ix.Symbol.Name]}static [eK]="Relation";referencedTableName;fieldName}class nl{constructor(e,i){this.table=e,this.config=i}static [eK]="Relations"}class nh extends ns{constructor(e,i,n,t){super(e,i,n?.relationName),this.config=n,this.isNullable=t}static [eK]="One";withFieldName(e){let i=new nh(this.sourceTable,this.referencedTable,this.config,this.isNullable);return i.fieldName=e,i}}class ng extends ns{constructor(e,i,n){super(e,i,n?.relationName),this.config=n}static [eK]="Many";withFieldName(e){let i=new ng(this.sourceTable,this.referencedTable,this.config);return i.fieldName=e,i}}function getOperators(){return{and:and,between:between,eq:eq,exists:exists,gt:gt,gte:gte,ilike:ilike,inArray:inArray,isNull:isNull,isNotNull:isNotNull,like:like,lt:lt,lte:lte,ne:ne,not:not,notBetween:notBetween,notExists:notExists,notLike:notLike,notIlike:notIlike,notInArray:notInArray,or:or,sql:sql_sql}}function getOrderByOperators(){return{sql:sql_sql,asc:asc,desc:select_desc}}function extractTablesRelationalConfig(e,i){1===Object.keys(e).length&&"default"in e&&!entity_is(e.default,ix)&&(e=e.default);let n={},t={},a={};for(let[r,o]of Object.entries(e))if(entity_is(o,ix)){let e=getTableUniqueName(o),i=t[e];for(let t of(n[e]=r,a[r]={tsName:r,dbName:o[ix.Symbol.Name],schema:o[ix.Symbol.Schema],columns:o[ix.Symbol.Columns],relations:i?.relations??{},primaryKey:i?.primaryKey??[]},Object.values(o[ix.Symbol.Columns])))t.primary&&a[r].primaryKey.push(t);let u=o[ix.Symbol.ExtraConfigBuilder]?.(o[ix.Symbol.ExtraConfigColumns]);if(u)for(let e of Object.values(u))entity_is(e,no)&&a[r].primaryKey.push(...e.columns)}else if(entity_is(o,nl)){let e,r=getTableUniqueName(o.table),u=n[r];for(let[n,s]of Object.entries(o.config(i(o.table))))if(u){let i=a[u];i.relations[n]=s,e&&i.primaryKey.push(...e)}else r in t||(t[r]={relations:{},primaryKey:e}),t[r].relations[n]=s}return{tables:a,tableNamesMap:n}}function createOne(e){return function(i,n){return new nh(e,i,n,n?.fields.reduce((e,i)=>e&&i.notNull,!0)??!1)}}function createMany(e){return function(i,n){return new ng(e,i,n)}}function normalizeRelation(e,i,n){if(entity_is(n,nh)&&n.config)return{fields:n.config.fields,references:n.config.references};let t=i[getTableUniqueName(n.referencedTable)];if(!t)throw Error(`Table "${n.referencedTable[ix.Symbol.Name]}" not found in schema`);let a=e[t];if(!a)throw Error(`Table "${t}" not found in schema`);let r=n.sourceTable,o=i[getTableUniqueName(r)];if(!o)throw Error(`Table "${r[ix.Symbol.Name]}" not found in schema`);let u=[];for(let e of Object.values(a.relations))(n.relationName&&n!==e&&e.relationName===n.relationName||!n.relationName&&e.referencedTable===n.sourceTable)&&u.push(e);if(u.length>1)throw n.relationName?Error(`There are multiple relations with name "${n.relationName}" in table "${t}"`):Error(`There are multiple relations between "${t}" and "${n.sourceTable[ix.Symbol.Name]}". Please specify relation name`);if(u[0]&&entity_is(u[0],nh)&&u[0].config)return{fields:u[0].config.references,references:u[0].config.fields};throw Error(`There is not enough information to infer relation "${o}.${n.fieldName}"`)}function createTableRelationsHelpers(e){return{one:createOne(e),many:createMany(e)}}function mapRelationalRow(e,i,n,t,a=e=>e){let r={};for(let[o,u]of t.entries())if(u.isJson){let t=i.relations[u.tsKey],s=n[o],l="string"==typeof s?JSON.parse(s):s;r[u.tsKey]=entity_is(t,nh)?l&&mapRelationalRow(e,e[u.relationTableTsKey],l,u.selection,a):l.map(i=>mapRelationalRow(e,e[u.relationTableTsKey],i,u.selection,a))}else{let e,i=a(n[o]),t=u.field;e=entity_is(t,eV)?t:entity_is(t,i_)?t.decoder:t.sql.decoder,r[u.tsKey]=null===i?null:e.mapFromDriverValue(i)}return r}function mapResultRow(e,i,n){let t={},a=e.reduce((e,{path:a,field:r},o)=>{let u;u=entity_is(r,eV)?r:entity_is(r,i_)?r.decoder:entity_is(r,ih)?r._.sql.decoder:r.sql.decoder;let s=e;for(let[e,l]of a.entries())if(e<a.length-1)l in s||(s[l]={}),s=s[l];else{let e=i[o],h=s[l]=null===e?null:u.mapFromDriverValue(e);if(n&&entity_is(r,eV)&&2===a.length){let e=a[0];e in t?"string"==typeof t[e]&&t[e]!==r.table[e1]&&(t[e]=!1):t[e]=null===h&&r.table[e1]}}return e},{});if(n&&Object.keys(t).length>0)for(let[e,i]of Object.entries(t))"string"!=typeof i||n[i]||(a[e]=null);return a}function orderSelectedFields(e,i){return Object.entries(e).reduce((e,[n,t])=>{if("string"!=typeof n)return e;let a=i?[...i,n]:[n];return entity_is(t,eV)||entity_is(t,i_)||entity_is(t,i_.Aliased)||entity_is(t,ih)?e.push({path:a,field:t}):entity_is(t,ix)?e.push(...orderSelectedFields(t[ix.Symbol.Columns],a)):e.push(...orderSelectedFields(t,a)),e},[])}function haveSameKeys(e,i){let n=Object.keys(e),t=Object.keys(i);if(n.length!==t.length)return!1;for(let[e,i]of n.entries())if(i!==t[e])return!1;return!0}function mapUpdateSet(e,i){let n=Object.entries(i).filter(([,e])=>void 0!==e).map(([i,n])=>entity_is(n,i_)||entity_is(n,eV)?[i,n]:[i,new iA(n,e[ix.Symbol.Columns][i])]);if(0===n.length)throw Error("No values to set");return Object.fromEntries(n)}function applyMixins(e,i){for(let n of i)for(let i of Object.getOwnPropertyNames(n.prototype))"constructor"!==i&&Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(n.prototype,i)||Object.create(null))}function getTableColumns(e){return e[ix.Symbol.Columns]}function getTableLikeName(e){return entity_is(e,ih)?e._.alias:entity_is(e,iM)?e[id].name:entity_is(e,i_)?void 0:e[ix.Symbol.IsAlias]?e[ix.Symbol.Name]:e[ix.Symbol.BaseName]}function isConfig(e){if("object"!=typeof e||null===e||"Object"!==e.constructor.name)return!1;if("logger"in e){let i=typeof e.logger;return"boolean"===i||"object"===i&&"function"==typeof e.logger.logQuery||"undefined"===i}if("schema"in e){let i=typeof e.schema;return"object"===i||"undefined"===i}if("casing"in e){let i=typeof e.casing;return"string"===i||"undefined"===i}if("mode"in e)return"default"===e.mode&&"planetscale"===e.mode&&void 0===e.mode;if("connection"in e){let i=typeof e.connection;return"string"===i||"object"===i||"undefined"===i}if("client"in e){let i=typeof e.client;return"object"===i||"function"===i||"undefined"===i}return 0===Object.keys(e).length}"u"<typeof TextDecoder||new TextDecoder;class nc extends iM{static [eK]="PgViewBase"}class nd{static [eK]="PgDialect";casing;constructor(e){this.casing=new iH(e?.casing)}async migrate(e,i,n){let t="string"==typeof n?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",a="string"==typeof n?"drizzle":n.migrationsSchema??"drizzle",r=sql_sql`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS ${sql_sql.identifier(a)}.${sql_sql.identifier(t)} (
|
|
4
4
|
id SERIAL PRIMARY KEY,
|