coze-coding-dev-sdk 0.7.13 → 0.7.14

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/index.js CHANGED
@@ -27,7 +27,7 @@ ${t.join(";")}
27
27
  ${n}`}async createStringToSign(e,i,n,t){let a=new this.sha256;a.update((0,u.F)(n));let s=await a.digest();return`${t}
28
28
  ${e}
29
29
  ${i}
30
- ${(0,o.n)(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let i=[];for(let n of e.split("/"))n?.length!==0&&"."!==n&&(".."===n?i.pop():i.push(n));let n=`${e?.startsWith("/")?"/":""}${i.join("/")}${i.length>0&&e?.endsWith("/")?"/":""}`;return(0,R.o)(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if("object"!=typeof e||"string"!=typeof e.accessKeyId||"string"!=typeof e.secretAccessKey)throw Error("Resolved credential object is not valid")}formatDate(e){var i;let n=("number"==typeof(i=e)?new Date(1e3*i):"string"==typeof i?new Date(Number(i)?1e3*Number(i):i):i).toISOString().replace(/\.\d{3}Z$/,"Z").replace(/[\-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}class H extends B{headerFormatter=new Z;constructor({applyChecksum:e,credentials:i,region:n,service:t,sha256:a,uriEscapePath:o=!0}){super({applyChecksum:e,credentials:i,region:n,service:t,sha256:a,uriEscapePath:o})}async presign(e,i={}){let{signingDate:n=new Date,expiresIn:t=3600,unsignableHeaders:a,unhoistableHeaders:o,signableHeaders:u,hoistableHeaders:h,signingRegion:d,signingService:c}=i,g=await this.credentialProvider();this.validateResolvedCredentials(g);let p=d??await this.regionProvider(),{longDate:m,shortDate:f}=this.formatDate(n);if(t>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=T(f,p,c??this.service),S=((e,i={})=>{let{headers:n,query:t={}}=k.K.clone(e);for(let e of Object.keys(n)){let a=e.toLowerCase();("x-amz-"===a.slice(0,6)&&!i.unhoistableHeaders?.has(a)||i.hoistableHeaders?.has(a))&&(t[e]=n[e],delete n[e])}return{...e,headers:n,query:t}})(P(e),{unhoistableHeaders:o,hoistableHeaders:h});g.sessionToken&&(S.query[l]=g.sessionToken),S.query["X-Amz-Algorithm"]=b,S.query["X-Amz-Credential"]=`${g.accessKeyId}/${y}`,S.query[s]=m,S.query["X-Amz-Expires"]=t.toString(10);let C=E(S,a,u);return S.query["X-Amz-SignedHeaders"]=this.getCanonicalHeaderList(C),S.query[r]=await this.getSignature(m,y,this.getSigningKey(g,p,f,c),this.createCanonicalRequest(S,C,await D(e,this.sha256))),S}async sign(e,i){return"string"==typeof e?this.signString(e,i):e.headers&&e.payload?this.signEvent(e,i):e.message?this.signMessage(e,i):this.signRequest(e,i)}async signEvent({headers:e,payload:i},{signingDate:n=new Date,priorSignature:t,signingRegion:a,signingService:u}){let s=a??await this.regionProvider(),{shortDate:r,longDate:l}=this.formatDate(n),h=T(r,s,u??this.service),d=await D({headers:{},body:i},this.sha256),c=new this.sha256;c.update(e);let g=["AWS4-HMAC-SHA256-PAYLOAD",l,h,t,(0,o.n)(await c.digest()),d].join("\n");return this.signString(g,{signingDate:n,signingRegion:s,signingService:u})}async signMessage(e,{signingDate:i=new Date,signingRegion:n,signingService:t}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:i,signingRegion:n,signingService:t,priorSignature:e.priorSignature}).then(i=>({message:e.message,signature:i}))}async signString(e,{signingDate:i=new Date,signingRegion:n,signingService:t}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=n??await this.regionProvider(),{shortDate:r}=this.formatDate(i),l=new this.sha256(await this.getSigningKey(a,s,r,t));return l.update((0,u.F)(e)),(0,o.n)(await l.digest())}async signRequest(e,{signingDate:i=new Date,signableHeaders:n,unsignableHeaders:t,signingRegion:a,signingService:o}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let s=a??await this.regionProvider(),r=P(e),{longDate:l,shortDate:c}=this.formatDate(i),g=T(c,s,o??this.service);r.headers[d]=l,u.sessionToken&&(r.headers[m]=u.sessionToken);let f=await D(r,this.sha256);!((e,i)=>{for(let n of(e=e.toLowerCase(),Object.keys(i)))if(e===n.toLowerCase())return!0;return!1})(p,r.headers)&&this.applyChecksum&&(r.headers[p]=f);let y=E(r,t,n),S=await this.getSignature(l,g,this.getSigningKey(u,s,c,o),this.createCanonicalRequest(r,y,f));return r.headers[h]=`${b} Credential=${u.accessKeyId}/${g}, SignedHeaders=${this.getCanonicalHeaderList(y)}, Signature=${S}`,r}async getSignature(e,i,n,t){let a=await this.createStringToSign(e,i,t,b),s=new this.sha256(await n);return s.update((0,u.F)(a)),(0,o.n)(await s.digest())}getSigningKey(e,i,n,t){return _(this.sha256,e,n,i,t||this.service)}}},"./node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"(e,i,n){"use strict";n.d(i,{N:()=>t});class t{trace(){}debug(){}info(){}warn(){}error(){}}},"./node_modules/@smithy/smithy-client/dist-es/client.js"(e,i,n){"use strict";n.d(i,{K:()=>a});var t=n("./node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js");class a{config;middlewareStack=(0,t.o)();initConfig;handlers;constructor(e){this.config=e;const{protocol:i,protocolSettings:n}=e;n&&"function"==typeof i&&(e.protocol=new i(n))}send(e,i,n){let t,a="function"!=typeof i?i:void 0,o="function"==typeof i?i:n;if(void 0===a&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);let i=this.handlers;i.has(e.constructor)?t=i.get(e.constructor):(t=e.resolveMiddleware(this.middlewareStack,this.config,a),i.set(e.constructor,t))}else delete this.handlers,t=e.resolveMiddleware(this.middlewareStack,this.config,a);if(!o)return t(e).then(e=>e.output);t(e).then(e=>o(null,e.output),e=>o(e)).catch(()=>{})}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}},"./node_modules/@smithy/smithy-client/dist-es/command.js"(e,i,n){"use strict";n.d(i,{u:()=>r});var t=n("./node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"),a=n("./node_modules/@smithy/types/dist-es/middleware.js"),o=n("./node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js");let u="***SensitiveInformation***";function s(e,i){if(null==i)return i;let n=o.l.of(e);if(n.getMergedTraits().sensitive)return u;if(n.isListSchema()){if(n.getValueSchema().getMergedTraits().sensitive)return u}else if(n.isMapSchema()){if(n.getKeySchema().getMergedTraits().sensitive||n.getValueSchema().getMergedTraits().sensitive)return u}else if(n.isStructSchema()&&"object"==typeof i){let e={};for(let[t,a]of n.structIterator())null!=i[t]&&(e[t]=s(a,i[t]));return e}return i}class r{middlewareStack=(0,t.o)();schema;static classBuilder(){return new l}resolveMiddlewareWithContext(e,i,n,{middlewareFn:t,clientName:o,commandName:u,inputFilterSensitiveLog:s,outputFilterSensitiveLog:r,smithyContext:l,additionalContext:h,CommandCtor:d}){for(let a of t.bind(this)(d,e,i,n))this.middlewareStack.use(a);let c=e.concat(this.middlewareStack),{logger:g}=i,p={logger:g,clientName:o,commandName:u,inputFilterSensitiveLog:s,outputFilterSensitiveLog:r,[a.V]:{commandInstance:this,...l},...h},{requestHandler:m}=i;return c.resolve(e=>m.handle(e.request,n||{}),p)}}class l{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,i,n={}){return this._smithyContext={service:e,operation:i,...n},this}c(e={}){return this._additionalContext=e,this}n(e,i){return this._clientName=e,this._commandName=i,this}f(e=e=>e,i=e=>e){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=i,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){let e,i=this;return e=class extends r{input;static getEndpointParameterInstructions(){return i._ep}constructor(...[e]){super(),this.input=e??{},i._init(this),this.schema=i._operationSchema}resolveMiddleware(n,t,a){let o=i._operationSchema,u=o?.[4]??o?.input,r=o?.[5]??o?.output;return this.resolveMiddlewareWithContext(n,t,a,{CommandCtor:e,middlewareFn:i._middlewareFn,clientName:i._clientName,commandName:i._commandName,inputFilterSensitiveLog:i._inputFilterSensitiveLog??(o?s.bind(null,u):e=>e),outputFilterSensitiveLog:i._outputFilterSensitiveLog??(o?s.bind(null,r):e=>e),smithyContext:i._smithyContext,additionalContext:i._additionalContext})}serialize=i._serializer;deserialize=i._deserializer}}}},"./node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"(e,i,n){"use strict";n.d(i,{l:()=>t});let t=e=>{switch(e){case"standard":case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}},"./node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"(e,i,n){"use strict";n.d(i,{I:()=>a});let t=!1,a=e=>{e&&!t&&16>parseInt(e.substring(1,e.indexOf(".")))&&(t=!0)}},"./node_modules/@smithy/smithy-client/dist-es/exceptions.js"(e,i,n){"use strict";n.d(i,{M:()=>a,T:()=>t});class t extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){return!!e&&(t.prototype.isPrototypeOf(e)||!!e.$fault&&!!e.$metadata&&("client"===e.$fault||"server"===e.$fault))}static[Symbol.hasInstance](e){return!!e&&(this===t?t.isInstance(e):!!t.isInstance(e)&&(e.name&&this.name?this.prototype.isPrototypeOf(e)||e.name===this.name:this.prototype.isPrototypeOf(e)))}}let a=(e,i={})=>{Object.entries(i).filter(([,e])=>void 0!==e).forEach(([i,n])=>{(void 0==e[i]||""===e[i])&&(e[i]=n)});let n=e.message||e.Message||"UnknownError";return e.message=n,delete e.Message,e}},"./node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"(e,i,n){"use strict";var t,a;n.d(i,{uv:()=>u,xA:()=>o}),(a=t||(t={})).MD5="md5",a.CRC32="crc32",a.CRC32C="crc32c",a.SHA1="sha1",a.SHA256="sha256";let o=e=>Object.assign((e=>{let i=[];for(let n in t){let a=t[n];void 0!==e[a]&&i.push({algorithmId:()=>a,checksumConstructor:()=>e[a]})}return{addChecksumAlgorithm(e){i.push(e)},checksumAlgorithms:()=>i}})(e),{setRetryStrategy(i){e.retryStrategy=i},retryStrategy:()=>e.retryStrategy}),u=e=>{let i,n;return Object.assign((i={},e.checksumAlgorithms().forEach(e=>{i[e.algorithmId()]=e.checksumConstructor()}),i),((n={}).retryStrategy=e.retryStrategy(),n))}},"./node_modules/@smithy/types/dist-es/middleware.js"(e,i,n){"use strict";n.d(i,{V:()=>t});let t="__smithy_context"},"./node_modules/@smithy/types/dist-es/profile.js"(e,i,n){"use strict";var t,a;n.d(i,{I:()=>t}),(a=t||(t={})).PROFILE="profile",a.SSO_SESSION="sso-session",a.SERVICES="services"},"./node_modules/@smithy/url-parser/dist-es/index.js"(e,i,n){"use strict";n.d(i,{D:()=>t});let t=e=>{let i;if("string"==typeof e)return t(new URL(e));let{hostname:n,pathname:a,port:o,protocol:u,search:s}=e;return s&&(i=function(e){let i={};if(e=e.replace(/^\?/,""))for(let n of e.split("&")){let[e,t=null]=n.split("=");e=decodeURIComponent(e),t&&(t=decodeURIComponent(t)),e in i?Array.isArray(i[e])?i[e].push(t):i[e]=[i[e],t]:i[e]=t}return i}(s)),{hostname:n,port:o?parseInt(o):void 0,protocol:u,path:a,query:i}}},"./node_modules/@smithy/util-base64/dist-es/fromBase64.js"(e,i,n){"use strict";n.d(i,{E:()=>o});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js");let a=/^[A-Za-z0-9+/]*={0,2}$/,o=e=>{if(3*e.length%4!=0)throw TypeError("Incorrect padding on base64 string.");if(!a.exec(e))throw TypeError("Invalid base64 string.");let i=(0,t.s)(e,"base64");return new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}},"./node_modules/@smithy/util-base64/dist-es/toBase64.js"(e,i,n){"use strict";n.d(i,{n:()=>o});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js"),a=n("./node_modules/@smithy/util-utf8/dist-es/fromUtf8.js");let o=e=>{let i;if("object"!=typeof(i="string"==typeof e?(0,a.a)(e):e)||"number"!=typeof i.byteOffset||"number"!=typeof i.byteLength)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return(0,t.Q)(i.buffer,i.byteOffset,i.byteLength).toString("base64")}},"./node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js"(e,i,n){"use strict";n.d(i,{n:()=>a});var t=n("node:fs");let a=e=>{if(!e)return 0;if("string"==typeof e)return Buffer.byteLength(e);if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;if("number"==typeof e.start&&"number"==typeof e.end)return e.end+1-e.start;if(e instanceof t.ReadStream){if(null!=e.path)return(0,t.lstatSync)(e.path).size;else if("number"==typeof e.fd)return(0,t.fstatSync)(e.fd).size}throw Error(`Body Length computation failed for ${e}`)}},"./node_modules/@smithy/util-buffer-from/dist-es/index.js"(e,i,n){"use strict";n.d(i,{Q:()=>o,s:()=>u});var t=n("./node_modules/@smithy/is-array-buffer/dist-es/index.js"),a=n("buffer");let o=(e,i=0,n=e.byteLength-i)=>{if(!(0,t.m)(e))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return a.Buffer.from(e,i,n)},u=(e,i)=>{if("string"!=typeof e)throw TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return i?a.Buffer.from(e,i):a.Buffer.from(e)}},"./node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"(e,i,n){"use strict";n.d(i,{Q:()=>t});let t=(e,i,n)=>{if(i in e){if("true"===e[i])return!0;if("false"===e[i])return!1;throw Error(`Cannot load ${n} "${i}". Expected "true" or "false", got ${e[i]}.`)}}},"./node_modules/@smithy/util-config-provider/dist-es/types.js"(e,i,n){"use strict";var t,a;n.d(i,{c:()=>t}),(a=t||(t={})).ENV="env",a.CONFIG="shared config entry"},"./node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js"(e,i,n){"use strict";n.d(i,{I:()=>h});var t=n("./node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"),a=n("./node_modules/@smithy/node-config-provider/dist-es/configLoader.js"),o=n("./node_modules/@smithy/property-provider/dist-es/memoize.js");let u="AWS_REGION",s="AWS_DEFAULT_REGION",r=["in-region","cross-region","mobile","standard","legacy"],l={environmentVariableSelector:e=>e.AWS_DEFAULTS_MODE,configFileSelector:e=>e.defaults_mode,default:"legacy"},h=({region:e=(0,a.Z)(t.GG),defaultsMode:i=(0,a.Z)(l)}={})=>(0,o.B)(async()=>{let n="function"==typeof i?await i():i;switch(n?.toLowerCase()){case"auto":return d(e);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(n?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${r.join(", ")}, got ${n}`)}}),d=async e=>{if(e){let i="function"==typeof e?await e():e,n=await c();return n?i===n?"in-region":"cross-region":"standard"}return"standard"},c=async()=>{if(process.env.AWS_EXECUTION_ENV&&(process.env[u]||process.env[s]))return process.env[u]??process.env[s];if(!process.env.AWS_EC2_METADATA_DISABLED)try{let{getInstanceMetadataEndpoint:e,httpRequest:i}=await n.e("560").then(n.bind(n,"./node_modules/@smithy/credential-provider-imds/dist-es/index.js")),t=await e();return(await i({...t,path:"/latest/meta-data/placement/region"})).toString()}catch(e){}}},"./node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"(e,i,n){"use strict";n.d(i,{k:()=>t});class t{capacity;data=new Map;parameters=[];constructor({size:e,params:i}){this.capacity=e??50,i&&(this.parameters=i)}get(e,i){let n=this.hash(e);if(!1===n)return i();if(!this.data.has(n)){if(this.data.size>this.capacity+10){let e=this.data.keys(),i=0;for(;;){let{value:n,done:t}=e.next();if(this.data.delete(n),t||++i>10)break}}this.data.set(n,i())}return this.data.get(n)}size(){return this.data.size}hash(e){let i="",{parameters:n}=this;if(0===n.length)return!1;for(let t of n){let n=String(e[t]??"");if(n.includes("|;"))return!1;i+=n+"|;"}return i}}},"./node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"(e,i,n){"use strict";n.d(i,{o:()=>a});let t=RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),a=e=>t.test(e)||e.startsWith("[")&&e.endsWith("]")},"./node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"(e,i,n){"use strict";n.d(i,{X:()=>a});let t=RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),a=(e,i=!1)=>{if(!i)return t.test(e);for(let i of e.split("."))if(!a(i))return!1;return!0}},"./node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"(e,i,n){"use strict";n.d(i,{s:()=>Y});let t="endpoints";function a(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${a(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(a).join(", ")})`:JSON.stringify(e,null,2)}class o extends Error{constructor(e){super(e),this.name="EndpointError"}}var u,s,r=n("./node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js");let l=(e,i)=>(e=>{let i=e.split("."),n=[];for(let t of i){let i=t.indexOf("[");if(-1!==i){if(t.indexOf("]")!==t.length-1)throw new o(`Path: '${e}' does not end with ']'`);let a=t.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new o(`Invalid array index: '${a}' in path: '${e}'`);0!==i&&n.push(t.slice(0,i)),n.push(a)}else n.push(t)}return n})(i).reduce((n,t)=>{if("object"!=typeof n)throw new o(`Index '${t}' in '${i}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(t)]:n[t]},e);var h=n("./node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js");(u=s||(s={})).HTTP="http",u.HTTPS="https";var d=n("./node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js");let c={[s.HTTP]:80,[s.HTTPS]:443},g={booleanEquals:(e,i)=>e===i,getAttr:l,isSet:e=>null!=e,isValidHostLabel:h.X,not:e=>!e,parseURL:e=>{let i=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){let{hostname:i,port:n,protocol:t="",path:a="",query:o={}}=e,u=new URL(`${t}//${i}${n?`:${n}`:""}${a}`);return u.search=Object.entries(o).map(([e,i])=>`${e}=${i}`).join("&"),u}return new URL(e)}catch(e){return null}})();if(!i)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;let n=i.href,{host:t,hostname:a,pathname:o,protocol:u,search:r}=i;if(r)return null;let l=u.slice(0,-1);if(!Object.values(s).includes(l))return null;let h=(0,d.o)(a),g=n.includes(`${t}:${c[l]}`)||"string"==typeof e&&e.includes(`${t}:${c[l]}`),p=`${t}${g?`:${c[l]}`:""}`;return{scheme:l,authority:p,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:h}},stringEquals:(e,i)=>e===i,substring:(e,i,n,t)=>i>=n||e.length<n?null:t?e.substring(e.length-n,e.length-i):e.substring(i,n),uriEncode:e=>encodeURIComponent(e).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)},p=(e,i)=>{let n=[],t={...i.endpointParams,...i.referenceRecord},a=0;for(;a<e.length;){let i=e.indexOf("{",a);if(-1===i){n.push(e.slice(a));break}n.push(e.slice(a,i));let o=e.indexOf("}",i);if(-1===o){n.push(e.slice(i));break}"{"===e[i+1]&&"}"===e[o+1]&&(n.push(e.slice(i+1,o)),a=o+2);let u=e.substring(i+1,o);if(u.includes("#")){let[e,i]=u.split("#");n.push(l(t[e],i))}else n.push(t[u]);a=o+1}return n.join("")},m=(e,i,n)=>{if("string"==typeof e)return p(e,n);if(e.fn)return y.callFunction(e,n);if(e.ref)return(({ref:e},i)=>({...i.endpointParams,...i.referenceRecord})[e])(e,n);throw new o(`'${i}': ${String(e)} is not a string, function or reference.`)},f=({fn:e,argv:i},n)=>{let t=i.map(e=>["boolean","number"].includes(typeof e)?e:y.evaluateExpression(e,"arg",n)),a=e.split(".");return a[0]in r.m&&null!=a[1]?r.m[a[0]][a[1]](...t):g[e](...t)},y={evaluateExpression:m,callFunction:f},S=({assign:e,...i},n)=>{if(e&&e in n.referenceRecord)throw new o(`'${e}' is already defined in Reference Record.`);let u=f(i,n);return n.logger?.debug?.(`${t} evaluateCondition: ${a(i)} = ${a(u)}`),{result:""===u||!!u,...null!=e&&{toAssign:{name:e,value:u}}}},b=(e=[],i)=>{let n={};for(let o of e){let{result:e,toAssign:u}=S(o,{...i,referenceRecord:{...i.referenceRecord,...n}});if(!e)return{result:e};u&&(n[u.name]=u.value,i.logger?.debug?.(`${t} assign: ${u.name} := ${a(u.value)}`))}return{result:!0,referenceRecord:n}},C=(e,i)=>Object.entries(e).reduce((e,[n,t])=>({...e,[n]:x.getEndpointProperty(t,i)}),{}),w=(e,i)=>{if(Array.isArray(e))return e.map(e=>w(e,i));switch(typeof e){case"string":return p(e,i);case"object":if(null===e)throw new o(`Unexpected endpoint property: ${e}`);return x.getEndpointProperties(e,i);case"boolean":return e;default:throw new o(`Unexpected endpoint property type: ${typeof e}`)}},x={getEndpointProperty:w,getEndpointProperties:C},T=(e,i)=>{let{conditions:n,endpoint:u}=e,{result:s,referenceRecord:r}=b(n,i);if(!s)return;let l={...i,referenceRecord:{...i.referenceRecord,...r}},{url:h,properties:d,headers:c}=u;return i.logger?.debug?.(`${t} Resolving endpoint from template: ${a(u)}`),{...void 0!=c&&{headers:Object.entries(c).reduce((e,[i,n])=>({...e,[i]:n.map(e=>{let n=m(e,"Header value entry",l);if("string"!=typeof n)throw new o(`Header '${i}' value '${n}' is not a string`);return n})}),{})},...void 0!=d&&{properties:C(d,l)},url:((e,i)=>{let n=m(e,"Endpoint URL",i);if("string"==typeof n)try{return new URL(n)}catch(e){throw console.error(`Failed to construct URL with ${n}`,e),e}throw new o(`Endpoint URL must be a string, got ${typeof n}`)})(h,l)}},_=(e,i)=>{let{conditions:n,error:t}=e,{result:a,referenceRecord:u}=b(n,i);if(a)throw new o(m(t,"Error",{...i,referenceRecord:{...i.referenceRecord,...u}}))},L=(e,i)=>{for(let n of e)if("endpoint"===n.type){let e=T(n,i);if(e)return e}else if("error"===n.type)_(n,i);else if("tree"===n.type){let e=E.evaluateTreeRule(n,i);if(e)return e}else throw new o(`Unknown endpoint rule: ${n}`);throw new o("Rules evaluation failed")},E={evaluateRules:L,evaluateTreeRule:(e,i)=>{let{conditions:n,rules:t}=e,{result:a,referenceRecord:o}=b(n,i);if(a)return E.evaluateRules(t,{...i,referenceRecord:{...i.referenceRecord,...o}})}},Y=(e,i)=>{let{endpointParams:n,logger:u}=i,{parameters:s,rules:r}=e;i.logger?.debug?.(`${t} Initial EndpointParams: ${a(n)}`);let l=Object.entries(s).filter(([,e])=>null!=e.default).map(([e,i])=>[e,i.default]);if(l.length>0)for(let[e,i]of l)n[e]=n[e]??i;for(let e of Object.entries(s).filter(([,e])=>e.required).map(([e])=>e))if(null==n[e])throw new o(`Missing required parameter: '${e}'`);let h=L(r,{endpointParams:n,logger:u,referenceRecord:{}});return i.logger?.debug?.(`${t} Resolved endpoint: ${a(h)}`),h}},"./node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"(e,i,n){"use strict";n.d(i,{m:()=>t});let t={}},"./node_modules/@smithy/util-hex-encoding/dist-es/index.js"(e,i,n){"use strict";n.d(i,{a:()=>o,n:()=>u});let t={},a={};for(let e=0;e<256;e++){let i=e.toString(16).toLowerCase();1===i.length&&(i=`0${i}`),t[e]=i,a[i]=e}function o(e){if(e.length%2!=0)throw Error("Hex encoded strings must have an even number length");let i=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2){let t=e.slice(n,n+2).toLowerCase();if(t in a)i[n/2]=a[t];else throw Error(`Cannot decode unrecognized sequence ${t} as hexadecimal`)}return i}function u(e){let i="";for(let n=0;n<e.byteLength;n++)i+=t[e[n]];return i}},"./node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"(e,i,n){"use strict";n.d(i,{u:()=>a});var t=n("./node_modules/@smithy/types/dist-es/middleware.js");let a=e=>e[t.V]||(e[t.V]={})},"./node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"(e,i,n){"use strict";n.d(i,{t:()=>t});let t=e=>{if("function"==typeof e)return e;let i=Promise.resolve(e);return()=>i}},"./node_modules/@smithy/util-retry/dist-es/config.js"(e,i,n){"use strict";var t,a;n.d(i,{L:()=>o,c:()=>t}),(a=t||(t={})).STANDARD="standard",a.ADAPTIVE="adaptive";let o=t.STANDARD},"./node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js"(e,i,n){"use strict";n.d(i,{c:()=>y});var t=n("./node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"),a=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js"),o=n("stream"),u=n("./node_modules/@smithy/util-base64/dist-es/fromBase64.js");let s=async e=>"function"==typeof Blob&&e instanceof Blob||e.constructor?.name==="Blob"?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await e.arrayBuffer()):r(e):l(e);async function r(e){var i;let n=await (i=e,new Promise((e,n)=>{let t=new FileReader;t.onloadend=()=>{if(2!==t.readyState)return n(Error("Reader aborted too early"));let i=t.result??"",a=i.indexOf(","),o=a>-1?a+1:i.length;e(i.substring(o))},t.onabort=()=>n(Error("Read aborted")),t.onerror=()=>n(t.error),t.readAsDataURL(i)}));return new Uint8Array((0,u.E)(n))}async function l(e){let i=[],n=e.getReader(),t=!1,a=0;for(;!t;){let{done:e,value:o}=await n.read();o&&(i.push(o),a+=o.length),t=e}let o=new Uint8Array(a),u=0;for(let e of i)o.set(e,u),u+=e.length;return o}var h=n("./node_modules/@smithy/util-base64/dist-es/toBase64.js"),d=n("./node_modules/@smithy/util-hex-encoding/dist-es/index.js"),c=n("./node_modules/@smithy/util-utf8/dist-es/toUtf8.js"),g=n("./node_modules/@smithy/util-stream/dist-es/stream-type-check.js");let p="The stream has already been transformed.",m=e=>"function"==typeof Blob&&e instanceof Blob,f="The stream has already been transformed.",y=e=>{if(!(e instanceof o.Readable))try{if(!m(e)&&!(0,g.H)(e)){let i=e?.__proto__?.constructor?.name||e;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${i}`)}let i=!1,n=async()=>{if(i)throw Error(p);return i=!0,await s(e)};return Object.assign(e,{transformToByteArray:n,transformToString:async e=>{let i=await n();if("base64"===e)return(0,h.n)(i);if("hex"===e)return(0,d.n)(i);if(void 0===e||"utf8"===e||"utf-8"===e)return(0,c.P)(i);if("function"==typeof TextDecoder)return new TextDecoder(e).decode(i);throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(i)throw Error(p);if(i=!0,m(e)){if("function"!=typeof e.stream)throw Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return e.stream()}if((0,g.H)(e))return e;throw Error(`Cannot transform payload to web stream, got ${e}`)}})}catch(n){let i=e?.__proto__?.constructor?.name||e;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${i}`)}let i=!1,n=async()=>{if(i)throw Error(f);return i=!0,await (0,t.k)(e)};return Object.assign(e,{transformToByteArray:n,transformToString:async e=>{let i=await n();return void 0===e||Buffer.isEncoding(e)?(0,a.Q)(i.buffer,i.byteOffset,i.byteLength).toString(e):new TextDecoder(e).decode(i)},transformToWebStream:()=>{if(i)throw Error(f);if(null!==e.readableFlowing)throw Error("The stream has been consumed by other callbacks.");if("function"!=typeof o.Readable.toWeb)throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return i=!0,o.Readable.toWeb(e)}})}},"./node_modules/@smithy/util-stream/dist-es/stream-type-check.js"(e,i,n){"use strict";n.d(i,{H:()=>t,q:()=>a});let t=e=>"function"==typeof ReadableStream&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),a=e=>"function"==typeof Blob&&(e?.constructor?.name===Blob.name||e instanceof Blob)},"./node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"(e,i,n){"use strict";n.d(i,{o:()=>t});let t=e=>encodeURIComponent(e).replace(/[!'()*]/g,a),a=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`},"./node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"(e,i,n){"use strict";n.d(i,{a:()=>a});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js");let a=e=>{let i=(0,t.s)(e,"utf8");return new Uint8Array(i.buffer,i.byteOffset,i.byteLength/Uint8Array.BYTES_PER_ELEMENT)}},"./node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"(e,i,n){"use strict";n.d(i,{F:()=>a});var t=n("./node_modules/@smithy/util-utf8/dist-es/fromUtf8.js");let a=e=>"string"==typeof e?(0,t.a)(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)},"./node_modules/@smithy/util-utf8/dist-es/toUtf8.js"(e,i,n){"use strict";n.d(i,{P:()=>a});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js");let a=e=>{if("string"==typeof e)return e;if("object"!=typeof e||"number"!=typeof e.byteOffset||"number"!=typeof e.byteLength)throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return(0,t.Q)(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}},"./node_modules/@smithy/uuid/dist-es/v4.js"(e,i,n){"use strict";n.d(i,{v4:()=>s});var t=n("crypto"),a=n.n(t);let o=a().randomUUID.bind(a()),u=Array.from({length:256},(e,i)=>i.toString(16).padStart(2,"0")),s=()=>{if(o)return o();let e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128,u[e[0]]+u[e[1]]+u[e[2]]+u[e[3]]+"-"+u[e[4]]+u[e[5]]+"-"+u[e[6]]+u[e[7]]+"-"+u[e[8]]+u[e[9]]+"-"+u[e[10]]+u[e[11]]+u[e[12]]+u[e[13]]+u[e[14]]+u[e[15]]}},"./node_modules/dotenv/lib/main.js"(e,i,n){let t=n("fs"),a=n("path"),o=n("os"),u=n("crypto"),s=n("./node_modules/dotenv/package.json").version,r=["\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 l(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}let h=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function d(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function c(e){console.log(`[dotenv@${s}] ${e}`)}function g(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 p(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 m(e){return"~"===e[0]?a.join(o.homedir(),e.slice(1)):e}let f={configDotenv:function(e){let i,n=a.resolve(process.cwd(),".env"),o="utf8",u=process.env;e&&null!=e.processEnv&&(u=e.processEnv);let s=l(u.DOTENV_CONFIG_DEBUG||e&&e.debug),h=l(u.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?o=e.encoding:s&&d("No encoding is specified. UTF-8 is used by default");let g=[n];if(e&&e.path)if(Array.isArray(e.path))for(let i of(g=[],e.path))g.push(m(i));else g=[m(e.path)];let p={};for(let n of g)try{let i=f.parse(t.readFileSync(n,{encoding:o}));f.populate(p,i,e)}catch(e){s&&d(`Failed to load ${n} ${e.message}`),i=e}let y=f.populate(u,p,e);if(s=l(u.DOTENV_CONFIG_DEBUG||s),h=l(u.DOTENV_CONFIG_QUIET||h),s||!h){var S;let e=Object.keys(y).length,n=[];for(let e of g)try{let i=a.relative(process.cwd(),e);n.push(i)}catch(n){s&&d(`Failed to load ${e} ${n.message}`),i=n}c(`injecting env (${e}) from ${n.join(",")} ${(S=`-- tip: ${r[Math.floor(Math.random()*r.length)]}`,process.stdout.isTTY?`\x1b[2m${S}\x1b[0m`:S)}`)}return i?{parsed:p,error:i}:{parsed:p}},_configVault:function(e){let i=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(i||!n)&&c("Loading env from encrypted .env.vault");let t=f._parseVault(e),a=process.env;return e&&null!=e.processEnv&&(a=e.processEnv),f.populate(a,t,e),{parsed:t}},_parseVault:function(e){let i,n=p(e=e||{});e.path=n;let t=f.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=g(e).split(","),o=a.length;for(let e=0;e<o;e++)try{let n=a[e].trim(),o=function(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 o=`DOTENV_VAULT_${a.toUpperCase()}`,u=e.parsed[o];if(!u){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:u,key:t}}(t,n);i=f.decrypt(o.ciphertext,o.key);break}catch(i){if(e+1>=o)throw i}return f.parse(i)},config:function(e){if(0===g(e).length)return f.configDotenv(e);let i=p(e);if(!i){var n;return n=`You set DOTENV_KEY but you are missing a .env.vault file at ${i}. Did you forget to build it?`,console.error(`[dotenv@${s}][WARN] ${n}`),f.configDotenv(e)}return f._configVault(e)},decrypt:function(e,i){let n=Buffer.from(i.slice(-64),"hex"),t=Buffer.from(e,"base64"),a=t.subarray(0,12),o=t.subarray(-16);t=t.subarray(12,-16);try{let e=u.createDecipheriv("aes-256-gcm",n,a);return e.setAuthTag(o),`${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=h.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),o={};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],o[n]=i[n]),t&&(!0===a?d(`"${n}" is already defined and WAS overwritten`):d(`"${n}" is already defined and was NOT overwritten`))):(e[n]=i[n],o[n]=i[n]);return o}};e.exports.configDotenv=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f},"./src/core/headers.ts"(e,i,n){"use strict";n.d(i,{n:()=>t,p:()=>a});let t=["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 a{static extractForwardHeaders(e){let i={};return e instanceof Headers?t.forEach(n=>{let t=e.get(n);t&&(i[n]=t)}):t.forEach(n=>{let t=e[n]||e[n.toLowerCase()];t&&(i[n]=t)}),i}}},"./src/database/index.ts"(e,i,n){"use strict";n.d(i,{M4:()=>h,Tj:()=>y,generateModels:()=>w,d_:()=>p,qd:()=>s.q,Lf:()=>m,y:()=>l,upgrade:()=>x,KU:()=>f});var t=n("./node_modules/drizzle-orm/node-postgres/driver.js"),a=n("pg"),o=n.n(a),u=n("child_process"),s=n("./src/database/models.ts");let r=!1;function l(){if(!r&&!process.env.PGDATABASE_URL)try{try{if(n("./node_modules/dotenv/lib/main.js").config(),process.env.PGDATABASE_URL){r=!0;return}}catch{}let e=`
30
+ ${(0,o.n)(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let i=[];for(let n of e.split("/"))n?.length!==0&&"."!==n&&(".."===n?i.pop():i.push(n));let n=`${e?.startsWith("/")?"/":""}${i.join("/")}${i.length>0&&e?.endsWith("/")?"/":""}`;return(0,R.o)(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if("object"!=typeof e||"string"!=typeof e.accessKeyId||"string"!=typeof e.secretAccessKey)throw Error("Resolved credential object is not valid")}formatDate(e){var i;let n=("number"==typeof(i=e)?new Date(1e3*i):"string"==typeof i?new Date(Number(i)?1e3*Number(i):i):i).toISOString().replace(/\.\d{3}Z$/,"Z").replace(/[\-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}class H extends B{headerFormatter=new Z;constructor({applyChecksum:e,credentials:i,region:n,service:t,sha256:a,uriEscapePath:o=!0}){super({applyChecksum:e,credentials:i,region:n,service:t,sha256:a,uriEscapePath:o})}async presign(e,i={}){let{signingDate:n=new Date,expiresIn:t=3600,unsignableHeaders:a,unhoistableHeaders:o,signableHeaders:u,hoistableHeaders:h,signingRegion:d,signingService:c}=i,g=await this.credentialProvider();this.validateResolvedCredentials(g);let p=d??await this.regionProvider(),{longDate:m,shortDate:f}=this.formatDate(n);if(t>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=T(f,p,c??this.service),S=((e,i={})=>{let{headers:n,query:t={}}=k.K.clone(e);for(let e of Object.keys(n)){let a=e.toLowerCase();("x-amz-"===a.slice(0,6)&&!i.unhoistableHeaders?.has(a)||i.hoistableHeaders?.has(a))&&(t[e]=n[e],delete n[e])}return{...e,headers:n,query:t}})(P(e),{unhoistableHeaders:o,hoistableHeaders:h});g.sessionToken&&(S.query[l]=g.sessionToken),S.query["X-Amz-Algorithm"]=b,S.query["X-Amz-Credential"]=`${g.accessKeyId}/${y}`,S.query[s]=m,S.query["X-Amz-Expires"]=t.toString(10);let C=E(S,a,u);return S.query["X-Amz-SignedHeaders"]=this.getCanonicalHeaderList(C),S.query[r]=await this.getSignature(m,y,this.getSigningKey(g,p,f,c),this.createCanonicalRequest(S,C,await D(e,this.sha256))),S}async sign(e,i){return"string"==typeof e?this.signString(e,i):e.headers&&e.payload?this.signEvent(e,i):e.message?this.signMessage(e,i):this.signRequest(e,i)}async signEvent({headers:e,payload:i},{signingDate:n=new Date,priorSignature:t,signingRegion:a,signingService:u}){let s=a??await this.regionProvider(),{shortDate:r,longDate:l}=this.formatDate(n),h=T(r,s,u??this.service),d=await D({headers:{},body:i},this.sha256),c=new this.sha256;c.update(e);let g=["AWS4-HMAC-SHA256-PAYLOAD",l,h,t,(0,o.n)(await c.digest()),d].join("\n");return this.signString(g,{signingDate:n,signingRegion:s,signingService:u})}async signMessage(e,{signingDate:i=new Date,signingRegion:n,signingService:t}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:i,signingRegion:n,signingService:t,priorSignature:e.priorSignature}).then(i=>({message:e.message,signature:i}))}async signString(e,{signingDate:i=new Date,signingRegion:n,signingService:t}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=n??await this.regionProvider(),{shortDate:r}=this.formatDate(i),l=new this.sha256(await this.getSigningKey(a,s,r,t));return l.update((0,u.F)(e)),(0,o.n)(await l.digest())}async signRequest(e,{signingDate:i=new Date,signableHeaders:n,unsignableHeaders:t,signingRegion:a,signingService:o}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let s=a??await this.regionProvider(),r=P(e),{longDate:l,shortDate:c}=this.formatDate(i),g=T(c,s,o??this.service);r.headers[d]=l,u.sessionToken&&(r.headers[m]=u.sessionToken);let f=await D(r,this.sha256);!((e,i)=>{for(let n of(e=e.toLowerCase(),Object.keys(i)))if(e===n.toLowerCase())return!0;return!1})(p,r.headers)&&this.applyChecksum&&(r.headers[p]=f);let y=E(r,t,n),S=await this.getSignature(l,g,this.getSigningKey(u,s,c,o),this.createCanonicalRequest(r,y,f));return r.headers[h]=`${b} Credential=${u.accessKeyId}/${g}, SignedHeaders=${this.getCanonicalHeaderList(y)}, Signature=${S}`,r}async getSignature(e,i,n,t){let a=await this.createStringToSign(e,i,t,b),s=new this.sha256(await n);return s.update((0,u.F)(a)),(0,o.n)(await s.digest())}getSigningKey(e,i,n,t){return _(this.sha256,e,n,i,t||this.service)}}},"./node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"(e,i,n){"use strict";n.d(i,{N:()=>t});class t{trace(){}debug(){}info(){}warn(){}error(){}}},"./node_modules/@smithy/smithy-client/dist-es/client.js"(e,i,n){"use strict";n.d(i,{K:()=>a});var t=n("./node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js");class a{config;middlewareStack=(0,t.o)();initConfig;handlers;constructor(e){this.config=e;const{protocol:i,protocolSettings:n}=e;n&&"function"==typeof i&&(e.protocol=new i(n))}send(e,i,n){let t,a="function"!=typeof i?i:void 0,o="function"==typeof i?i:n;if(void 0===a&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);let i=this.handlers;i.has(e.constructor)?t=i.get(e.constructor):(t=e.resolveMiddleware(this.middlewareStack,this.config,a),i.set(e.constructor,t))}else delete this.handlers,t=e.resolveMiddleware(this.middlewareStack,this.config,a);if(!o)return t(e).then(e=>e.output);t(e).then(e=>o(null,e.output),e=>o(e)).catch(()=>{})}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}},"./node_modules/@smithy/smithy-client/dist-es/command.js"(e,i,n){"use strict";n.d(i,{u:()=>r});var t=n("./node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"),a=n("./node_modules/@smithy/types/dist-es/middleware.js"),o=n("./node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js");let u="***SensitiveInformation***";function s(e,i){if(null==i)return i;let n=o.l.of(e);if(n.getMergedTraits().sensitive)return u;if(n.isListSchema()){if(n.getValueSchema().getMergedTraits().sensitive)return u}else if(n.isMapSchema()){if(n.getKeySchema().getMergedTraits().sensitive||n.getValueSchema().getMergedTraits().sensitive)return u}else if(n.isStructSchema()&&"object"==typeof i){let e={};for(let[t,a]of n.structIterator())null!=i[t]&&(e[t]=s(a,i[t]));return e}return i}class r{middlewareStack=(0,t.o)();schema;static classBuilder(){return new l}resolveMiddlewareWithContext(e,i,n,{middlewareFn:t,clientName:o,commandName:u,inputFilterSensitiveLog:s,outputFilterSensitiveLog:r,smithyContext:l,additionalContext:h,CommandCtor:d}){for(let a of t.bind(this)(d,e,i,n))this.middlewareStack.use(a);let c=e.concat(this.middlewareStack),{logger:g}=i,p={logger:g,clientName:o,commandName:u,inputFilterSensitiveLog:s,outputFilterSensitiveLog:r,[a.V]:{commandInstance:this,...l},...h},{requestHandler:m}=i;return c.resolve(e=>m.handle(e.request,n||{}),p)}}class l{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,i,n={}){return this._smithyContext={service:e,operation:i,...n},this}c(e={}){return this._additionalContext=e,this}n(e,i){return this._clientName=e,this._commandName=i,this}f(e=e=>e,i=e=>e){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=i,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){let e,i=this;return e=class extends r{input;static getEndpointParameterInstructions(){return i._ep}constructor(...[e]){super(),this.input=e??{},i._init(this),this.schema=i._operationSchema}resolveMiddleware(n,t,a){let o=i._operationSchema,u=o?.[4]??o?.input,r=o?.[5]??o?.output;return this.resolveMiddlewareWithContext(n,t,a,{CommandCtor:e,middlewareFn:i._middlewareFn,clientName:i._clientName,commandName:i._commandName,inputFilterSensitiveLog:i._inputFilterSensitiveLog??(o?s.bind(null,u):e=>e),outputFilterSensitiveLog:i._outputFilterSensitiveLog??(o?s.bind(null,r):e=>e),smithyContext:i._smithyContext,additionalContext:i._additionalContext})}serialize=i._serializer;deserialize=i._deserializer}}}},"./node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"(e,i,n){"use strict";n.d(i,{l:()=>t});let t=e=>{switch(e){case"standard":case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}},"./node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"(e,i,n){"use strict";n.d(i,{I:()=>a});let t=!1,a=e=>{e&&!t&&16>parseInt(e.substring(1,e.indexOf(".")))&&(t=!0)}},"./node_modules/@smithy/smithy-client/dist-es/exceptions.js"(e,i,n){"use strict";n.d(i,{M:()=>a,T:()=>t});class t extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){return!!e&&(t.prototype.isPrototypeOf(e)||!!e.$fault&&!!e.$metadata&&("client"===e.$fault||"server"===e.$fault))}static[Symbol.hasInstance](e){return!!e&&(this===t?t.isInstance(e):!!t.isInstance(e)&&(e.name&&this.name?this.prototype.isPrototypeOf(e)||e.name===this.name:this.prototype.isPrototypeOf(e)))}}let a=(e,i={})=>{Object.entries(i).filter(([,e])=>void 0!==e).forEach(([i,n])=>{(void 0==e[i]||""===e[i])&&(e[i]=n)});let n=e.message||e.Message||"UnknownError";return e.message=n,delete e.Message,e}},"./node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"(e,i,n){"use strict";var t,a;n.d(i,{uv:()=>u,xA:()=>o}),(a=t||(t={})).MD5="md5",a.CRC32="crc32",a.CRC32C="crc32c",a.SHA1="sha1",a.SHA256="sha256";let o=e=>Object.assign((e=>{let i=[];for(let n in t){let a=t[n];void 0!==e[a]&&i.push({algorithmId:()=>a,checksumConstructor:()=>e[a]})}return{addChecksumAlgorithm(e){i.push(e)},checksumAlgorithms:()=>i}})(e),{setRetryStrategy(i){e.retryStrategy=i},retryStrategy:()=>e.retryStrategy}),u=e=>{let i,n;return Object.assign((i={},e.checksumAlgorithms().forEach(e=>{i[e.algorithmId()]=e.checksumConstructor()}),i),((n={}).retryStrategy=e.retryStrategy(),n))}},"./node_modules/@smithy/types/dist-es/middleware.js"(e,i,n){"use strict";n.d(i,{V:()=>t});let t="__smithy_context"},"./node_modules/@smithy/types/dist-es/profile.js"(e,i,n){"use strict";var t,a;n.d(i,{I:()=>t}),(a=t||(t={})).PROFILE="profile",a.SSO_SESSION="sso-session",a.SERVICES="services"},"./node_modules/@smithy/url-parser/dist-es/index.js"(e,i,n){"use strict";n.d(i,{D:()=>t});let t=e=>{let i;if("string"==typeof e)return t(new URL(e));let{hostname:n,pathname:a,port:o,protocol:u,search:s}=e;return s&&(i=function(e){let i={};if(e=e.replace(/^\?/,""))for(let n of e.split("&")){let[e,t=null]=n.split("=");e=decodeURIComponent(e),t&&(t=decodeURIComponent(t)),e in i?Array.isArray(i[e])?i[e].push(t):i[e]=[i[e],t]:i[e]=t}return i}(s)),{hostname:n,port:o?parseInt(o):void 0,protocol:u,path:a,query:i}}},"./node_modules/@smithy/util-base64/dist-es/fromBase64.js"(e,i,n){"use strict";n.d(i,{E:()=>o});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js");let a=/^[A-Za-z0-9+/]*={0,2}$/,o=e=>{if(3*e.length%4!=0)throw TypeError("Incorrect padding on base64 string.");if(!a.exec(e))throw TypeError("Invalid base64 string.");let i=(0,t.s)(e,"base64");return new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}},"./node_modules/@smithy/util-base64/dist-es/toBase64.js"(e,i,n){"use strict";n.d(i,{n:()=>o});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js"),a=n("./node_modules/@smithy/util-utf8/dist-es/fromUtf8.js");let o=e=>{let i;if("object"!=typeof(i="string"==typeof e?(0,a.a)(e):e)||"number"!=typeof i.byteOffset||"number"!=typeof i.byteLength)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return(0,t.Q)(i.buffer,i.byteOffset,i.byteLength).toString("base64")}},"./node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js"(e,i,n){"use strict";n.d(i,{n:()=>a});var t=n("node:fs");let a=e=>{if(!e)return 0;if("string"==typeof e)return Buffer.byteLength(e);if("number"==typeof e.byteLength)return e.byteLength;if("number"==typeof e.size)return e.size;if("number"==typeof e.start&&"number"==typeof e.end)return e.end+1-e.start;if(e instanceof t.ReadStream){if(null!=e.path)return(0,t.lstatSync)(e.path).size;else if("number"==typeof e.fd)return(0,t.fstatSync)(e.fd).size}throw Error(`Body Length computation failed for ${e}`)}},"./node_modules/@smithy/util-buffer-from/dist-es/index.js"(e,i,n){"use strict";n.d(i,{Q:()=>o,s:()=>u});var t=n("./node_modules/@smithy/is-array-buffer/dist-es/index.js"),a=n("buffer");let o=(e,i=0,n=e.byteLength-i)=>{if(!(0,t.m)(e))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return a.Buffer.from(e,i,n)},u=(e,i)=>{if("string"!=typeof e)throw TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return i?a.Buffer.from(e,i):a.Buffer.from(e)}},"./node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js"(e,i,n){"use strict";n.d(i,{Q:()=>t});let t=(e,i,n)=>{if(i in e){if("true"===e[i])return!0;if("false"===e[i])return!1;throw Error(`Cannot load ${n} "${i}". Expected "true" or "false", got ${e[i]}.`)}}},"./node_modules/@smithy/util-config-provider/dist-es/types.js"(e,i,n){"use strict";var t,a;n.d(i,{c:()=>t}),(a=t||(t={})).ENV="env",a.CONFIG="shared config entry"},"./node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js"(e,i,n){"use strict";n.d(i,{I:()=>h});var t=n("./node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"),a=n("./node_modules/@smithy/node-config-provider/dist-es/configLoader.js"),o=n("./node_modules/@smithy/property-provider/dist-es/memoize.js");let u="AWS_REGION",s="AWS_DEFAULT_REGION",r=["in-region","cross-region","mobile","standard","legacy"],l={environmentVariableSelector:e=>e.AWS_DEFAULTS_MODE,configFileSelector:e=>e.defaults_mode,default:"legacy"},h=({region:e=(0,a.Z)(t.GG),defaultsMode:i=(0,a.Z)(l)}={})=>(0,o.B)(async()=>{let n="function"==typeof i?await i():i;switch(n?.toLowerCase()){case"auto":return d(e);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(n?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${r.join(", ")}, got ${n}`)}}),d=async e=>{if(e){let i="function"==typeof e?await e():e,n=await c();return n?i===n?"in-region":"cross-region":"standard"}return"standard"},c=async()=>{if(process.env.AWS_EXECUTION_ENV&&(process.env[u]||process.env[s]))return process.env[u]??process.env[s];if(!process.env.AWS_EC2_METADATA_DISABLED)try{let{getInstanceMetadataEndpoint:e,httpRequest:i}=await n.e("560").then(n.bind(n,"./node_modules/@smithy/credential-provider-imds/dist-es/index.js")),t=await e();return(await i({...t,path:"/latest/meta-data/placement/region"})).toString()}catch(e){}}},"./node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"(e,i,n){"use strict";n.d(i,{k:()=>t});class t{capacity;data=new Map;parameters=[];constructor({size:e,params:i}){this.capacity=e??50,i&&(this.parameters=i)}get(e,i){let n=this.hash(e);if(!1===n)return i();if(!this.data.has(n)){if(this.data.size>this.capacity+10){let e=this.data.keys(),i=0;for(;;){let{value:n,done:t}=e.next();if(this.data.delete(n),t||++i>10)break}}this.data.set(n,i())}return this.data.get(n)}size(){return this.data.size}hash(e){let i="",{parameters:n}=this;if(0===n.length)return!1;for(let t of n){let n=String(e[t]??"");if(n.includes("|;"))return!1;i+=n+"|;"}return i}}},"./node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"(e,i,n){"use strict";n.d(i,{o:()=>a});let t=RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),a=e=>t.test(e)||e.startsWith("[")&&e.endsWith("]")},"./node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"(e,i,n){"use strict";n.d(i,{X:()=>a});let t=RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),a=(e,i=!1)=>{if(!i)return t.test(e);for(let i of e.split("."))if(!a(i))return!1;return!0}},"./node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"(e,i,n){"use strict";n.d(i,{s:()=>Y});let t="endpoints";function a(e){return"object"!=typeof e||null==e?e:"ref"in e?`$${a(e.ref)}`:"fn"in e?`${e.fn}(${(e.argv||[]).map(a).join(", ")})`:JSON.stringify(e,null,2)}class o extends Error{constructor(e){super(e),this.name="EndpointError"}}var u,s,r=n("./node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js");let l=(e,i)=>(e=>{let i=e.split("."),n=[];for(let t of i){let i=t.indexOf("[");if(-1!==i){if(t.indexOf("]")!==t.length-1)throw new o(`Path: '${e}' does not end with ']'`);let a=t.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new o(`Invalid array index: '${a}' in path: '${e}'`);0!==i&&n.push(t.slice(0,i)),n.push(a)}else n.push(t)}return n})(i).reduce((n,t)=>{if("object"!=typeof n)throw new o(`Index '${t}' in '${i}' not found in '${JSON.stringify(e)}'`);return Array.isArray(n)?n[parseInt(t)]:n[t]},e);var h=n("./node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js");(u=s||(s={})).HTTP="http",u.HTTPS="https";var d=n("./node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js");let c={[s.HTTP]:80,[s.HTTPS]:443},g={booleanEquals:(e,i)=>e===i,getAttr:l,isSet:e=>null!=e,isValidHostLabel:h.X,not:e=>!e,parseURL:e=>{let i=(()=>{try{if(e instanceof URL)return e;if("object"==typeof e&&"hostname"in e){let{hostname:i,port:n,protocol:t="",path:a="",query:o={}}=e,u=new URL(`${t}//${i}${n?`:${n}`:""}${a}`);return u.search=Object.entries(o).map(([e,i])=>`${e}=${i}`).join("&"),u}return new URL(e)}catch(e){return null}})();if(!i)return console.error(`Unable to parse ${JSON.stringify(e)} as a whatwg URL.`),null;let n=i.href,{host:t,hostname:a,pathname:o,protocol:u,search:r}=i;if(r)return null;let l=u.slice(0,-1);if(!Object.values(s).includes(l))return null;let h=(0,d.o)(a),g=n.includes(`${t}:${c[l]}`)||"string"==typeof e&&e.includes(`${t}:${c[l]}`),p=`${t}${g?`:${c[l]}`:""}`;return{scheme:l,authority:p,path:o,normalizedPath:o.endsWith("/")?o:`${o}/`,isIp:h}},stringEquals:(e,i)=>e===i,substring:(e,i,n,t)=>i>=n||e.length<n?null:t?e.substring(e.length-n,e.length-i):e.substring(i,n),uriEncode:e=>encodeURIComponent(e).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)},p=(e,i)=>{let n=[],t={...i.endpointParams,...i.referenceRecord},a=0;for(;a<e.length;){let i=e.indexOf("{",a);if(-1===i){n.push(e.slice(a));break}n.push(e.slice(a,i));let o=e.indexOf("}",i);if(-1===o){n.push(e.slice(i));break}"{"===e[i+1]&&"}"===e[o+1]&&(n.push(e.slice(i+1,o)),a=o+2);let u=e.substring(i+1,o);if(u.includes("#")){let[e,i]=u.split("#");n.push(l(t[e],i))}else n.push(t[u]);a=o+1}return n.join("")},m=(e,i,n)=>{if("string"==typeof e)return p(e,n);if(e.fn)return y.callFunction(e,n);if(e.ref)return(({ref:e},i)=>({...i.endpointParams,...i.referenceRecord})[e])(e,n);throw new o(`'${i}': ${String(e)} is not a string, function or reference.`)},f=({fn:e,argv:i},n)=>{let t=i.map(e=>["boolean","number"].includes(typeof e)?e:y.evaluateExpression(e,"arg",n)),a=e.split(".");return a[0]in r.m&&null!=a[1]?r.m[a[0]][a[1]](...t):g[e](...t)},y={evaluateExpression:m,callFunction:f},S=({assign:e,...i},n)=>{if(e&&e in n.referenceRecord)throw new o(`'${e}' is already defined in Reference Record.`);let u=f(i,n);return n.logger?.debug?.(`${t} evaluateCondition: ${a(i)} = ${a(u)}`),{result:""===u||!!u,...null!=e&&{toAssign:{name:e,value:u}}}},b=(e=[],i)=>{let n={};for(let o of e){let{result:e,toAssign:u}=S(o,{...i,referenceRecord:{...i.referenceRecord,...n}});if(!e)return{result:e};u&&(n[u.name]=u.value,i.logger?.debug?.(`${t} assign: ${u.name} := ${a(u.value)}`))}return{result:!0,referenceRecord:n}},C=(e,i)=>Object.entries(e).reduce((e,[n,t])=>({...e,[n]:x.getEndpointProperty(t,i)}),{}),w=(e,i)=>{if(Array.isArray(e))return e.map(e=>w(e,i));switch(typeof e){case"string":return p(e,i);case"object":if(null===e)throw new o(`Unexpected endpoint property: ${e}`);return x.getEndpointProperties(e,i);case"boolean":return e;default:throw new o(`Unexpected endpoint property type: ${typeof e}`)}},x={getEndpointProperty:w,getEndpointProperties:C},T=(e,i)=>{let{conditions:n,endpoint:u}=e,{result:s,referenceRecord:r}=b(n,i);if(!s)return;let l={...i,referenceRecord:{...i.referenceRecord,...r}},{url:h,properties:d,headers:c}=u;return i.logger?.debug?.(`${t} Resolving endpoint from template: ${a(u)}`),{...void 0!=c&&{headers:Object.entries(c).reduce((e,[i,n])=>({...e,[i]:n.map(e=>{let n=m(e,"Header value entry",l);if("string"!=typeof n)throw new o(`Header '${i}' value '${n}' is not a string`);return n})}),{})},...void 0!=d&&{properties:C(d,l)},url:((e,i)=>{let n=m(e,"Endpoint URL",i);if("string"==typeof n)try{return new URL(n)}catch(e){throw console.error(`Failed to construct URL with ${n}`,e),e}throw new o(`Endpoint URL must be a string, got ${typeof n}`)})(h,l)}},_=(e,i)=>{let{conditions:n,error:t}=e,{result:a,referenceRecord:u}=b(n,i);if(a)throw new o(m(t,"Error",{...i,referenceRecord:{...i.referenceRecord,...u}}))},L=(e,i)=>{for(let n of e)if("endpoint"===n.type){let e=T(n,i);if(e)return e}else if("error"===n.type)_(n,i);else if("tree"===n.type){let e=E.evaluateTreeRule(n,i);if(e)return e}else throw new o(`Unknown endpoint rule: ${n}`);throw new o("Rules evaluation failed")},E={evaluateRules:L,evaluateTreeRule:(e,i)=>{let{conditions:n,rules:t}=e,{result:a,referenceRecord:o}=b(n,i);if(a)return E.evaluateRules(t,{...i,referenceRecord:{...i.referenceRecord,...o}})}},Y=(e,i)=>{let{endpointParams:n,logger:u}=i,{parameters:s,rules:r}=e;i.logger?.debug?.(`${t} Initial EndpointParams: ${a(n)}`);let l=Object.entries(s).filter(([,e])=>null!=e.default).map(([e,i])=>[e,i.default]);if(l.length>0)for(let[e,i]of l)n[e]=n[e]??i;for(let e of Object.entries(s).filter(([,e])=>e.required).map(([e])=>e))if(null==n[e])throw new o(`Missing required parameter: '${e}'`);let h=L(r,{endpointParams:n,logger:u,referenceRecord:{}});return i.logger?.debug?.(`${t} Resolved endpoint: ${a(h)}`),h}},"./node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"(e,i,n){"use strict";n.d(i,{m:()=>t});let t={}},"./node_modules/@smithy/util-hex-encoding/dist-es/index.js"(e,i,n){"use strict";n.d(i,{a:()=>o,n:()=>u});let t={},a={};for(let e=0;e<256;e++){let i=e.toString(16).toLowerCase();1===i.length&&(i=`0${i}`),t[e]=i,a[i]=e}function o(e){if(e.length%2!=0)throw Error("Hex encoded strings must have an even number length");let i=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2){let t=e.slice(n,n+2).toLowerCase();if(t in a)i[n/2]=a[t];else throw Error(`Cannot decode unrecognized sequence ${t} as hexadecimal`)}return i}function u(e){let i="";for(let n=0;n<e.byteLength;n++)i+=t[e[n]];return i}},"./node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"(e,i,n){"use strict";n.d(i,{u:()=>a});var t=n("./node_modules/@smithy/types/dist-es/middleware.js");let a=e=>e[t.V]||(e[t.V]={})},"./node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"(e,i,n){"use strict";n.d(i,{t:()=>t});let t=e=>{if("function"==typeof e)return e;let i=Promise.resolve(e);return()=>i}},"./node_modules/@smithy/util-retry/dist-es/config.js"(e,i,n){"use strict";var t,a;n.d(i,{L:()=>o,c:()=>t}),(a=t||(t={})).STANDARD="standard",a.ADAPTIVE="adaptive";let o=t.STANDARD},"./node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js"(e,i,n){"use strict";n.d(i,{c:()=>y});var t=n("./node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js"),a=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js"),o=n("stream"),u=n("./node_modules/@smithy/util-base64/dist-es/fromBase64.js");let s=async e=>"function"==typeof Blob&&e instanceof Blob||e.constructor?.name==="Blob"?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await e.arrayBuffer()):r(e):l(e);async function r(e){var i;let n=await (i=e,new Promise((e,n)=>{let t=new FileReader;t.onloadend=()=>{if(2!==t.readyState)return n(Error("Reader aborted too early"));let i=t.result??"",a=i.indexOf(","),o=a>-1?a+1:i.length;e(i.substring(o))},t.onabort=()=>n(Error("Read aborted")),t.onerror=()=>n(t.error),t.readAsDataURL(i)}));return new Uint8Array((0,u.E)(n))}async function l(e){let i=[],n=e.getReader(),t=!1,a=0;for(;!t;){let{done:e,value:o}=await n.read();o&&(i.push(o),a+=o.length),t=e}let o=new Uint8Array(a),u=0;for(let e of i)o.set(e,u),u+=e.length;return o}var h=n("./node_modules/@smithy/util-base64/dist-es/toBase64.js"),d=n("./node_modules/@smithy/util-hex-encoding/dist-es/index.js"),c=n("./node_modules/@smithy/util-utf8/dist-es/toUtf8.js"),g=n("./node_modules/@smithy/util-stream/dist-es/stream-type-check.js");let p="The stream has already been transformed.",m=e=>"function"==typeof Blob&&e instanceof Blob,f="The stream has already been transformed.",y=e=>{if(!(e instanceof o.Readable))try{if(!m(e)&&!(0,g.H)(e)){let i=e?.__proto__?.constructor?.name||e;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${i}`)}let i=!1,n=async()=>{if(i)throw Error(p);return i=!0,await s(e)};return Object.assign(e,{transformToByteArray:n,transformToString:async e=>{let i=await n();if("base64"===e)return(0,h.n)(i);if("hex"===e)return(0,d.n)(i);if(void 0===e||"utf8"===e||"utf-8"===e)return(0,c.P)(i);if("function"==typeof TextDecoder)return new TextDecoder(e).decode(i);throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(i)throw Error(p);if(i=!0,m(e)){if("function"!=typeof e.stream)throw Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return e.stream()}if((0,g.H)(e))return e;throw Error(`Cannot transform payload to web stream, got ${e}`)}})}catch(n){let i=e?.__proto__?.constructor?.name||e;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${i}`)}let i=!1,n=async()=>{if(i)throw Error(f);return i=!0,await (0,t.k)(e)};return Object.assign(e,{transformToByteArray:n,transformToString:async e=>{let i=await n();return void 0===e||Buffer.isEncoding(e)?(0,a.Q)(i.buffer,i.byteOffset,i.byteLength).toString(e):new TextDecoder(e).decode(i)},transformToWebStream:()=>{if(i)throw Error(f);if(null!==e.readableFlowing)throw Error("The stream has been consumed by other callbacks.");if("function"!=typeof o.Readable.toWeb)throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return i=!0,o.Readable.toWeb(e)}})}},"./node_modules/@smithy/util-stream/dist-es/stream-type-check.js"(e,i,n){"use strict";n.d(i,{H:()=>t,q:()=>a});let t=e=>"function"==typeof ReadableStream&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),a=e=>"function"==typeof Blob&&(e?.constructor?.name===Blob.name||e instanceof Blob)},"./node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"(e,i,n){"use strict";n.d(i,{o:()=>t});let t=e=>encodeURIComponent(e).replace(/[!'()*]/g,a),a=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`},"./node_modules/@smithy/util-utf8/dist-es/fromUtf8.js"(e,i,n){"use strict";n.d(i,{a:()=>a});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js");let a=e=>{let i=(0,t.s)(e,"utf8");return new Uint8Array(i.buffer,i.byteOffset,i.byteLength/Uint8Array.BYTES_PER_ELEMENT)}},"./node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"(e,i,n){"use strict";n.d(i,{F:()=>a});var t=n("./node_modules/@smithy/util-utf8/dist-es/fromUtf8.js");let a=e=>"string"==typeof e?(0,t.a)(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)},"./node_modules/@smithy/util-utf8/dist-es/toUtf8.js"(e,i,n){"use strict";n.d(i,{P:()=>a});var t=n("./node_modules/@smithy/util-buffer-from/dist-es/index.js");let a=e=>{if("string"==typeof e)return e;if("object"!=typeof e||"number"!=typeof e.byteOffset||"number"!=typeof e.byteLength)throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return(0,t.Q)(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}},"./node_modules/@smithy/uuid/dist-es/v4.js"(e,i,n){"use strict";n.d(i,{v4:()=>s});var t=n("crypto"),a=n.n(t);let o=a().randomUUID.bind(a()),u=Array.from({length:256},(e,i)=>i.toString(16).padStart(2,"0")),s=()=>{if(o)return o();let e=new Uint8Array(16);return crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128,u[e[0]]+u[e[1]]+u[e[2]]+u[e[3]]+"-"+u[e[4]]+u[e[5]]+"-"+u[e[6]]+u[e[7]]+"-"+u[e[8]]+u[e[9]]+"-"+u[e[10]]+u[e[11]]+u[e[12]]+u[e[13]]+u[e[14]]+u[e[15]]}},"./node_modules/dotenv/lib/main.js"(e,i,n){let t=n("fs"),a=n("path"),o=n("os"),u=n("crypto"),s=n("./node_modules/dotenv/package.json").version,r=["\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 l(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}let h=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function d(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function c(e){console.log(`[dotenv@${s}] ${e}`)}function g(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 p(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 m(e){return"~"===e[0]?a.join(o.homedir(),e.slice(1)):e}let f={configDotenv:function(e){let i,n=a.resolve(process.cwd(),".env"),o="utf8",u=process.env;e&&null!=e.processEnv&&(u=e.processEnv);let s=l(u.DOTENV_CONFIG_DEBUG||e&&e.debug),h=l(u.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?o=e.encoding:s&&d("No encoding is specified. UTF-8 is used by default");let g=[n];if(e&&e.path)if(Array.isArray(e.path))for(let i of(g=[],e.path))g.push(m(i));else g=[m(e.path)];let p={};for(let n of g)try{let i=f.parse(t.readFileSync(n,{encoding:o}));f.populate(p,i,e)}catch(e){s&&d(`Failed to load ${n} ${e.message}`),i=e}let y=f.populate(u,p,e);if(s=l(u.DOTENV_CONFIG_DEBUG||s),h=l(u.DOTENV_CONFIG_QUIET||h),s||!h){var S;let e=Object.keys(y).length,n=[];for(let e of g)try{let i=a.relative(process.cwd(),e);n.push(i)}catch(n){s&&d(`Failed to load ${e} ${n.message}`),i=n}c(`injecting env (${e}) from ${n.join(",")} ${(S=`-- tip: ${r[Math.floor(Math.random()*r.length)]}`,process.stdout.isTTY?`\x1b[2m${S}\x1b[0m`:S)}`)}return i?{parsed:p,error:i}:{parsed:p}},_configVault:function(e){let i=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(i||!n)&&c("Loading env from encrypted .env.vault");let t=f._parseVault(e),a=process.env;return e&&null!=e.processEnv&&(a=e.processEnv),f.populate(a,t,e),{parsed:t}},_parseVault:function(e){let i,n=p(e=e||{});e.path=n;let t=f.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=g(e).split(","),o=a.length;for(let e=0;e<o;e++)try{let n=a[e].trim(),o=function(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 o=`DOTENV_VAULT_${a.toUpperCase()}`,u=e.parsed[o];if(!u){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:u,key:t}}(t,n);i=f.decrypt(o.ciphertext,o.key);break}catch(i){if(e+1>=o)throw i}return f.parse(i)},config:function(e){if(0===g(e).length)return f.configDotenv(e);let i=p(e);if(!i){var n;return n=`You set DOTENV_KEY but you are missing a .env.vault file at ${i}. Did you forget to build it?`,console.error(`[dotenv@${s}][WARN] ${n}`),f.configDotenv(e)}return f._configVault(e)},decrypt:function(e,i){let n=Buffer.from(i.slice(-64),"hex"),t=Buffer.from(e,"base64"),a=t.subarray(0,12),o=t.subarray(-16);t=t.subarray(12,-16);try{let e=u.createDecipheriv("aes-256-gcm",n,a);return e.setAuthTag(o),`${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=h.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),o={};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],o[n]=i[n]),t&&(!0===a?d(`"${n}" is already defined and WAS overwritten`):d(`"${n}" is already defined and was NOT overwritten`))):(e[n]=i[n],o[n]=i[n]);return o}};e.exports.configDotenv=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f},"./src/core/headers.ts"(e,i,n){"use strict";n.d(i,{n:()=>t,p:()=>a});let t=["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 a{static extractForwardHeaders(e){let i={};return e instanceof Headers?t.forEach(n=>{let t=e.get(n);t&&(i[n]=t)}):t.forEach(n=>{let t=e[n]||e[n.toLowerCase()];t&&(i[n]=t)}),i}}},"./src/database/index.ts"(e,i,n){"use strict";n.d(i,{M4:()=>h,Tj:()=>y,generateModels:()=>x,d_:()=>p,qd:()=>s.q,Lf:()=>m,y:()=>l,upgrade:()=>T,KU:()=>f});var t=n("./node_modules/drizzle-orm/node-postgres/driver.js"),a=n("pg"),o=n.n(a),u=n("child_process"),s=n("./src/database/models.ts");let r=!1;function l(){if(!r&&!process.env.PGDATABASE_URL)try{try{if(n("./node_modules/dotenv/lib/main.js").config(),process.env.PGDATABASE_URL){r=!0;return}}catch{}let e=`
31
31
  import os
32
32
  import sys
33
33
  try:
@@ -39,7 +39,7 @@ try:
39
39
  print(f"{env_var.key}={env_var.value}")
40
40
  except Exception as e:
41
41
  print(f"# Error: {e}", file=sys.stderr)
42
- `;for(let i of(0,u.execSync)(`python3 -c '${e.replace(/'/g,"'\"'\"'")}'`,{encoding:"utf-8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim().split("\n")){if(i.startsWith("#"))continue;let e=i.indexOf("=");if(e>0){let n=i.substring(0,e),t=i.substring(e+1);(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),process.env[n]||(process.env[n]=t)}}r=!0}catch{}}function h(){l();let e=process.env.PGDATABASE_URL||"";if(!e)throw Error("Database URL not configured. Set PGDATABASE_URL environment variable.\nDid you create a database? You can create one via the Coze Coding platform.");return e.startsWith("postgres://")&&(e="postgresql://"+e.substring(11)),e}let d=null,c=null;async function g(e){let i=h(),n=new(o()).Pool({connectionString:i,max:e?.maxConnections??s.q.MAX_CONNECTIONS,idleTimeoutMillis:e?.idleTimeoutMillis??s.q.IDLE_TIMEOUT_MILLIS,connectionTimeoutMillis:e?.connectionTimeoutMillis??s.q.CONNECTION_TIMEOUT_MILLIS}),t=Date.now(),a=null;for(;Date.now()-t<s.q.MAX_RETRY_TIME;)try{let e=await n.connect();return await e.query("SELECT 1"),e.release(),n}catch(i){a=i;let e=((Date.now()-t)/1e3).toFixed(1);console.warn(`Database connection failed, retrying... (elapsed: ${e}s)`),await new Promise(e=>setTimeout(e,Math.min(1e3,s.q.MAX_RETRY_TIME-(Date.now()-t))))}throw console.error(`Database connection failed after ${s.q.MAX_RETRY_TIME/1e3}s: ${a?.message}`),a}async function p(e){return l(),d||(d=await g(e)),d}async function m(e){if(!c){let i=await p();c=e?(0,t.fd)(i,{schema:e}):(0,t.fd)(i)}return c}async function f(){return(await p()).connect()}async function y(){d&&(await d.end(),d=null,c=null)}var S=n("fs"),b=n("path"),C=n("os");async function w(e={}){let{outputPath:i=s.q.DEFAULT_SCHEMA_PATH,verbose:n=!1}=e;l();let t=h(),a=b.dirname(i);a&&!S.existsSync(a)&&S.mkdirSync(a,{recursive:!0});let o=S.mkdtempSync(b.join(C.tmpdir(),"drizzle-")),r=b.dirname(a),d=b.join(r,"drizzle.config.ts"),c=`
42
+ `;for(let i of(0,u.execSync)(`python3 -c '${e.replace(/'/g,"'\"'\"'")}'`,{encoding:"utf-8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim().split("\n")){if(i.startsWith("#"))continue;let e=i.indexOf("=");if(e>0){let n=i.substring(0,e),t=i.substring(e+1);(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),process.env[n]||(process.env[n]=t)}}r=!0}catch{}}function h(){l();let e=process.env.PGDATABASE_URL||"";if(!e)throw Error("Database URL not configured. Set PGDATABASE_URL environment variable.\nDid you create a database? You can create one via the Coze Coding platform.");return e.startsWith("postgres://")&&(e="postgresql://"+e.substring(11)),e}let d=null,c=null;async function g(e){let i=h(),n=new(o()).Pool({connectionString:i,max:e?.maxConnections??s.q.MAX_CONNECTIONS,idleTimeoutMillis:e?.idleTimeoutMillis??s.q.IDLE_TIMEOUT_MILLIS,connectionTimeoutMillis:e?.connectionTimeoutMillis??s.q.CONNECTION_TIMEOUT_MILLIS}),t=Date.now(),a=null;for(;Date.now()-t<s.q.MAX_RETRY_TIME;)try{let e=await n.connect();return await e.query("SELECT 1"),e.release(),n}catch(i){a=i;let e=((Date.now()-t)/1e3).toFixed(1);console.warn(`Database connection failed, retrying... (elapsed: ${e}s)`),await new Promise(e=>setTimeout(e,Math.min(1e3,s.q.MAX_RETRY_TIME-(Date.now()-t))))}throw console.error(`Database connection failed after ${s.q.MAX_RETRY_TIME/1e3}s: ${a?.message}`),a}async function p(e){return l(),d||(d=await g(e)),d}async function m(e){if(!c){let i=await p();c=e?(0,t.fd)(i,{schema:e}):(0,t.fd)(i)}return c}async function f(){return(await p()).connect()}async function y(){d&&(await d.end(),d=null,c=null)}var S=n("fs"),b=n("path"),C=n("os");let w="/usr/lib/node_modules";async function x(e={}){let{outputPath:i=s.q.DEFAULT_SCHEMA_PATH,verbose:n=!1}=e;l();let t=h(),a=b.dirname(i);a&&!S.existsSync(a)&&S.mkdirSync(a,{recursive:!0});let o=S.mkdtempSync(b.join(C.tmpdir(),"drizzle-")),r=b.dirname(a),d=b.join(r,"drizzle.config.ts"),c=`
43
43
  import { defineConfig } from 'drizzle-kit';
44
44
 
45
45
  export default defineConfig({
@@ -49,9 +49,9 @@ export default defineConfig({
49
49
  url: '${t}',
50
50
  },
51
51
  });
52
- `;try{let e;S.writeFileSync(d,c),n&&console.log("Introspecting database schema...");let t=`npx drizzle-kit introspect --config=${d}`;n&&console.log(`Running: ${t}`);try{e=(0,u.execSync)(t,{encoding:"utf-8",stdio:"pipe",timeout:6e4})}catch(n){let e=n.stderr?.toString()||"",i=n.stdout?.toString()||"";throw Error(`drizzle-kit introspect failed:
52
+ `;try{let e;S.writeFileSync(d,c),n&&console.log("Introspecting database schema...");let t=`npx drizzle-kit introspect --config=${d}`;n&&console.log(`Running: ${t}`);try{e=(0,u.execSync)(t,{encoding:"utf-8",stdio:"pipe",timeout:6e4,env:{...process.env,NODE_PATH:w}})}catch(n){let e=n.stderr?.toString()||"",i=n.stdout?.toString()||"";throw Error(`drizzle-kit introspect failed:
53
53
  ${e||i||n.message}`)}if(e&&(e.includes("error:")||e.includes("Error:")))throw Error(`drizzle-kit introspect failed:
54
- ${e}`);n&&e&&console.log(e);let s=b.join(o,"schema.ts"),r=b.join(o,"relations.ts");if(S.existsSync(s)&&(!function(e){if(!S.existsSync(e))return;let i=S.readFileSync(e,"utf-8"),n=i.replace(/\.generatedByDefaultAsIdentity\(\{[^}]*\}\)/g,".generatedByDefaultAsIdentity()");n!==i&&S.writeFileSync(e,n)}(s),S.copyFileSync(s,i),n&&console.log(`✓ Copied schema.ts to ${a}/`)),S.existsSync(r)){let e=b.join(a,"relations.ts");S.copyFileSync(r,e),n&&console.log(`✓ Copied relations.ts to ${a}/`)}try{(0,u.execSync)("git add -A",{encoding:"utf-8",stdio:"pipe",cwd:process.cwd()})}catch{}n&&console.log("✓ Schema generated successfully")}finally{S.existsSync(d)&&S.unlinkSync(d),S.existsSync(o)&&S.rmSync(o,{recursive:!0})}}async function x(e={}){let{schemaPath:i=s.q.DEFAULT_SCHEMA_PATH,projectPath:n=process.cwd(),verbose:t=!1}=e;l();let a=h(),o=b.isAbsolute(i)?i:b.join(n,i);if(!S.existsSync(o))throw Error(`Schema file not found: ${o}`);let r=b.dirname(o),d=b.dirname(r),c=b.join(d,"drizzle.config.ts"),g=`
54
+ ${e}`);n&&e&&console.log(e);let s=b.join(o,"schema.ts"),r=b.join(o,"relations.ts");if(S.existsSync(s)&&(!function(e){if(!S.existsSync(e))return;let i=S.readFileSync(e,"utf-8"),n=i.replace(/\.generatedByDefaultAsIdentity\(\{[^}]*\}\)/g,".generatedByDefaultAsIdentity()");n!==i&&S.writeFileSync(e,n)}(s),S.copyFileSync(s,i),n&&console.log(`✓ Copied schema.ts to ${a}/`)),S.existsSync(r)){let e=b.join(a,"relations.ts");S.copyFileSync(r,e),n&&console.log(`✓ Copied relations.ts to ${a}/`)}try{(0,u.execSync)("git add -A",{encoding:"utf-8",stdio:"pipe",cwd:process.cwd()})}catch{}n&&console.log("✓ Schema generated successfully")}finally{S.existsSync(d)&&S.unlinkSync(d),S.existsSync(o)&&S.rmSync(o,{recursive:!0})}}async function T(e={}){let{schemaPath:i=s.q.DEFAULT_SCHEMA_PATH,projectPath:n=process.cwd(),verbose:t=!1}=e;l();let a=h(),o=b.isAbsolute(i)?i:b.join(n,i);if(!S.existsSync(o))throw Error(`Schema file not found: ${o}`);let r=b.dirname(o),d=b.dirname(r),c=b.join(d,"drizzle.config.ts"),g=`
55
55
  import { defineConfig } from 'drizzle-kit';
56
56
 
57
57
  export default defineConfig({
@@ -61,7 +61,7 @@ export default defineConfig({
61
61
  url: '${a}',
62
62
  },
63
63
  });
64
- `;try{let e;S.writeFileSync(c,g),t&&console.log("Pushing schema changes to database...");let i=`npx drizzle-kit push --force --config=${c}`;t&&console.log(`Running: ${i}`);try{e=(0,u.execSync)(i,{encoding:"utf-8",stdio:"pipe",timeout:12e4,cwd:n})}catch(n){let e=n.stderr?.toString()||"",i=n.stdout?.toString()||"";throw Error(`drizzle-kit push failed:
64
+ `;try{let e;S.writeFileSync(c,g),t&&console.log("Pushing schema changes to database...");let i=`npx drizzle-kit push --force --config=${c}`;t&&console.log(`Running: ${i}`);try{e=(0,u.execSync)(i,{encoding:"utf-8",stdio:"pipe",timeout:12e4,cwd:n,env:{...process.env,NODE_PATH:w}})}catch(n){let e=n.stderr?.toString()||"",i=n.stdout?.toString()||"";throw Error(`drizzle-kit push failed:
65
65
  ${e||i||n.message}`)}if(e&&(e.includes("error:")||e.includes("Error:")))throw Error(`drizzle-kit push failed:
66
66
  ${e}`);t&&e&&console.log(e),t&&console.log("✅ Database migration completed successfully")}finally{S.existsSync(c)&&S.unlinkSync(c)}}},"./src/database/models.ts"(e,i,n){"use strict";n.d(i,{q:()=>t});class t{static MAX_CONNECTIONS=100;static IDLE_TIMEOUT_MILLIS=3e4;static CONNECTION_TIMEOUT_MILLIS=3e4;static MAX_RETRY_TIME=2e4;static DEFAULT_SCHEMA_PATH="src/storage/database/shared/schema.ts"}},"./src/embedding/types.ts"(e,i,n){"use strict";n.d(i,{F:()=>t});let t={defaultModel:"doubao-embedding-vision-251215",defaultEncodingFormat:"float",maxBatchSize:100}},"./src/image/models.ts"(e,i,n){"use strict";n.d(i,{K8:()=>t,Li:()=>s,Ru:()=>a,rD:()=>o,td:()=>u});class t{static DEFAULT_MODEL="doubao-seedream-4-5-251128";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 a(e){if(t.PRESET_SIZES.includes(e))return e;let i=e.match(/^(\d+)x(\d+)$/);if(!i)throw Error(`Invalid size format. Must be ${JSON.stringify(t.PRESET_SIZES)} or 'WIDTHxHEIGHT' format (e.g., 2048x2048). Got: ${e}`);let n=parseInt(i[1],10),a=parseInt(i[2],10);if(n<=0||a<=0)throw Error(`Width and height must be positive integers. Got: ${e}`);let o=n*a;if(o<t.MIN_TOTAL_PIXELS||o>t.MAX_TOTAL_PIXELS)throw Error(`Total pixels must be between ${t.MIN_TOTAL_PIXELS.toLocaleString()} and ${t.MAX_TOTAL_PIXELS.toLocaleString()}. Got: ${o.toLocaleString()} (${n}x${a})`);let u=n/a;if(u<t.MIN_ASPECT_RATIO||u>t.MAX_ASPECT_RATIO)throw Error(`Aspect ratio must be between 1:16 and 16:1. Got: ${n}:${a} (${u.toFixed(2)})`);return e}function o(e){try{return a(e)}catch{return t.DEFAULT_SIZE}}class u{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 s(e,i){let n=o(e.size||t.DEFAULT_SIZE);return{model:i,prompt:e.prompt,size:n,watermark:e.watermark??t.DEFAULT_WATERMARK,image:e.image,response_format:e.responseFormat||t.DEFAULT_RESPONSE_FORMAT,optimize_prompt_options:{mode:e.optimizePromptMode||t.DEFAULT_OPTIMIZE_PROMPT_MODE},sequential_image_generation:e.sequentialImageGeneration||t.DEFAULT_SEQUENTIAL_IMAGE_GENERATION,sequential_image_generation_options:{max_images:e.sequentialImageGenerationMaxImages||t.DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES}}}},"./src/llm/models.ts"(e,i,n){"use strict";n.d(i,{c:()=>t});let t={MODEL:"doubao-seed-1-8-251228",THINKING:"disabled",CACHING:"disabled",TEMPERATURE:1,STREAMING:!0}},"./src/s3/models.ts"(e,i,n){"use strict";n.d(i,{B:()=>t,a:()=>a});class t{static DEFAULT_REGION="cn-beijing";static DEFAULT_MAX_KEYS=1e3;static DEFAULT_PRESIGNED_EXPIRE_TIME=86400;static DEFAULT_UPLOAD_TIMEOUT=3e4}let a=/^[A-Za-z0-9._\-/]+$/},"./src/search/models.ts"(e,i,n){"use strict";function t(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 a(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}n.d(i,{a:()=>t,b:()=>a})},"./src/video/models.ts"(e,i,n){"use strict";n.d(i,{K:()=>t});class t{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}},"./src/video_edit/models.ts"(e,i,n){"use strict";n.d(i,{M:()=>t});class t{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"}},"./src/voice/models.ts"(e,i,n){"use strict";n.d(i,{UX:()=>t,Xd:()=>a,uF:()=>o});class t{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 a(e){let i={user:{uid:e.uid},req_params:{speaker:e.speaker||t.DEFAULT_SPEAKER,audio_params:{format:e.audioFormat||t.DEFAULT_AUDIO_FORMAT,sample_rate:e.sampleRate||t.DEFAULT_SAMPLE_RATE,speech_rate:e.speechRate??t.DEFAULT_SPEECH_RATE,loudness_rate:e.loudnessRate??t.DEFAULT_LOUDNESS_RATE}}};return e.text?i.req_params.text=e.text:e.ssml&&(i.req_params.ssml=e.ssml),i}function o(e){let i={};return e.url?i.url=e.url:e.base64Data&&(i.data=e.base64Data),{user:{uid:e.uid},audio:i}}},axios(e){"use strict";e.exports=require("axios")},buffer(e){"use strict";e.exports=require("buffer")},child_process(e){"use strict";e.exports=require("child_process")},crypto(e){"use strict";e.exports=require("crypto")},fs(e){"use strict";e.exports=require("fs")},"fs/promises"(e){"use strict";e.exports=require("fs/promises")},http(e){"use strict";e.exports=require("http")},"node:crypto"(e){"use strict";e.exports=require("node:crypto")},"node:fs"(e){"use strict";e.exports=require("node:fs")},"node:os"(e){"use strict";e.exports=require("node:os")},"node:path"(e){"use strict";e.exports=require("node:path")},os(e){"use strict";e.exports=require("os")},path(e){"use strict";e.exports=require("path")},pg(e){"use strict";e.exports=require("pg")},stream(e){"use strict";e.exports=require("stream")},url(e){"use strict";e.exports=require("url")},util(e){"use strict";e.exports=require("util")},"./node_modules/drizzle-orm/node-postgres/driver.js"(e,i,n){"use strict";let t,a;n.d(i,{fd:()=>ni});var o,u=n("pg");let s=Symbol.for("drizzle:entityKind");function r(e,i){if(!e||"object"!=typeof e)return!1;if(e instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,s))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(s in n&&n[s]===i[s])return!0;n=Object.getPrototypeOf(n)}return!1}Symbol.for("drizzle:hasOwnEntityKind");class l{static [s]="ConsoleLogWriter";write(e){console.log(e)}}class h{static [s]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new l}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 d{static [s]="NoopLogger";logQuery(){}}class c{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 [s]="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 g{static [s]="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 p=Symbol.for("drizzle:Name");class m{static [s]="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 f(e,this)}}class f{constructor(e,i){this.table=e,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static [s]="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),o=[this.table[p],...t,n[0].table[p],...a];return e??`${o.join("_")}_fk`}}function y(e,...i){return e(...i)}function S(e,i){return`${e[p]}_${i.join("_")}_unique`}class b{constructor(e,i){this.name=i,this.columns=e}static [s]=null;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new w(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class C{static [s]=null;name;constructor(e){this.name=e}on(...e){return new b(e,this.name)}}class w{constructor(e,i,n,t){this.table=e,this.columns=i,this.name=t??S(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static [s]=null;columns;name;nullsNotDistinct=!1;getName(){return this.name}}function x(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]}class T extends g{foreignKeyConfigs=[];static [s]="PgColumnBuilder";array(e){return new Y(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})=>y((n,t)=>{let a=new m(()=>({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 L(e,this.config)}}class _ extends c{constructor(e,i){i.uniqueName||(i.uniqueName=S(e,[i.name])),super(e,i),this.table=e}static [s]="PgColumn"}class L extends _{static [s]="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 E{static [s]=null;constructor(e,i,n,t){this.name=e,this.keyAsName=i,this.type=n,this.indexConfig=t}name;keyAsName;type;indexConfig}class Y extends T{static [s]="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 D(e,this.config,i)}}class D extends _{constructor(e,i,n,t){super(e,i),this.baseColumn=n,this.range=t,this.size=i.size}size;static [s]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=function(e){let[i]=function e(i,n=0){let t=[],a=n,o=!1;for(;a<i.length;){let u=i[a];if(","===u){(o||a===n)&&t.push(""),o=!0,a++;continue}if(o=!1,"\\"===u){a+=2;continue}if('"'===u){let[e,n]=x(i,a+1,!0);t.push(e),a=n;continue}if("}"===u)return[t,a+1];if("{"===u){let[n,o]=e(i,a+1);t.push(n),a=o;continue}let[s,r]=x(i,a,!1);t.push(s),a=r}return[t,a]}(e,1);return i}(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,i=!1){let n=e.map(e=>null===e?null:r(this.baseColumn,D)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return i?n:function e(i){return`{${i.map(i=>Array.isArray(i)?e(i):"string"==typeof i?`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${i}`).join(",")}}`}(n)}}class v extends T{static [s]="PgEnumObjectColumnBuilder";constructor(e,i){super(e,"string","PgEnumObjectColumn"),this.config.enum=i}build(e){return new Z(e,this.config)}}class Z extends _{static [s]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}let A=Symbol.for("drizzle:isPgEnum");class N extends T{static [s]="PgEnumColumnBuilder";constructor(e,i){super(e,"string","PgEnumColumn"),this.config.enum=i}build(e){return new J(e,this.config)}}class J extends _{static [s]="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 k{static [s]="Subquery";constructor(e,i,n,t=!1,a=[]){this._={brand:"Subquery",sql:e,selectedFields:i,alias:n,isWith:t,usedTables:a}}}class P extends k{static [s]="WithSubquery"}let M=(e,i)=>t?(a||(a=t.trace.getTracer("drizzle-orm","0.45.1")),y((n,t)=>t.startActiveSpan(e,e=>{try{return i(e)}catch(i){throw e.setStatus({code:n.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{e.end()}}),t,a)):i(),R=Symbol.for("drizzle:ViewBaseConfig"),B=Symbol.for("drizzle:Schema"),H=Symbol.for("drizzle:Columns"),X=Symbol.for("drizzle:ExtraConfigColumns"),F=Symbol.for("drizzle:OriginalName"),I=Symbol.for("drizzle:BaseName"),Q=Symbol.for("drizzle:IsAlias"),j=Symbol.for("drizzle:ExtraConfigBuilder"),O=Symbol.for("drizzle:IsDrizzleTable");class G{static [s]="Table";static Symbol={Name:p,Schema:B,OriginalName:F,Columns:H,ExtraConfigColumns:X,BaseName:I,IsAlias:Q,ExtraConfigBuilder:j};[p];[F];[B];[H];[X];[I];[Q]=!1;[O]=!0;[j]=void 0;constructor(e,i,n){this[p]=this[F]=e,this[B]=i,this[I]=n}}function K(e){return`${e[B]??"public"}.${e[p]}`}class ${static [s]=null}function U(e){return null!=e&&"function"==typeof e.getSQL}class z{static [s]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new W([this])}}class W{constructor(e){for(const i of(this.queryChunks=e,e))if(r(i,G)){const e=i[G.Symbol.Schema];this.usedTables.push(void 0===e?i[G.Symbol.Name]:e+"."+i[G.Symbol.Name])}}static [s]="SQL";decoder=V;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return M("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:o,prepareTyping:u,inlineParams:s,paramStartIndex:l}=n;var h=e.map(e=>{if(r(e,z))return{sql:e.value.join(""),params:[]};if(r(e,q))return{sql:a(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let i=[new z("(")];for(let[n,t]of e.entries())i.push(t),n<e.length-1&&i.push(new z(", "));return i.push(new z(")")),this.buildQueryFromSourceParams(i,n)}if(r(e,W))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:s||e.shouldInlineParams});if(r(e,G)){let i=e[G.Symbol.Schema],n=e[G.Symbol.Name];return{sql:void 0===i||e[Q]?a(n):a(i)+"."+a(n),params:[]}}if(r(e,c)){let n=t.getColumnCasing(e);if("indexes"===i.invokeSource)return{sql:a(n),params:[]};let o=e.table[G.Symbol.Schema];return{sql:e.table[Q]||void 0===o?a(e.table[G.Symbol.Name])+"."+a(n):a(o)+"."+a(e.table[G.Symbol.Name])+"."+a(n),params:[]}}if(r(e,er)){let i=e[R].schema,n=e[R].name;return{sql:void 0===i||e[R].isAlias?a(n):a(i)+"."+a(n),params:[]}}if(r(e,ei)){if(r(e.value,eo))return{sql:o(l.value++,e),params:[e],typings:["none"]};let i=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(r(i,W))return this.buildQueryFromSourceParams([i],n);if(s)return{sql:this.mapInlineParam(i,n),params:[]};let t=["none"];return u&&(t=[u(e.encoder)]),{sql:o(l.value++,i),params:[i],typings:t}}return r(e,eo)?{sql:o(l.value++,e),params:[e],typings:["none"]}:r(e,W.Aliased)&&void 0!==e.fieldAlias?{sql:a(e.fieldAlias),params:[]}:r(e,k)?e._.isWith?{sql:a(e._.alias),params:[]}:this.buildQueryFromSourceParams([new z("("),e._.sql,new z(") "),new q(e._.alias)],n):e&&"function"==typeof e&&A in e&&!0===e[A]?e.schema?{sql:a(e.schema)+"."+a(e.enumName),params:[]}:{sql:a(e.enumName),params:[]}:U(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new z("("),e.getSQL(),new z(")")],n):s?{sql:this.mapInlineParam(e,n),params:[]}:{sql:o(l.value++,e),params:[e],typings:["none"]}});let d={sql:"",params:[]};for(let e of h)d.sql+=e.sql,d.params.push(...e.params),e.typings?.length&&(d.typings||(d.typings=[]),d.typings.push(...e.typings));return d}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 W.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 q{constructor(e){this.value=e}static [s]="Name";brand;getSQL(){return new W([this])}}let V={mapFromDriverValue:e=>e},ee={mapToDriverValue:e=>e};({...V,...ee});class ei{constructor(e,i=ee){this.value=e,this.encoder=i}static [s]="Param";brand;getSQL(){return new W([this])}}function en(e,...i){let n=[];for(let[t,a]of((i.length>0||e.length>0&&""!==e[0])&&n.push(new z(e[0])),i.entries()))n.push(a,new z(e[t+1]));return new W(n)}(o=en||(en={})).empty=function(){return new W([])},o.fromList=function(e){return new W(e)},o.raw=function(e){return new W([new z(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 W(n)},o.identifier=function(e){return new q(e)},o.placeholder=function(e){return new eo(e)},o.param=function(e,i){return new ei(e,i)};var et=W||(W={});class ea{constructor(e,i){this.sql=e,this.fieldAlias=i}static [s]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new ea(this.sql,this.fieldAlias)}}et.Aliased=ea;class eo{constructor(e){this.name=e}static [s]="Placeholder";getSQL(){return new W([this])}}function eu(e,i){return e.map(e=>{if(r(e,eo)){if(!(e.name in i))throw Error(`No value for placeholder "${e.name}" was provided`);return i[e.name]}if(r(e,ei)&&r(e.value,eo)){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 es=Symbol.for("drizzle:IsDrizzleView");class er{static [s]="View";[R];[es]=!0;constructor({name:e,schema:i,selectedFields:n,query:t}){this[R]={name:e,originalName:e,schema:i,selectedFields:n,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new W([this])}}c.prototype.getSQL=function(){return new W([this])},G.prototype.getSQL=function(){return new W([this])},k.prototype.getSQL=function(){return new W([this])};class el{constructor(e){this.table=e}static [s]="ColumnAliasProxyHandler";get(e,i){return"table"===i?this.table:e[i]}}class eh{constructor(e,i){this.alias=e,this.replaceOriginalName=i}static [s]="TableAliasProxyHandler";get(e,i){if(i===G.Symbol.IsAlias)return!0;if(i===G.Symbol.Name||this.replaceOriginalName&&i===G.Symbol.OriginalName)return this.alias;if(i===R)return{...e[R],name:this.alias,isAlias:!0};if(i===G.Symbol.Columns){let i=e[G.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map(t=>{n[t]=new Proxy(i[t],new el(new Proxy(e,this)))}),n}let n=e[i];return r(n,c)?new Proxy(n,new el(new Proxy(e,this))):n}}class ed{constructor(e){this.alias=e}static [s]=null;get(e,i){return"sourceTable"===i?ec(e.sourceTable,this.alias):e[i]}}function ec(e,i){return new Proxy(e,new eh(i,!1))}function eg(e,i){return new Proxy(e,new el(new Proxy(e.table,new eh(i,!1))))}function ep(e,i){return new W.Aliased(em(e.sql,i),e.fieldAlias)}function em(e,i){return en.join(e.queryChunks.map(e=>r(e,c)?eg(e,i):r(e,W)?em(e,i):r(e,W.Aliased)?ep(e,i):e))}function ef(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function ey(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 eS(e){return e}class eb{static [s]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?ef:"camelCase"===e?ey:eS}getColumnCasing(e){if(!e.keyAsName)return e.name;let i=e.table[G.Symbol.Schema]??"public",n=e.table[G.Symbol.OriginalName],t=`${i}.${n}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let i=e[G.Symbol.Schema]??"public",n=e[G.Symbol.OriginalName],t=`${i}.${n}`;if(!this.cachedTables[t]){for(let i of Object.values(e[G.Symbol.Columns])){let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class eC extends Error{static [s]="DrizzleError";constructor({message:e,cause:i}){super(e),this.name="DrizzleError",this.cause=i}}class ew extends Error{constructor(e,i,n){super(`Failed query: ${e}
67
67
  params: ${i}`),this.query=e,this.params=i,this.cause=n,Error.captureStackTrace(this,ew),n&&(this.cause=n)}}class ex extends eC{static [s]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class eT extends T{static [s]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new e_(e,this.config)}}class e_ extends _{static [s]="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 eL extends T{static [s]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new eE(e,this.config)}}class eE extends _{static [s]="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 eY extends T{static [s]="PgNumericBuilder";constructor(e,i,n){super(e,"string","PgNumeric"),this.config.precision=i,this.config.scale=n}build(e){return new eD(e,this.config)}}class eD extends _{static [s]="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 ev extends T{static [s]="PgNumericNumberBuilder";constructor(e,i,n){super(e,"number","PgNumericNumber"),this.config.precision=i,this.config.scale=n}build(e){return new eZ(e,this.config)}}class eZ extends _{static [s]="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 eA extends T{static [s]="PgNumericBigIntBuilder";constructor(e,i,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=i,this.config.scale=n}build(e){return new eN(e,this.config)}}class eN extends _{static [s]="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 eJ extends T{static [s]="PgDateColumnBaseBuilder";defaultNow(){return this.default(en`now()`)}}class ek extends eJ{constructor(e,i,n){super(e,"string","PgTime"),this.withTimezone=i,this.precision=n,this.config.withTimezone=i,this.config.precision=n}static [s]="PgTimeBuilder";build(e){return new eP(e,this.config)}}class eP extends _{static [s]="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 eM extends eJ{static [s]="PgTimestampBuilder";constructor(e,i,n){super(e,"date","PgTimestamp"),this.config.withTimezone=i,this.config.precision=n}build(e){return new eR(e,this.config)}}class eR extends _{static [s]="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 eB extends eJ{static [s]="PgTimestampStringBuilder";constructor(e,i,n){super(e,"string","PgTimestampString"),this.config.withTimezone=i,this.config.precision=n}build(e){return new eH(e,this.config)}}class eH extends _{static [s]="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 eX extends eJ{static [s]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new eF(e,this.config)}}class eF extends _{static [s]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?new Date(e):e}mapToDriverValue(e){return e.toISOString()}}class eI extends eJ{static [s]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new eQ(e,this.config)}}class eQ extends _{static [s]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?e:e.toISOString().slice(0,-14)}}class ej extends T{static [s]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(en`gen_random_uuid()`)}build(e){return new eO(e,this.config)}}class eO extends _{static [s]="PgUUID";getSQLType(){return"uuid"}}let eG=Symbol.for("drizzle:PgInlineForeignKeys"),eK=Symbol.for("drizzle:EnableRLS");class e$ extends G{static [s]="PgTable";static Symbol=Object.assign({},G.Symbol,{InlineForeignKeys:eG,EnableRLS:eK});[eG]=[];[eK]=!1;[G.Symbol.ExtraConfigBuilder]=void 0;[G.Symbol.ExtraConfigColumns]={}}class eU{static [s]="PgPrimaryKeyBuilder";columns;name;constructor(e,i){this.columns=e,this.name=i}build(e){return new ez(e,this.columns,this.name)}}class ez{constructor(e,i,n){this.table=e,this.columns=i,this.name=n}static [s]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[e$.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}function eW(e,i){return"object"!=typeof i||null===i||!("mapToDriverValue"in i)||"function"!=typeof i.mapToDriverValue||U(e)||r(e,ei)||r(e,eo)||r(e,c)||r(e,G)||r(e,er)?e:new ei(e,i)}let eq=(e,i)=>en`${e} = ${eW(i,e)}`,eV=(e,i)=>en`${e} <> ${eW(i,e)}`;function e0(...e){let i=e.filter(e=>void 0!==e);if(0!==i.length)return new W(1===i.length?i:[new z("("),en.join(i,new z(" and ")),new z(")")])}function e1(...e){let i=e.filter(e=>void 0!==e);if(0!==i.length)return new W(1===i.length?i:[new z("("),en.join(i,new z(" or ")),new z(")")])}function e3(e){return en`not ${e}`}let e2=(e,i)=>en`${e} > ${eW(i,e)}`,e4=(e,i)=>en`${e} >= ${eW(i,e)}`,e6=(e,i)=>en`${e} < ${eW(i,e)}`,e8=(e,i)=>en`${e} <= ${eW(i,e)}`;function e5(e,i){return Array.isArray(i)?0===i.length?en`false`:en`${e} in ${i.map(i=>eW(i,e))}`:en`${e} in ${eW(i,e)}`}function e7(e,i){return Array.isArray(i)?0===i.length?en`true`:en`${e} not in ${i.map(i=>eW(i,e))}`:en`${e} not in ${eW(i,e)}`}function e9(e){return en`${e} is null`}function ie(e){return en`${e} is not null`}function ii(e){return en`exists ${e}`}function it(e){return en`not exists ${e}`}function ia(e,i,n){return en`${e} between ${eW(i,e)} and ${eW(n,e)}`}function io(e,i,n){return en`${e} not between ${eW(i,e)} and ${eW(n,e)}`}function iu(e,i){return en`${e} like ${i}`}function is(e,i){return en`${e} not like ${i}`}function ir(e,i){return en`${e} ilike ${i}`}function il(e,i){return en`${e} not ilike ${i}`}function ih(e){return en`${e} asc`}function id(e){return en`${e} desc`}class ic{constructor(e,i,n){this.sourceTable=e,this.referencedTable=i,this.relationName=n,this.referencedTableName=i[G.Symbol.Name]}static [s]="Relation";referencedTableName;fieldName}class ig{constructor(e,i){this.table=e,this.config=i}static [s]="Relations"}class ip extends ic{constructor(e,i,n,t){super(e,i,n?.relationName),this.config=n,this.isNullable=t}static [s]="One";withFieldName(e){let i=new ip(this.sourceTable,this.referencedTable,this.config,this.isNullable);return i.fieldName=e,i}}class im extends ic{constructor(e,i,n){super(e,i,n?.relationName),this.config=n}static [s]="Many";withFieldName(e){let i=new im(this.sourceTable,this.referencedTable,this.config);return i.fieldName=e,i}}function iy(e){return{one:function(i,n){return new ip(e,i,n,n?.fields.reduce((e,i)=>e&&i.notNull,!0)??!1)},many:function(i,n){return new im(e,i,n)}}}function iS(e,i){return Object.entries(e).reduce((e,[n,t])=>{if("string"!=typeof n)return e;let a=i?[...i,n]:[n];return r(t,c)||r(t,W)||r(t,W.Aliased)||r(t,k)?e.push({path:a,field:t}):r(t,G)?e.push(...iS(t[G.Symbol.Columns],a)):e.push(...iS(t,a)),e},[])}function ib(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 iC(e,i){let n=Object.entries(i).filter(([,e])=>void 0!==e).map(([i,n])=>r(n,W)||r(n,c)?[i,n]:[i,new ei(n,e[G.Symbol.Columns][i])]);if(0===n.length)throw Error("No values to set");return Object.fromEntries(n)}function iw(e){return r(e,k)?e._.alias:r(e,er)?e[R].name:r(e,W)?void 0:e[G.Symbol.IsAlias]?e[G.Symbol.Name]:e[G.Symbol.BaseName]}"u"<typeof TextDecoder||new TextDecoder;class ix extends er{static [s]="PgViewBase"}class iT{static [s]="PgDialect";casing;constructor(e){this.casing=new eb(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",o=en`