UNPKG

decocms

Version:

Deco CMS — Self-hostable MCP Gateway for managing AI connections and tools

5 lines (4 loc) • 19 kB
// @bun var T=import.meta.require;var i="16";function E(h){return{name:"decocms",systemDatabaseUrl:h.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:h.poolSize,runAdminServer:!1,executorID:h.executorID,applicationVersion:i,...h.listenQueues!==void 0?{listenQueues:h.listenQueues}:{}}}function j(h,w={}){let{signal:f}=w;if(f?.aborted)return Promise.reject(f.reason);return new Promise((y,c)=>{let o=()=>{clearTimeout(+d),c(f?.reason)},d=_(()=>{f?.removeEventListener("abort",o),y()},h);f?.addEventListener("abort",o,{once:!0})})}var Q=2147483647;function _(h,w){if(w=Math.trunc(Math.max(w,0)||0),w<=Q){let o=Number(setTimeout(h,w));return{valueOf:()=>o}}let f=Date.now(),y,c=()=>{let o=w-(Date.now()-f);y=o>Q?Number(setTimeout(c,Q)):Number(setTimeout(h,o))};return c(),{valueOf:()=>y}}import M from"pg";var R=8314027461559302n,P=600000,g=500;async function G(h,w){let{databaseUrl:f,lockTimeoutMs:y=P}=h,c=h.log??((W)=>console.log(W)),o=new M.Client({connectionString:f});await o.connect();let J=Date.now(),d=!1;try{while(!d){if(d=(await o.query("SELECT pg_try_advisory_lock($1) AS locked",[R.toString()])).rows[0]?.locked===!0,d)break;if(Date.now()-J>=y)throw Error(`Timed out after ${y}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await j(g)}let W=Date.now()-J;if(W>1000)c(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await w()}finally{if(d)try{await o.query("SELECT pg_advisory_unlock($1)",[R.toString()])}catch{}await o.end().catch(()=>{})}}import{homedir as u}from"os";var A=new Set(["all","worker","api"]);function p(h){let w=(h??"").trim();return A.has(w)?w:"all"}var I=new Set(["production","development","test"]);function t(h){let w=(h??"").trim();return I.has(w)?w:"development"}function k(h){return h==="true"||h==="1"}function X(h,w,f){if(w===void 0||w==="")return;let y=Number(w);if(!Number.isSafeInteger(y)||y<=0)throw Error(`${h} must be a positive integer`);if(f!==void 0&&y>f)throw Error(`${h} must be at most ${f}`);return y}function z(h,w,f,y){return X(h,w,y)??f}function l(h){let w={};for(let f of(h??"").split(",")){let y=f.trim();if(!y)continue;let c=y.indexOf("="),o=c>0?y.slice(0,c).trim():"",J=c>0?y.slice(c+1).trim():"";if(!o||!J){console.warn(`STRIPE_PLAN_PRICE_IDS: ignoring unparseable entry "${y}" \u2014 expected price_xxx=planId`);continue}w[o]=J}return w}function n(h){let w={};for(let f of(h??"").split(",")){let y=f.trim();if(!y)continue;let c=y.indexOf("="),o=c>0?y.slice(0,c).trim():"",J=c>0?y.slice(c+1).trim():"";if(!o||!J){console.warn(`MCP_INTERNAL_HOST_MAP: ignoring unparseable entry "${y}" \u2014 expected host=origin`);continue}w[o]=J}return w}function V(h,w,f,y){if(w===void 0||w==="")return f;let c=Number(w);if(!Number.isSafeInteger(c)||c<0)throw Error(`${h} must be a non-negative integer`);if(y!==void 0&&c>y)throw Error(`${h} must be at most ${y}`);return c}function U(h,w){if(h===void 0||h==="")return w;return h==="true"||h==="1"}function r(h){return h===void 0||h===""||h==="true"||h==="1"}function m(h,w){return h||w}function q(h){let w=h.DATA_DIR||h.DECOCMS_HOME||`${u()}/deco`,f=t(h.NODE_ENV),y=h.VOICE_CONVERSATION_PROVIDER?.trim()||"elevenlabs",c={nodeEnv:f,port:z("PORT",h.PORT,3000,65535),baseUrl:h.BASE_URL,publicUrl:m(h.STUDIO_PUBLIC_URL,h.MESH_PUBLIC_URL),dataDir:w,voiceConversationProvider:y==="elevenlabs"||y==="openai"?y:null,openaiLiveApiKey:h.OPENAI_LIVE_API_KEY,openaiLiveModel:h.OPENAI_LIVE_MODEL?.trim()||"gpt-live-1",openaiLiveVoice:h.OPENAI_LIVE_VOICE?.trim()||"marin",elevenlabsApiKey:h.ELEVENLABS_API_KEY,elevenlabsVoiceId:h.ELEVENLABS_VOICE_ID||"JBFqnCBsd6RMkjVDRZzb",elevenlabsVoiceModel:h.ELEVENLABS_VOICE_MODEL||"eleven_v4_turbo",elevenlabsConversationModel:h.ELEVENLABS_CONVERSATION_MODEL?.trim()||"gemini-2.5-flash",databaseUrl:h.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/postgres",databasePgSsl:k(h.DATABASE_PG_SSL),databasePoolMax:z("DATABASE_POOL_MAX",h.DATABASE_POOL_MAX,5),dbosPoolSize:z("DBOS_POOL_SIZE",h.DBOS_POOL_SIZE,5),betterAuthSecret:h.BETTER_AUTH_SECRET||"",encryptionKey:h.ENCRYPTION_KEY||"",studioJwtSecret:m(h.STUDIO_JWT_SECRET,h.MESH_JWT_SECRET),localMode:k(h.DECOCMS_LOCAL_MODE),disableRateLimit:k(h.DISABLE_RATE_LIMIT),jiraAllowLocalSiteUrl:k(h.JIRA_ALLOW_LOCAL_SITE_URL),codexUsageUrl:h.CODEX_USAGE_URL||"https://chatgpt.com/backend-api/wham/usage",claudeUsageUrl:h.CLAUDE_USAGE_URL||"https://api.anthropic.com/api/oauth/usage",jiraSettleSeconds:z("JIRA_SETTLE_SECONDS",h.JIRA_SETTLE_SECONDS,20,3600),studioProvisionSecretKey:h.STUDIO_PROVISION_SECRET_KEY,deploymentAdminEmails:(h.DEPLOYMENT_ADMIN_EMAILS??"").split(",").map((o)=>o.trim().toLowerCase()).filter(Boolean),taskBoardAdminOrgIds:(h.STUDIO_ADMIN_ORG_IDS??"").split(",").map((o)=>o.trim()).filter(Boolean),feedbackOrgId:h.STUDIO_FEEDBACK_ORG_ID?.trim()||void 0,feedbackProjectId:h.STUDIO_FEEDBACK_PROJECT_ID?.trim()||void 0,deploymentAdminToken:h.DEPLOYMENT_ADMIN_TOKEN||void 0,clickhouseUrl:h.CLICKHOUSE_URL,clickhouseMaxMemoryUsage:X("CLICKHOUSE_MAX_MEMORY_USAGE",h.CLICKHOUSE_MAX_MEMORY_USAGE),monitoringOtlpEndpoint:h.MONITORING_OTLP_ENDPOINT,otelServiceName:h.OTEL_SERVICE_NAME||"studio",natsUrls:(h.NATS_URL||"nats://localhost:4222").split(",").map((o)=>o.trim()).filter(Boolean),natsCredsPath:h.NATS_CREDS,natsUser:h.NATS_USER||void 0,natsPassword:h.NATS_PASSWORD||void 0,configPath:h.CONFIG_PATH||"./config.json",aiGatewayEnabled:k(h.DECO_AI_GATEWAY_ENABLED),aiGatewayUrl:h.DECO_AI_GATEWAY_URL||"https://ai-site.deco.site",aiGatewayAdminToken:h.DECO_AI_GATEWAY_ADMIN_TOKEN,stripeWebhookSecret:h.STRIPE_WEBHOOK_SECRET,stripeSecretKey:h.STRIPE_SECRET_KEY,stripeOrgPriceId:h.STRIPE_ORG_PRICE_ID,stripePlanPriceIds:l(h.STRIPE_PLAN_PRICE_IDS),stripePortalConfigurationId:h.STRIPE_PORTAL_CONFIGURATION_ID,stripeTopupProductId:h.STRIPE_TOPUP_PRODUCT_ID,topupFeePercent:V("STUDIO_TOPUP_FEE_PERCENT",h.STUDIO_TOPUP_FEE_PERCENT,15,100),enableDecoImport:k(h.ENABLE_DECO_IMPORT),hostingControlPlaneGa:k(h.HOSTING_CONTROL_PLANE_GA),monitorGa:k(h.MONITOR_GA),plansEnabled:k(h.STUDIO_PLANS_ENABLED),mcpCacheEnabled:U(h.MCP_CACHE_ENABLED,f!=="development"),mcpInternalHostMap:n(h.MCP_INTERNAL_HOST_MAP),orgFsPublicSetsJson:h.ORGFS_PUBLIC_SETS,orgFsMountsDisabled:k(h.DISABLE_ORGFS_MOUNTS),decopilotMaxConcurrentSubagents:z("DECOPILOT_MAX_CONCURRENT_SUBAGENTS",h.DECOPILOT_MAX_CONCURRENT_SUBAGENTS,4),decopilotMaxConcurrentHostedRuns:z("DECOPILOT_MAX_CONCURRENT_HOSTED_RUNS",h.DECOPILOT_MAX_CONCURRENT_HOSTED_RUNS,3),taskBoardReviewSweeperEnabled:U(h.TASK_BOARD_REVIEW_SWEEPER_ENABLED,!0),boardTransitionSettleSeconds:z("BOARD_TRANSITION_SETTLE_SECONDS",h.BOARD_TRANSITION_SETTLE_SECONDS,20,3600),decofileCommitGapSeconds:z("DECOFILE_COMMIT_GAP_SECONDS",h.DECOFILE_COMMIT_GAP_SECONDS,5,60),sandboxMaxConcurrentHostedRuns:z("SANDBOX_MAX_CONCURRENT_HOSTED_RUNS",h.SANDBOX_MAX_CONCURRENT_HOSTED_RUNS,12),s3Endpoint:h.S3_ENDPOINT,s3Bucket:h.S3_BUCKET,s3Region:h.S3_REGION||"auto",s3AccessKeyId:h.S3_ACCESS_KEY_ID,s3SecretAccessKey:h.S3_SECRET_ACCESS_KEY,s3ForcePathStyle:r(h.S3_FORCE_PATH_STYLE),monitoringS3Bucket:h.MONITORING_S3_BUCKET,monitoringS3Endpoint:h.MONITORING_S3_ENDPOINT,monitoringS3Region:h.MONITORING_S3_REGION,monitoringS3AccessKeyId:h.MONITORING_S3_ACCESS_KEY_ID,monitoringS3SecretAccessKey:h.MONITORING_S3_SECRET_ACCESS_KEY,monitoringS3Prefix:h.MONITORING_S3_PREFIX,duckdbExtensionDirectory:h.DUCKDB_EXTENSION_DIRECTORY||"/opt/duckdb/extensions",duckdbMemoryLimit:h.DUCKDB_MEMORY_LIMIT||void 0,duckdbThreads:X("DUCKDB_THREADS",h.DUCKDB_THREADS),podName:h.POD_NAME||crypto.randomUUID(),dispatchRole:p(m(h.STUDIO_DISPATCH_ROLE,h.MESH_DISPATCH_ROLE)),agentSandboxEnabled:k(h.STUDIO_AGENT_SANDBOX_ENABLED),sandboxStickyHeadRefEnabled:k(h.SANDBOX_STICKY_HEAD_REF),taskBoardRerunReusesPrBranch:U(h.TASK_BOARD_RERUN_REUSES_PR_BRANCH,!0),sandboxReleaseOnRunEndEnabled:k(h.SANDBOX_RELEASE_ON_RUN_END),sandboxPrewarmOnThreadCreateEnabled:k(h.SANDBOX_PREWARM_ON_THREAD_CREATE),sandboxPersistentHarnessEnabled:k(h.SANDBOX_PERSISTENT_HARNESS),sandboxReleaseGraceMs:z("SANDBOX_RELEASE_GRACE_MS",h.SANDBOX_RELEASE_GRACE_MS,120000),decoSupabaseUrl:h.DECO_SUPABASE_URL,decoSupabaseServiceKey:h.DECO_SUPABASE_SERVICE_KEY,controlplaneRestUrl:h.CONTROLPLANE_REST_URL,controlplaneServiceToken:h.CONTROLPLANE_SERVICE_TOKEN,analyticsDataUrl:h.ANALYTICS_URL,analyticsMasterToken:h.ANALYTICS_MASTER_TOKEN,clickhouseAnalyticsUrl:h.CLICKHOUSE_ANALYTICS_ADDRESS,clickhouseAnalyticsUsername:h.CLICKHOUSE_ANALYTICS_USERNAME||"admin_monitor",clickhouseAnalyticsPassword:h.CLICKHOUSE_ANALYTICS_PASSWORD,customerLakeUrl:h.CUSTOMER_LAKE_URL,customerLakeAdminUsername:h.CUSTOMER_LAKE_ADMIN_USERNAME||"customer_lake_user_admin",customerLakeAdminPassword:h.CUSTOMER_LAKE_ADMIN_PASSWORD,customerLakeTenantSecret:h.CUSTOMER_LAKE_TENANT_SECRET,orderMonitorIngestUrl:h.ORDER_MONITOR_INGEST_URL,oneDollarStatsApiKey:h.ONEDOLLAR_BACKEND_API_KEY,reportsInternalApiUrl:m(h.REPORTS_INTERNAL_API_URL,h.COMMERCE_DISCOVERY_INTERNAL_API_URL),reportsInternalApiKey:m(h.REPORTS_INTERNAL_API_KEY,h.COMMERCE_DISCOVERY_INTERNAL_API_KEY),s3TenantBucket:h.S3_TENANT_BUCKET||"new-deco-sites-assets",s3TenantRegion:h.S3_TENANT_REGION||"us-west-2",s3TenantEndpoint:h.S3_TENANT_ENDPOINT,s3TenantPublicUrlBase:h.S3_TENANT_PUBLIC_URL_BASE||"https://assets.decocms.com",awsS3TenantRoleArn:h.AWS_S3_TENANT_ROLE_ARN,awsS3TenantProvisionerAccessKeyId:h.AWS_S3_TENANT_PROVISIONER_ACCESS_KEY_ID,awsS3TenantProvisionerSecretAccessKey:h.AWS_S3_TENANT_PROVISIONER_SECRET_ACCESS_KEY,deliveryR2AccountId:h.DELIVERY_R2_ACCOUNT_ID,deliveryR2AccessKeyId:h.DELIVERY_R2_ACCESS_KEY_ID,deliveryR2SecretAccessKey:h.DELIVERY_R2_SECRET_ACCESS_KEY,deliveryR2Bucket:h.DELIVERY_R2_BUCKET,deliveryR2Endpoint:h.DELIVERY_R2_ENDPOINT,deliveryPublicOrigin:h.DELIVERY_PUBLIC_ORIGIN,deliveryKeyPrefix:h.DELIVERY_KEY_PREFIX,siteTokenSigningKey:h.DECO_SITE_TOKEN_SIGNING_KEY,cfDeliveryZoneId:h.CF_DELIVERY_ZONE_ID,cfPurgeApiToken:h.CF_PURGE_API_TOKEN};if(Boolean(c.natsUser)!==Boolean(c.natsPassword))throw Error("NATS_USER and NATS_PASSWORD must be set together");if(c.natsCredsPath&&c.natsUser)throw Error("Use either NATS_CREDS or NATS_USER/NATS_PASSWORD");if(c.plansEnabled&&!c.studioJwtSecret)throw Error("STUDIO_PLANS_ENABLED requires an explicit gateway JWT secret. Set STUDIO_JWT_SECRET (or its legacy alias MESH_JWT_SECRET) to the same value as the gateway's MESH_JWT_SECRET. Refusing to fall back to BETTER_AUTH_SECRET: that mismatch 401s every entitlements call, which every feature gate reads as 'no answer' and fails OPEN.");if(c.plansEnabled&&!c.studioProvisionSecretKey)throw Error("STUDIO_PLANS_ENABLED requires STUDIO_PROVISION_SECRET_KEY, set to the same value as the gateway's STUDIO_PROVISION_KEY. Without it the gateway cannot identify this server, falls back to a per-user membership callback that 401s for any user who never completed the gateway OAuth flow, and every feature gate then fails OPEN.");if(c.plansEnabled&&!c.aiGatewayEnabled)throw Error("STUDIO_PLANS_ENABLED requires DECO_AI_GATEWAY_ENABLED=true. Plans are read from the gateway; with it disabled there is no adapter to ask, so every feature gate fails OPEN on both server and client and the paid product is free fleet-wide.");if(c.plansEnabled&&Object.keys(c.stripePlanPriceIds).length>0&&!c.aiGatewayAdminToken)throw Error("STRIPE_PLAN_PRICE_IDS is set but DECO_AI_GATEWAY_ADMIN_TOKEN is not. The Stripe webhook places the paid tier through the gateway's admin API, so without the token a customer is charged and the entitlement "+"is never granted \u2014 and AI_PLAN_SET cannot repair it, it accepts only "+"'free'.");if(c.plansEnabled&&Object.keys(c.stripePlanPriceIds).length>1&&!c.stripePortalConfigurationId)console.warn("STRIPE_PLAN_PRICE_IDS maps more than one plan but STRIPE_PORTAL_CONFIGURATION_ID is unset. An org that already has a subscription cannot change tier: the account's default portal configuration lists only the legacy plans, not the tiers, so Stripe refuses the update flow. First-time checkout is unaffected.");return c}var s=null;function D(){return s??=Object.freeze(q(process.env))}import{Kysely as gc,PostgresDialect as uc}from"kysely";import{Pool as pc}from"pg";import{createContextKey as ch,metrics as fh,propagation as Aw,ROOT_CONTEXT as pw,SpanStatusCode as Iw,trace as yh}from"@opentelemetry/api";import{logs as oh,SeverityNumber as K}from"@opentelemetry/api-logs";import{OTLPLogExporter as nw}from"@opentelemetry/exporter-logs-otlp-proto";import{PrometheusExporter as Jh}from"@opentelemetry/exporter-prometheus";import{OTLPTraceExporter as sw}from"@opentelemetry/exporter-trace-otlp-proto";import{RuntimeNodeInstrumentation as ew}from"@opentelemetry/instrumentation-runtime-node";import{context as Th,propagation as _h,SpanKind as Mh,SpanStatusCode as Ph}from"@opentelemetry/api";var uh=globalThis.fetch;import{ExportResultCode as ah}from"@opentelemetry/core";import{ExportResultCode as Z}from"@opentelemetry/core";import{mkdir as v,rename as e,writeFile as a}from"fs/promises";import{join as $}from"path";class F{bufferItems=[];bufferBytes=0;flushTimer=null;flushQueue=Promise.resolve();basePath;flushThreshold;maxBufferBytes;isShutdown=!1;knownDirs=new Set;partitionKey;constructor(h){this.basePath=h.basePath,this.flushThreshold=h.flushThreshold??1000,this.maxBufferBytes=h.maxBufferBytes??10485760,this.partitionKey=h.partitionKey;let w=h.flushIntervalMs??60000;if(w>0&&w<3600000){if(this.flushTimer=setInterval(()=>{this.flush().catch((f)=>{console.error("[NDJSONExporter] Timer flush failed:",f)})},w),this.flushTimer&&typeof this.flushTimer==="object"&&"unref"in this.flushTimer)this.flushTimer.unref()}}exportRows(h){if(this.isShutdown)return Promise.resolve({code:Z.FAILED});for(let w of h){let f=JSON.stringify(w),y=this.partitionKey?this.partitionKey(w):"";this.bufferItems.push({partition:y,json:f}),this.bufferBytes+=Buffer.byteLength(f,"utf8")+1}if(this.bufferItems.length>=this.flushThreshold||this.bufferBytes>=this.maxBufferBytes)return this.flush().then(()=>({code:Z.SUCCESS})).catch((w)=>{return console.error("[NDJSONExporter] Flush failed:",w),{code:Z.FAILED}});return Promise.resolve({code:Z.SUCCESS})}async shutdown(){if(this.isShutdown=!0,this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;try{await this.flushQueue}catch{}if(this.bufferItems.length>0)await this.flush()}async forceFlush(){try{await this.flushQueue}catch{}if(this.bufferItems.length>0)await this.flush()}flush(){let w=this.flushQueue.catch(()=>{}).then(()=>this.doFlush());return this.flushQueue=w,w}async doFlush(){if(this.bufferItems.length===0)return;let h=this.bufferItems;this.bufferItems=[],this.bufferBytes=0;let w=new Map;for(let c of h){let o=w.get(c.partition);if(!o)o=[],w.set(c.partition,o);o.push(c.json)}let f=await Promise.allSettled(Array.from(w.entries()).map(([c,o])=>this.writeNDJSON(o,c).then(()=>c))),y=f.find((c)=>c.status==="rejected");if(y){let c=new Set;for(let J of f)if(J.status==="fulfilled")c.add(J.value);let o=h.filter((J)=>!c.has(J.partition));this.bufferItems=o.concat(this.bufferItems),this.bufferBytes=0;for(let J of this.bufferItems)this.bufferBytes+=Buffer.byteLength(J.json,"utf8")+1;throw y.reason}}async writeNDJSON(h,w){let f=new Date,y=[String(f.getUTCFullYear()),String(f.getUTCMonth()+1).padStart(2,"0"),String(f.getUTCDate()).padStart(2,"0"),String(f.getUTCHours()).padStart(2,"0")],c=w?$(this.basePath,w,...y):$(this.basePath,...y);if(!this.knownDirs.has(c))await v(c,{recursive:!0,mode:448}),this.knownDirs.add(c);let o=`${crypto.randomUUID()}.ndjson`,J=$(c,`.${o}.tmp`),d=$(c,o),W=h.join(` `)+` `;await a(J,W,{mode:384}),await e(J,d)}}import{ExportResultCode as yw}from"@opentelemetry/core";import{AggregationTemporality as Jw,DataPointType as dw}from"@opentelemetry/sdk-metrics";import{ExportResultCode as Dw}from"@opentelemetry/core";var Qw=Buffer.byteLength("... [TRUNCATED]","utf8");import{BatchLogRecordProcessor as dc,LoggerProvider as kc}from"@opentelemetry/sdk-logs";import{detectResources as zc,envDetector as Nc,hostDetector as mc,osDetector as Dc,processDetector as Zc,resourceFromAttributes as $c}from"@opentelemetry/resources";import{PeriodicExportingMetricReader as Qc}from"@opentelemetry/sdk-metrics";import{NOOP_LOGGER as Xw}from"@opentelemetry/api-logs";import{NodeSDK as Xc}from"@opentelemetry/sdk-node";import{BatchSpanProcessor as Kc,SamplingDecision as N}from"@opentelemetry/sdk-trace-base";import{SpanStatusCode as Cw}from"@opentelemetry/api";var dh="__d",kh=ch("Current request"),Wh=1;var O=(h)=>{let f=new URL(h.url).searchParams.get(dh);if(f==="")return crypto.randomUUID();if(!f)f=h.headers.get("x-trace-debug-id");return f};class S{inner;constructor(h){this.inner=h}shouldSample(h,w,f,y,c,o){let J=h.getValue(kh);if(!J){if(this.inner)return this.inner.shouldSample(h,w,f,y,c,o);return{decision:N.RECORD_AND_SAMPLED}}let d=O(J);if(d)return{decision:N.RECORD_AND_SAMPLED,attributes:{"trace.debug.id":d}};if(this.inner){let W=this.inner.shouldSample(h,w,f,y,c,o);if(W.decision===N.RECORD_AND_SAMPLED){let H=crypto.randomUUID();W.attributes={...W.attributes??{},"trace.debug.id":H}}return W}return{decision:N.NOT_RECORD}}toString(){return"DebugSampler"}}class b{ratio;constructor(h){this.ratio=h}shouldSample(){if(Math.random()<this.ratio)return{decision:N.RECORD_AND_SAMPLED};return{decision:N.NOT_RECORD}}toString(){return`RatioSampler(${this.ratio})`}}var Bc=new Jh({preventServerStart:!0}),Cc=new S(new b(Wh));var L=yh.getTracer("studio","1.0.0"),Y=fh.getMeter("studio","1.0.0"),zh=oh.getLogger("studio","1.0.0"),x=(h,w,f)=>{let y={},c=f,o=f[f.length-1];if(o!==null&&typeof o==="object"&&!Array.isArray(o)&&!(o instanceof Error)&&Object.getPrototypeOf(o)===Object.prototype)y=o,c=f.slice(0,-1);let J=c.map((d)=>{if(d instanceof Error)return`${d.name}: ${d.message}`;if(typeof d==="object")try{return JSON.stringify(d)}catch{return"[Object]"}return String(d)}).join(" ");zh.emit({severityNumber:h,severityText:w,body:J,attributes:{"log.source":"console",...y}})},B={error:console.error.bind(console),warn:console.warn.bind(console),debug:console.debug.bind(console)};console.error=(...h)=>{x(K.ERROR,"ERROR",h),B.error(...h)};console.warn=(...h)=>{x(K.WARN,"WARN",h),B.warn(...h)};console.debug=(...h)=>{x(K.DEBUG,"DEBUG",h),B.debug(...h)};function C(h,w){if(!w)return h;let f=new URL(h);if(!f.searchParams.has("sslmode"))f.searchParams.set("sslmode","verify-full");return f.toString()}async function Nh(){let h=D(),{DBOS:w}=await import("@dbos-inc/dbos-sdk");w.setConfig(E({systemDatabaseUrl:C(h.databaseUrl,h.databasePgSsl),poolSize:h.dbosPoolSize,executorID:h.podName,listenQueues:[]})),await G({databaseUrl:C(h.databaseUrl,h.databasePgSsl)},async()=>{await w.launch(),await w.shutdown()})}if(import.meta.main)(async()=>{try{await Nh(),console.log("DBOS system-schema migrations completed."),process.exit(0)}catch(h){console.error("DBOS system-schema migration failed:",h),process.exit(1)}})();export{Nh as migrateDbos};