@mastra/deployer-sandbox 0.1.4-alpha.0 → 0.2.0

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/alias.ts","../src/engine.ts","../src/manifest.ts","../src/deployer.ts"],"sourcesContent":["import type { SandboxAliasOptions } from './types';\n\n/**\n * Upsert a Vercel Edge Config item so a stable key always points at the\n * current sandbox URL. Used for Tier 3 routing: apps read the key from Edge\n * Config (e.g. in middleware) instead of hardcoding the rotating sandbox URL.\n */\nexport async function updateEdgeConfigAlias(options: SandboxAliasOptions & { url: string }): Promise<void> {\n const { token, teamId } = options;\n if (!token) {\n throw new Error('Updating the Edge Config alias requires a Vercel API token. Pass `alias.token`.');\n }\n\n const endpoint = new URL(`https://api.vercel.com/v1/edge-config/${options.edgeConfigId}/items`);\n if (teamId) {\n endpoint.searchParams.set('teamId', teamId);\n }\n\n const res = await fetch(endpoint, {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n items: [{ operation: 'upsert', key: options.key, value: options.url }],\n }),\n // Bounded so a hung Vercel API request can't keep `mastra build` open\n // after the sandbox itself is already deployed.\n signal: AbortSignal.timeout(30_000),\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => '');\n throw new Error(`Failed to update Edge Config alias \"${options.key}\" (${res.status}): ${body}`);\n }\n}\n","import { execFile } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n INSTALL_MARKER,\n SERVER_LOGFILE,\n SERVER_PIDFILE,\n SERVER_SCRIPT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n runInSandbox,\n shellQuote,\n tailServerLog,\n waitForHealthy,\n} from './shared';\nimport type { DeployToSandboxOptions, SandboxDeployLogger, SandboxDeployment } from './types';\n\nconst execFileAsync = promisify(execFile);\n\nconst noopLogger: SandboxDeployLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/** Max shell-command payload per chunk for the base64 upload fallback. */\nconst UPLOAD_CHUNK_SIZE = 96_000;\n\n/**\n * Deploy a prebuilt Mastra server directory into any workspace sandbox that\n * supports networking. Provider-agnostic: only uses the core WorkspaceSandbox\n * contract (`executeCommand` + `networking`, with `writeFiles` / `processes`\n * as fast paths).\n */\nexport async function deployToSandbox(options: DeployToSandboxOptions): Promise<SandboxDeployment> {\n const {\n sandbox,\n dir,\n port = DEFAULT_PORT,\n env = {},\n studio = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n healthCheckIntervalMs = 1_000,\n installCommand = 'npm install --omit=dev',\n logger = noopLogger,\n } = options;\n\n if (!existsSync(join(dir, 'index.mjs'))) {\n throw new Error(`No index.mjs found in \"${dir}\" — did the build succeed?`);\n }\n\n // 1. Start (providers handle create-or-resume by identity, e.g. sandbox name).\n logger.info(`Starting ${sandbox.provider} sandbox...`);\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs), ` +\n `which is required for sandbox deploys.`,\n );\n }\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\n\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Default the remote dir to $HOME/mastra-app — home directories persist\n // across snapshot stop/resume (unlike /tmp), so wakes find the app intact.\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n\n const mergedEnv = { ...env };\n if (studio && mergedEnv.MASTRA_STUDIO_PATH === undefined) {\n mergedEnv.MASTRA_STUDIO_PATH = `${remoteDir}/studio`;\n }\n\n // 2. Upload the build output as a tarball and extract it in the sandbox.\n logger.info(`Uploading build output from ${dir}...`);\n const tarball = await createTarball(dir);\n logger.debug(`Tarball size: ${(tarball.length / 1024 / 1024).toFixed(2)} MB`);\n\n const remoteTarball = `${remoteDir}/.deploy.tgz`;\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await uploadFile(sandbox, remoteTarball, tarball);\n\n // Stop the previous server BEFORE extracting over the live directory so it\n // can never serve a mix of old and new files while the release lands.\n await killPreviousServer(sandbox, remoteDir);\n\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && tar -xzf .deploy.tgz && rm -f .deploy.tgz`, {\n timeout: 120_000,\n });\n\n // 3. Install dependencies, skipped when the install inputs (package.json,\n // bundled lockfiles, and the install command itself) are unchanged since\n // the last completed install.\n const installHash = await hashInstallInputs(dir, installCommand);\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const markerCheck = await runInSandbox(sandbox, `cat ${shellQuote(marker)} 2>/dev/null || true`, {\n allowFailure: true,\n });\n\n if (installHash && markerCheck.stdout.trim() === installHash) {\n logger.info('Dependencies unchanged — skipping install.');\n } else {\n logger.info(`Installing dependencies (${installCommand})...`);\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && ${installCommand}`, {\n timeout: 600_000,\n label: `install dependencies (${installCommand})`,\n });\n if (installHash) {\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(installHash)} > ${shellQuote(marker)}`);\n }\n }\n\n // 4. Write the launch script and start the new server (the previous one was\n // stopped before extraction).\n const launchScript = buildLaunchScript({ remoteDir, port, env: mergedEnv });\n await uploadFile(sandbox, `${remoteDir}/${SERVER_SCRIPT}`, Buffer.from(launchScript));\n await runInSandbox(sandbox, `chmod 700 ${shellQuote(`${remoteDir}/${SERVER_SCRIPT}`)}`);\n\n logger.info('Starting Mastra server...');\n await launchServer(sandbox, remoteDir);\n\n // 5. Wait for the server to answer on its public URL.\n const healthy = await waitForHealthy(url, {\n path: healthCheckPath,\n timeoutMs: healthCheckTimeoutMs,\n intervalMs: healthCheckIntervalMs,\n });\n if (!healthy) {\n const log = await tailServerLog(sandbox, remoteDir).catch(() => '');\n throw new Error(\n `Mastra server did not become healthy at ${url}${healthCheckPath} within ${healthCheckTimeoutMs}ms.` +\n (log ? `\\n\\nServer log:\\n${log}` : '\\n\\n(no server log output captured)'),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n\n return {\n url,\n sandboxId: info?.id ?? sandbox.id,\n expiresAt: info?.timeoutAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n logs: (lines?: number) => tailServerLog(sandbox, remoteDir, lines),\n };\n}\n\n/**\n * Build the POSIX launch script. Re-running the script restarts the server —\n * the wake path uses this after a snapshot resume (which restores the\n * filesystem but not processes).\n */\nexport function buildLaunchScript(opts: { remoteDir: string; port: number; env: Record<string, string> }): string {\n const lines = ['#!/bin/sh', `cd ${shellQuote(opts.remoteDir)}`];\n\n // MASTRA_AUTO_DETECT_URL so Studio connects to the sandbox's public URL\n // (same origin) instead of localhost:4111 — overridable. PORT and\n // MASTRA_HOST are applied AFTER custom env: networking (`getPortUrl`) and\n // health checks target the configured port, and the server must bind\n // 0.0.0.0 to be reachable through the public port proxy. Change the port\n // via the deploy `port` option, not env.\n const env: Record<string, string> = {\n MASTRA_AUTO_DETECT_URL: 'true',\n ...opts.env,\n PORT: String(opts.port),\n MASTRA_HOST: '0.0.0.0',\n };\n for (const [key, value] of Object.entries(env)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(`Invalid environment variable name: \"${key}\"`);\n }\n lines.push(`export ${key}=${shellQuote(value)}`);\n }\n\n lines.push(`echo $$ > ${shellQuote(SERVER_PIDFILE)}`);\n lines.push(`exec node index.mjs >> ${shellQuote(SERVER_LOGFILE)} 2>&1`);\n return lines.join('\\n') + '\\n';\n}\n\n/** Create a gzipped tarball of the directory contents (excluding node_modules). */\nasync function createTarball(dir: string): Promise<Buffer> {\n const tmp = await mkdtemp(join(tmpdir(), 'mastra-sandbox-'));\n const tarPath = join(tmp, 'deploy.tgz');\n try {\n await execFileAsync('tar', ['-czf', tarPath, '--exclude=node_modules', '-C', dir, '.']);\n return await readFile(tarPath);\n } finally {\n await rm(tmp, { recursive: true, force: true });\n }\n}\n\n/**\n * Upload a file into the sandbox. Uses the provider's native `writeFiles` fast\n * path when available, otherwise falls back to base64 chunks over\n * `executeCommand` — so `executeCommand` + `networking` is the minimum contract.\n */\nasync function uploadFile(sandbox: WorkspaceSandbox, remotePath: string, content: Buffer): Promise<void> {\n if (sandbox.writeFiles) {\n await sandbox.writeFiles([{ path: remotePath, content }]);\n return;\n }\n\n const b64 = content.toString('base64');\n const tmpPath = `${remotePath}.b64`;\n await runInSandbox(sandbox, `rm -f ${shellQuote(tmpPath)}`);\n for (let i = 0; i < b64.length; i += UPLOAD_CHUNK_SIZE) {\n const chunk = b64.slice(i, i + UPLOAD_CHUNK_SIZE);\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(chunk)} >> ${shellQuote(tmpPath)}`, {\n label: `upload chunk to ${remotePath}`,\n });\n }\n await runInSandbox(\n sandbox,\n `base64 -d ${shellQuote(tmpPath)} > ${shellQuote(remotePath)} && rm -f ${shellQuote(tmpPath)}`,\n { label: `decode upload at ${remotePath}` },\n );\n}\n\n/** Lockfiles that, when present in the build output, participate in the install-skip hash. */\nconst LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock'];\n\n/**\n * Hash everything that determines the outcome of a dependency install:\n * package.json, any bundled lockfile, and the install command itself. A\n * matching hash means the previous `node_modules` can be reused.\n */\nasync function hashInstallInputs(dir: string, installCommand: string): Promise<string | null> {\n const hash = createHash('sha256');\n try {\n hash.update(await readFile(join(dir, 'package.json')));\n } catch {\n return null;\n }\n for (const lockfile of LOCKFILES) {\n let content: Buffer;\n try {\n content = await readFile(join(dir, lockfile));\n } catch {\n // Lockfile not part of the build output.\n continue;\n }\n hash.update(lockfile).update(content);\n }\n hash.update(installCommand);\n return hash.digest('hex');\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { SandboxDeploymentManifest } from './types';\n\nexport const MANIFEST_FILENAME = 'sandbox-deployment.json';\n\n/** Write `sandbox-deployment.json` into the build output directory. */\nexport async function writeDeploymentManifest(outputDir: string, manifest: SandboxDeploymentManifest): Promise<void> {\n await writeFile(join(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 2));\n}\n\n/** Read `sandbox-deployment.json` from the build output directory, or null when absent. */\nexport async function readDeploymentManifest(outputDir: string): Promise<SandboxDeploymentManifest | null> {\n let raw: string;\n try {\n raw = await readFile(join(outputDir, MANIFEST_FILENAME), 'utf-8');\n } catch (error) {\n // Only \"no manifest\" maps to null — anything else (permissions, a\n // corrupted file, malformed JSON below) should surface, not be hidden.\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n return JSON.parse(raw) as SandboxDeploymentManifest;\n}\n","import { access } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra/esm';\nimport { updateEdgeConfigAlias } from './alias';\nimport { deployToSandbox } from './engine';\nimport { writeDeploymentManifest } from './manifest';\nimport { DEFAULT_PORT } from './shared';\nimport type { SandboxDeployerOptions } from './types';\n\n/**\n * Deploy a full Mastra server into any workspace sandbox that supports\n * networking (Vercel Sandbox, E2B, ...) and get a live public URL.\n *\n * Positioning: ephemeral environments — instant previews, PR/CI smoke deploys,\n * agent-built-app verification. Not production hosting.\n *\n * @example\n * ```typescript\n * import { SandboxDeployer } from '@mastra/deployer-sandbox';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * export const mastra = new Mastra({\n * deployer: new SandboxDeployer({\n * sandbox: new VercelSandbox({ sandboxName: 'my-preview', timeout: 3_600_000, ports: [4111] }),\n * }),\n * });\n * ```\n */\nexport class SandboxDeployer extends Deployer {\n /** Sandbox deploys are push-style: `mastra build` runs `deploy()` after bundling. */\n readonly deployOnBuild = true;\n readonly sandbox: WorkspaceSandbox;\n readonly port: number;\n readonly studio: boolean;\n /** Explicit remote dir, when configured. The engine defaults to `$HOME/mastra-app` inside the sandbox. */\n readonly remoteDir?: string;\n private readonly env: Record<string, string>;\n private readonly alias?: SandboxDeployerOptions['alias'];\n private readonly healthCheckTimeoutMs?: number;\n\n constructor(options: SandboxDeployerOptions) {\n super({ name: 'SANDBOX' });\n\n this.sandbox = options.sandbox;\n this.port = options.port ?? DEFAULT_PORT;\n this.studio = options.studio ?? true;\n this.remoteDir = options.remoteDir;\n this.env = options.env ?? {};\n this.alias = options.alias;\n this.healthCheckTimeoutMs = options.healthCheckTimeoutMs;\n }\n\n /**\n * Merge all existing env files instead of only the first one (base behavior).\n * Later files win in `loadEnvVars()`, so order least → most specific: a\n * `.env.local` written by `vercel env pull` shouldn't shadow the `.env` that\n * holds the app's own keys.\n */\n override async getEnvFiles(): Promise<string[]> {\n const candidates = ['.env', '.env.production', '.env.local'];\n const existing: string[] = [];\n for (const file of candidates) {\n try {\n await access(file);\n existing.push(file);\n } catch {\n // skip missing files\n }\n }\n return existing;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Dependencies are installed inside the sandbox, so keep them external.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n protected getEntry(): string {\n return `\n // @ts-expect-error\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n import { mastra } from '#mastra';\n import { createNodeServer, getToolExports } from '#server';\n import { tools } from '#tools';\n\n // @ts-expect-error\n await createNodeServer(mastra, { tools: getToolExports(tools), studio: ${this.studio} });\n\n const storage = mastra.getStorage();\n if (storage) {\n if (!storage.disableInit) {\n storage.init();\n }\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n `;\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioSource = join(dirname(__dirname), 'dist', 'studio');\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n\n try {\n await copy(studioSource, studioServePath, { overwrite: true });\n } catch (err) {\n throw new Error(\n `Failed to copy studio assets from \"${studioSource}\" to \"${studioServePath}\": ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot }, toolsPaths);\n }\n\n /**\n * Deploy the built output into the sandbox and wait for the server to come\n * up on its public URL. Writes `sandbox-deployment.json` into the output\n * directory and updates the Edge Config alias when configured.\n */\n async deploy(outputDirectory: string): Promise<void> {\n const dir = join(outputDirectory, this.outputDir);\n\n // Merge .env file vars under explicitly configured env.\n const envVars = await this.loadEnvVars();\n const env: Record<string, string> = { ...Object.fromEntries(envVars), ...this.env };\n if (envVars.size > 0) {\n this.logger.warn(\n 'Environment variables from your .env file are injected into the remote sandbox. ' +\n 'Anyone with access to the sandbox can read them.',\n );\n }\n\n const deployment = await deployToSandbox({\n sandbox: this.sandbox,\n dir,\n port: this.port,\n env,\n studio: this.studio,\n remoteDir: this.remoteDir,\n healthCheckTimeoutMs: this.healthCheckTimeoutMs,\n logger: this.logger,\n });\n\n await writeDeploymentManifest(dir, {\n provider: this.sandbox.provider,\n sandboxId: deployment.sandboxId,\n url: deployment.url,\n port: this.port,\n deployedAt: new Date().toISOString(),\n expiresAt: deployment.expiresAt?.toISOString(),\n });\n\n if (this.alias) {\n await updateEdgeConfigAlias({ ...this.alias, url: deployment.url });\n this.logger.info(`Edge Config alias \"${this.alias.key}\" now points at ${deployment.url}`);\n }\n\n this.logger.info(`Mastra server deployed: ${deployment.url}/api`);\n if (this.studio) {\n this.logger.info(`Studio: ${deployment.url}`);\n }\n if (deployment.expiresAt) {\n this.logger.warn(`Sandbox expires at ${deployment.expiresAt.toISOString()} (provider runtime cap).`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAOA,eAAsB,sBAAsB,SAA+D;CACzG,MAAM,EAAE,OAAO,WAAW;CAC1B,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,iFAAiF;CAGnG,MAAM,WAAW,IAAI,IAAI,yCAAyC,QAAQ,aAAa,OAAO;CAC9F,IAAI,QACF,SAAS,aAAa,IAAI,UAAU,MAAM;CAG5C,MAAM,MAAM,MAAM,MAAM,UAAU;EAChC,QAAQ;EACR,SAAS;GACP,eAAe,UAAU;GACzB,gBAAgB;EAClB;EACA,MAAM,KAAK,UAAU,EACnB,OAAO,CAAC;GAAE,WAAW;GAAU,KAAK,QAAQ;GAAK,OAAO,QAAQ;EAAI,CAAC,EACvE,CAAC;EAGD,QAAQ,YAAY,QAAQ,GAAM;CACpC,CAAC;CAED,IAAI,CAAC,IAAI,IAAI;EACX,MAAM,OAAO,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE;EAC5C,MAAM,IAAI,MAAM,uCAAuC,QAAQ,IAAI,KAAK,IAAI,OAAO,KAAK,MAAM;CAChG;AACF;;;ACVA,MAAM,gBAAgB,UAAU,QAAQ;AAExC,MAAM,aAAkC;CACt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GAAG,WAAW;GAAE;GAAiB;EAAY,GAAG,UAAU;CAC9F;;;;;;CAOA,MAAM,OAAO,iBAAwC;EACnD,MAAM,MAAM,KAAK,iBAAiB,KAAK,SAAS;EAGhD,MAAM,UAAU,MAAM,KAAK,YAAY;EACvC,MAAM,MAA8B;GAAE,GAAG,OAAO,YAAY,OAAO;GAAG,GAAG,KAAK;EAAI;EAClF,IAAI,QAAQ,OAAO,GACjB,KAAK,OAAO,KACV,kIAEF;EAGF,MAAM,aAAa,MAAM,gBAAgB;GACvC,SAAS,KAAK;GACd;GACA,MAAM,KAAK;GACX;GACA,QAAQ,KAAK;GACb,WAAW,KAAK;GAChB,sBAAsB,KAAK;GAC3B,QAAQ,KAAK;EACf,CAAC;EAED,MAAM,wBAAwB,KAAK;GACjC,UAAU,KAAK,QAAQ;GACvB,WAAW,WAAW;GACtB,KAAK,WAAW;GAChB,MAAM,KAAK;GACX,6BAAY,IAAI,KAAK,EAAA,CAAE,YAAY;GACnC,WAAW,WAAW,WAAW,YAAY;EAC/C,CAAC;EAED,IAAI,KAAK,OAAO;GACd,MAAM,sBAAsB;IAAE,GAAG,KAAK;IAAO,KAAK,WAAW;GAAI,CAAC;GAClE,KAAK,OAAO,KAAK,sBAAsB,KAAK,MAAM,IAAI,kBAAkB,WAAW,KAAK;EAC1F;EAEA,KAAK,OAAO,KAAK,2BAA2B,WAAW,IAAI,KAAK;EAChE,IAAI,KAAK,QACP,KAAK,OAAO,KAAK,WAAW,WAAW,KAAK;EAE9C,IAAI,WAAW,WACb,KAAK,OAAO,KAAK,sBAAsB,WAAW,UAAU,YAAY,EAAE,yBAAyB;CAEvG;AACF"}
1
+ {"version":3,"file":"index.js","names":["INSTALL_MARKER"],"sources":["../src/alias.ts","../src/engine.ts","../src/manifest.ts","../src/deployer.ts","../src/worker.ts"],"sourcesContent":["import type { SandboxAliasOptions } from './types';\n\n/**\n * Upsert a Vercel Edge Config item so a stable key always points at the\n * current sandbox URL. Used for Tier 3 routing: apps read the key from Edge\n * Config (e.g. in middleware) instead of hardcoding the rotating sandbox URL.\n */\nexport async function updateEdgeConfigAlias(options: SandboxAliasOptions & { url: string }): Promise<void> {\n const { token, teamId } = options;\n if (!token) {\n throw new Error('Updating the Edge Config alias requires a Vercel API token. Pass `alias.token`.');\n }\n\n const endpoint = new URL(`https://api.vercel.com/v1/edge-config/${options.edgeConfigId}/items`);\n if (teamId) {\n endpoint.searchParams.set('teamId', teamId);\n }\n\n const res = await fetch(endpoint, {\n method: 'PATCH',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n items: [{ operation: 'upsert', key: options.key, value: options.url }],\n }),\n // Bounded so a hung Vercel API request can't keep `mastra build` open\n // after the sandbox itself is already deployed.\n signal: AbortSignal.timeout(30_000),\n });\n\n if (!res.ok) {\n const body = await res.text().catch(() => '');\n throw new Error(`Failed to update Edge Config alias \"${options.key}\" (${res.status}): ${body}`);\n }\n}\n","import { execFile } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { supportsNetworking } from '@mastra/core/workspace';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport {\n DEFAULT_PORT,\n INSTALL_MARKER,\n SERVER_LOGFILE,\n SERVER_PIDFILE,\n SERVER_SCRIPT,\n getInfoSafe,\n killPreviousServer,\n launchServer,\n resolveRemoteDir,\n runInSandbox,\n shellQuote,\n tailServerLog,\n waitForHealthy,\n} from './shared';\nimport type { DeployToSandboxOptions, SandboxDeployLogger, SandboxDeployment } from './types';\n\nconst execFileAsync = promisify(execFile);\n\nconst noopLogger: SandboxDeployLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/** Max shell-command payload per chunk for the base64 upload fallback. */\nconst UPLOAD_CHUNK_SIZE = 96_000;\n\n/**\n * Deploy a prebuilt Mastra server directory into any workspace sandbox that\n * supports networking. Provider-agnostic: only uses the core WorkspaceSandbox\n * contract (`executeCommand` + `networking`, with `writeFiles` / `processes`\n * as fast paths).\n */\nexport async function deployToSandbox(options: DeployToSandboxOptions): Promise<SandboxDeployment> {\n const {\n sandbox,\n dir,\n port = DEFAULT_PORT,\n env = {},\n studio = false,\n healthCheckPath = '/api',\n healthCheckTimeoutMs = 60_000,\n healthCheckIntervalMs = 1_000,\n installCommand = 'npm install --omit=dev',\n logger = noopLogger,\n } = options;\n\n if (!existsSync(join(dir, 'index.mjs'))) {\n throw new Error(`No index.mjs found in \"${dir}\" — did the build succeed?`);\n }\n\n // 1. Start (providers handle create-or-resume by identity, e.g. sandbox name).\n logger.info(`Starting ${sandbox.provider} sandbox...`);\n await sandbox.start?.();\n\n if (!supportsNetworking(sandbox)) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support networking (public port URLs), ` +\n `which is required for sandbox deploys.`,\n );\n }\n if (!sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" does not support executeCommand, which is required for sandbox deploys.`,\n );\n }\n\n const url = await sandbox.networking.getPortUrl(port);\n if (!url) {\n throw new Error(\n `Sandbox provider \"${sandbox.provider}\" did not expose a public URL for port ${port}. ` +\n `Make sure the port is declared when constructing the sandbox (e.g. \\`ports: [${port}]\\`).`,\n );\n }\n\n // Default the remote dir to $HOME/mastra-app — home directories persist\n // across snapshot stop/resume (unlike /tmp), so wakes find the app intact.\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n\n const mergedEnv = { ...env };\n if (studio && mergedEnv.MASTRA_STUDIO_PATH === undefined) {\n mergedEnv.MASTRA_STUDIO_PATH = `${remoteDir}/studio`;\n }\n\n // 2. Upload the build output as a tarball and extract it in the sandbox.\n logger.info(`Uploading build output from ${dir}...`);\n const tarball = await createTarball(dir);\n logger.debug(`Tarball size: ${(tarball.length / 1024 / 1024).toFixed(2)} MB`);\n\n const remoteTarball = `${remoteDir}/.deploy.tgz`;\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await uploadFile(sandbox, remoteTarball, tarball);\n\n // Stop the previous server BEFORE extracting over the live directory so it\n // can never serve a mix of old and new files while the release lands.\n await killPreviousServer(sandbox, remoteDir);\n\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && tar -xzf .deploy.tgz && rm -f .deploy.tgz`, {\n timeout: 120_000,\n });\n\n // 3. Install dependencies, skipped when the install inputs (package.json,\n // bundled lockfiles, and the install command itself) are unchanged since\n // the last completed install.\n const installHash = await hashInstallInputs(dir, installCommand);\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const markerCheck = await runInSandbox(sandbox, `cat ${shellQuote(marker)} 2>/dev/null || true`, {\n allowFailure: true,\n });\n\n if (installHash && markerCheck.stdout.trim() === installHash) {\n logger.info('Dependencies unchanged — skipping install.');\n } else {\n logger.info(`Installing dependencies (${installCommand})...`);\n await runInSandbox(sandbox, `cd ${shellQuote(remoteDir)} && ${installCommand}`, {\n timeout: 600_000,\n label: `install dependencies (${installCommand})`,\n });\n if (installHash) {\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(installHash)} > ${shellQuote(marker)}`);\n }\n }\n\n // 4. Write the launch script and start the new server (the previous one was\n // stopped before extraction).\n const launchScript = buildLaunchScript({ remoteDir, port, env: mergedEnv });\n await uploadFile(sandbox, `${remoteDir}/${SERVER_SCRIPT}`, Buffer.from(launchScript));\n await runInSandbox(sandbox, `chmod 700 ${shellQuote(`${remoteDir}/${SERVER_SCRIPT}`)}`);\n\n logger.info('Starting Mastra server...');\n await launchServer(sandbox, remoteDir);\n\n // 5. Wait for the server to answer on its public URL.\n const healthy = await waitForHealthy(url, {\n path: healthCheckPath,\n timeoutMs: healthCheckTimeoutMs,\n intervalMs: healthCheckIntervalMs,\n });\n if (!healthy) {\n const log = await tailServerLog(sandbox, remoteDir).catch(() => '');\n throw new Error(\n `Mastra server did not become healthy at ${url}${healthCheckPath} within ${healthCheckTimeoutMs}ms.` +\n (log ? `\\n\\nServer log:\\n${log}` : '\\n\\n(no server log output captured)'),\n );\n }\n\n const info = await getInfoSafe(sandbox);\n\n return {\n url,\n sandboxId: info?.id ?? sandbox.id,\n expiresAt: info?.timeoutAt,\n stop: async () => {\n await sandbox.stop?.();\n },\n destroy: async () => {\n await sandbox.destroy?.();\n },\n logs: (lines?: number) => tailServerLog(sandbox, remoteDir, lines),\n };\n}\n\n/**\n * Build the POSIX launch script. Re-running the script restarts the server —\n * the wake path uses this after a snapshot resume (which restores the\n * filesystem but not processes).\n */\nexport function buildLaunchScript(opts: { remoteDir: string; port: number; env: Record<string, string> }): string {\n const lines = ['#!/bin/sh', `cd ${shellQuote(opts.remoteDir)}`];\n\n // MASTRA_AUTO_DETECT_URL so Studio connects to the sandbox's public URL\n // (same origin) instead of localhost:4111 — overridable. PORT and\n // MASTRA_HOST are applied AFTER custom env: networking (`getPortUrl`) and\n // health checks target the configured port, and the server must bind\n // 0.0.0.0 to be reachable through the public port proxy. Change the port\n // via the deploy `port` option, not env.\n const env: Record<string, string> = {\n MASTRA_AUTO_DETECT_URL: 'true',\n ...opts.env,\n PORT: String(opts.port),\n MASTRA_HOST: '0.0.0.0',\n };\n for (const [key, value] of Object.entries(env)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(`Invalid environment variable name: \"${key}\"`);\n }\n lines.push(`export ${key}=${shellQuote(value)}`);\n }\n\n lines.push(`echo $$ > ${shellQuote(SERVER_PIDFILE)}`);\n lines.push(`exec node index.mjs >> ${shellQuote(SERVER_LOGFILE)} 2>&1`);\n return lines.join('\\n') + '\\n';\n}\n\n/** Create a gzipped tarball of the directory contents (excluding node_modules). */\nexport async function createTarball(dir: string): Promise<Buffer> {\n const tmp = await mkdtemp(join(tmpdir(), 'mastra-sandbox-'));\n const tarPath = join(tmp, 'deploy.tgz');\n try {\n await execFileAsync('tar', ['-czf', tarPath, '--exclude=node_modules', '-C', dir, '.']);\n return await readFile(tarPath);\n } finally {\n await rm(tmp, { recursive: true, force: true });\n }\n}\n\n/**\n * Upload a file into the sandbox. Uses the provider's native `writeFiles` fast\n * path when available, otherwise falls back to base64 chunks over\n * `executeCommand` — so `executeCommand` + `networking` is the minimum contract.\n */\nexport async function uploadFile(sandbox: WorkspaceSandbox, remotePath: string, content: Buffer): Promise<void> {\n if (sandbox.writeFiles) {\n await sandbox.writeFiles([{ path: remotePath, content }]);\n return;\n }\n\n const b64 = content.toString('base64');\n const tmpPath = `${remotePath}.b64`;\n await runInSandbox(sandbox, `rm -f ${shellQuote(tmpPath)}`);\n for (let i = 0; i < b64.length; i += UPLOAD_CHUNK_SIZE) {\n const chunk = b64.slice(i, i + UPLOAD_CHUNK_SIZE);\n await runInSandbox(sandbox, `printf '%s' ${shellQuote(chunk)} >> ${shellQuote(tmpPath)}`, {\n label: `upload chunk to ${remotePath}`,\n });\n }\n await runInSandbox(\n sandbox,\n `base64 -d ${shellQuote(tmpPath)} > ${shellQuote(remotePath)} && rm -f ${shellQuote(tmpPath)}`,\n { label: `decode upload at ${remotePath}` },\n );\n}\n\n/** Lockfiles that, when present in the build output, participate in the install-skip hash. */\nconst LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock'];\n\n/**\n * Hash everything that determines the outcome of a dependency install:\n * package.json, any bundled lockfile, and the install command itself. A\n * matching hash means the previous `node_modules` can be reused.\n */\nexport async function hashInstallInputs(dir: string, installCommand: string): Promise<string | null> {\n const hash = createHash('sha256');\n try {\n hash.update(await readFile(join(dir, 'package.json')));\n } catch {\n return null;\n }\n for (const lockfile of LOCKFILES) {\n let content: Buffer;\n try {\n content = await readFile(join(dir, lockfile));\n } catch {\n // Lockfile not part of the build output.\n continue;\n }\n hash.update(lockfile).update(content);\n }\n hash.update(installCommand);\n return hash.digest('hex');\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { SandboxDeploymentManifest } from './types';\n\nexport const MANIFEST_FILENAME = 'sandbox-deployment.json';\n\n/** Write `sandbox-deployment.json` into the build output directory. */\nexport async function writeDeploymentManifest(outputDir: string, manifest: SandboxDeploymentManifest): Promise<void> {\n await writeFile(join(outputDir, MANIFEST_FILENAME), JSON.stringify(manifest, null, 2));\n}\n\n/** Read `sandbox-deployment.json` from the build output directory, or null when absent. */\nexport async function readDeploymentManifest(outputDir: string): Promise<SandboxDeploymentManifest | null> {\n let raw: string;\n try {\n raw = await readFile(join(outputDir, MANIFEST_FILENAME), 'utf-8');\n } catch (error) {\n // Only \"no manifest\" maps to null — anything else (permissions, a\n // corrupted file, malformed JSON below) should surface, not be hidden.\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n return JSON.parse(raw) as SandboxDeploymentManifest;\n}\n","import { access } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { Deployer } from '@mastra/deployer';\nimport { copy } from 'fs-extra/esm';\nimport { updateEdgeConfigAlias } from './alias';\nimport { deployToSandbox } from './engine';\nimport { writeDeploymentManifest } from './manifest';\nimport { DEFAULT_PORT } from './shared';\nimport type { SandboxDeployerOptions } from './types';\n\n/**\n * Deploy a full Mastra server into any workspace sandbox that supports\n * networking (Vercel Sandbox, E2B, ...) and get a live public URL.\n *\n * Positioning: ephemeral environments — instant previews, PR/CI smoke deploys,\n * agent-built-app verification. Not production hosting.\n *\n * @example\n * ```typescript\n * import { SandboxDeployer } from '@mastra/deployer-sandbox';\n * import { VercelSandbox } from '@mastra/vercel';\n *\n * export const mastra = new Mastra({\n * deployer: new SandboxDeployer({\n * sandbox: new VercelSandbox({ sandboxName: 'my-preview', timeout: 3_600_000, ports: [4111] }),\n * }),\n * });\n * ```\n */\nexport class SandboxDeployer extends Deployer {\n /** Sandbox deploys are push-style: `mastra build` runs `deploy()` after bundling. */\n readonly deployOnBuild = true;\n readonly sandbox: WorkspaceSandbox;\n readonly port: number;\n readonly studio: boolean;\n /** Explicit remote dir, when configured. The engine defaults to `$HOME/mastra-app` inside the sandbox. */\n readonly remoteDir?: string;\n private readonly env: Record<string, string>;\n private readonly alias?: SandboxDeployerOptions['alias'];\n private readonly healthCheckTimeoutMs?: number;\n\n constructor(options: SandboxDeployerOptions) {\n super({ name: 'SANDBOX' });\n\n this.sandbox = options.sandbox;\n this.port = options.port ?? DEFAULT_PORT;\n this.studio = options.studio ?? true;\n this.remoteDir = options.remoteDir;\n this.env = options.env ?? {};\n this.alias = options.alias;\n this.healthCheckTimeoutMs = options.healthCheckTimeoutMs;\n }\n\n /**\n * Merge all existing env files instead of only the first one (base behavior).\n * Later files win in `loadEnvVars()`, so order least → most specific: a\n * `.env.local` written by `vercel env pull` shouldn't shadow the `.env` that\n * holds the app's own keys.\n */\n override async getEnvFiles(): Promise<string[]> {\n const candidates = ['.env', '.env.production', '.env.local'];\n const existing: string[] = [];\n for (const file of candidates) {\n try {\n await access(file);\n existing.push(file);\n } catch {\n // skip missing files\n }\n }\n return existing;\n }\n\n protected async getUserBundlerOptions(\n mastraEntryFile: string,\n outputDirectory: string,\n ): Promise<NonNullable<Config['bundler']>> {\n const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n // Dependencies are installed inside the sandbox, so keep them external.\n return {\n ...bundlerOptions,\n externals: true,\n };\n }\n\n protected getEntry(): string {\n return `\n // @ts-expect-error\n import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n import { mastra } from '#mastra';\n import { createNodeServer, getToolExports } from '#server';\n import { tools } from '#tools';\n\n // @ts-expect-error\n await createNodeServer(mastra, { tools: getToolExports(tools), studio: ${this.studio} });\n\n const storage = mastra.getStorage();\n if (storage) {\n if (!storage.disableInit) {\n storage.init();\n }\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n `;\n }\n\n async prepare(outputDirectory: string): Promise<void> {\n await super.prepare(outputDirectory);\n\n if (this.studio) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const studioSource = join(dirname(__dirname), 'dist', 'studio');\n const studioServePath = join(outputDirectory, this.outputDir, 'studio');\n\n try {\n await copy(studioSource, studioServePath, { overwrite: true });\n } catch (err) {\n throw new Error(\n `Failed to copy studio assets from \"${studioSource}\" to \"${studioServePath}\": ${err instanceof Error ? err.message : err}`,\n );\n }\n }\n }\n\n async bundle(\n entryFile: string,\n outputDirectory: string,\n { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n ): Promise<void> {\n return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot }, toolsPaths);\n }\n\n /**\n * Deploy the built output into the sandbox and wait for the server to come\n * up on its public URL. Writes `sandbox-deployment.json` into the output\n * directory and updates the Edge Config alias when configured.\n */\n async deploy(outputDirectory: string): Promise<void> {\n const dir = join(outputDirectory, this.outputDir);\n\n // Merge .env file vars under explicitly configured env.\n const envVars = await this.loadEnvVars();\n const env: Record<string, string> = { ...Object.fromEntries(envVars), ...this.env };\n if (envVars.size > 0) {\n this.logger.warn(\n 'Environment variables from your .env file are injected into the remote sandbox. ' +\n 'Anyone with access to the sandbox can read them.',\n );\n }\n\n const deployment = await deployToSandbox({\n sandbox: this.sandbox,\n dir,\n port: this.port,\n env,\n studio: this.studio,\n remoteDir: this.remoteDir,\n healthCheckTimeoutMs: this.healthCheckTimeoutMs,\n logger: this.logger,\n });\n\n await writeDeploymentManifest(dir, {\n provider: this.sandbox.provider,\n sandboxId: deployment.sandboxId,\n url: deployment.url,\n port: this.port,\n deployedAt: new Date().toISOString(),\n expiresAt: deployment.expiresAt?.toISOString(),\n });\n\n if (this.alias) {\n await updateEdgeConfigAlias({ ...this.alias, url: deployment.url });\n this.logger.info(`Edge Config alias \"${this.alias.key}\" now points at ${deployment.url}`);\n }\n\n this.logger.info(`Mastra server deployed: ${deployment.url}/api`);\n if (this.studio) {\n this.logger.info(`Studio: ${deployment.url}`);\n }\n if (deployment.expiresAt) {\n this.logger.warn(`Sandbox expires at ${deployment.expiresAt.toISOString()} (provider runtime cap).`);\n }\n }\n}\n","import { posix } from 'node:path';\n\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\n\nimport { createTarball, hashInstallInputs, uploadFile } from './engine.js';\nimport { getInfoSafe, resolveRemoteDir, runInSandbox, shellQuote } from './shared.js';\nimport type {\n DeployWorkerToSandboxOptions,\n SandboxDestroyResult,\n SandboxWorkerDeployment,\n SandboxWorkerInput,\n SandboxWorkerOutput,\n SandboxWorkerStatus,\n} from './types.js';\n\nconst ARCHIVE = '.mastra-worker.tar.gz';\nconst RUNTIME_DIR = '.mastra/executions';\nconst INSTALL_MARKER = '.mastra-install-hash';\nconst INSTALL_LOCK = '.mastra-install-lock';\nconst ARTIFACT_LOCK = '.mastra-artifact-lock';\nconst EXECUTION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nconst DEFAULT_INPUT_LIMIT = 16 * 1024 * 1024;\nconst DEFAULT_OUTPUT_READ_LIMIT = 1024 * 1024;\n\ninterface WorkerConfig {\n sandbox: WorkspaceSandbox;\n remoteDir: string;\n command: string;\n args: string[];\n env: Record<string, string>;\n workingDirectory: string;\n mode: 'worker' | 'job';\n startupTimeoutMs: number;\n executionTimeoutMs?: number;\n terminationGraceMs: number;\n inputLimitBytes: number;\n}\n\nexport async function deployWorkerToSandbox(options: DeployWorkerToSandboxOptions): Promise<SandboxWorkerDeployment> {\n validateOptions(options);\n const {\n sandbox,\n dir,\n executionId,\n command,\n mode = 'worker',\n args = [],\n env = {},\n workingDirectory = '.',\n installCommand = 'npm install --omit=dev',\n startupTimeoutMs = 10_000,\n executionTimeoutMs,\n terminationGraceMs = 5_000,\n inputLimitBytes = DEFAULT_INPUT_LIMIT,\n } = options;\n\n const remoteDir = await resolveRemoteDir(sandbox, options.remoteDir);\n const config: WorkerConfig = {\n sandbox,\n remoteDir,\n command,\n args,\n env,\n workingDirectory,\n mode,\n startupTimeoutMs,\n executionTimeoutMs,\n terminationGraceMs,\n inputLimitBytes,\n };\n\n const archive = `${remoteDir}/${ARCHIVE}`;\n const tarball = await createTarball(dir);\n const installHash = await hashInstallInputs(dir, installCommand);\n\n const artifactLock = `${remoteDir}/${ARTIFACT_LOCK}`;\n let artifactLockAcquired = false;\n try {\n await runInSandbox(sandbox, `mkdir -p ${shellQuote(remoteDir)}`);\n await acquireLock(sandbox, artifactLock, options.installTimeoutMs, 'worker artifact');\n artifactLockAcquired = true;\n await uploadFile(sandbox, archive, tarball);\n await runInSandbox(\n sandbox,\n `tar -xzf ${shellQuote(archive)} -C ${shellQuote(remoteDir)} && rm -f ${shellQuote(archive)}`,\n { label: 'extract worker artifact' },\n );\n } catch (error) {\n throw workerPhaseError('upload', error);\n } finally {\n if (artifactLockAcquired) {\n await runInSandbox(sandbox, `rm -rf ${shellQuote(artifactLock)}`, {\n allowFailure: true,\n label: 'release worker artifact lock',\n });\n }\n }\n\n try {\n await installDependencies(sandbox, remoteDir, installHash ?? undefined, installCommand, options.installTimeoutMs);\n } catch (error) {\n throw workerPhaseError('install', error);\n }\n\n return createExecution(config, executionId, options.input);\n}\n\nfunction validateOptions(options: DeployWorkerToSandboxOptions): void {\n if (!options.sandbox.executeCommand) {\n throw new Error(\n `Sandbox provider \"${options.sandbox.provider}\" does not support executeCommand, which is required for worker deploys.`,\n );\n }\n validateExecutionId(options.executionId);\n if (!options.command || /[\\0\\r\\n]/.test(options.command)) {\n throw new Error('Worker command must be a non-empty executable path.');\n }\n if (options.args?.some(arg => arg.includes('\\0'))) throw new Error('Worker arguments must not contain NUL bytes.');\n for (const key of Object.keys(options.env ?? {})) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error(`Invalid worker environment variable name: ${key}`);\n }\n validateRelativePath(options.workingDirectory ?? '.', 'workingDirectory');\n validateInput(options.input);\n for (const [name, value] of [\n ['inputLimitBytes', options.inputLimitBytes],\n ['startupTimeoutMs', options.startupTimeoutMs],\n ['executionTimeoutMs', options.executionTimeoutMs],\n ['terminationGraceMs', options.terminationGraceMs],\n ] as const) {\n if (value !== undefined && (!Number.isFinite(value) || value <= 0))\n throw new Error(`${name} must be greater than zero.`);\n }\n}\n\nfunction validateRelativePath(value: string, label: string): void {\n if (!value || posix.isAbsolute(value) || posix.normalize(value).startsWith('..')) {\n throw new Error(`Worker ${label} must stay within the deployed artifact root.`);\n }\n}\n\nfunction validateInput(input: SandboxWorkerInput | undefined): void {\n if (input?.type === 'file') validateRelativePath(input.path, 'input file path');\n}\n\nasync function acquireLock(\n sandbox: WorkspaceSandbox,\n lock: string,\n timeout: number | undefined,\n label: string,\n): Promise<void> {\n const timeoutMs = timeout ?? 600_000;\n const attempts = Math.max(1, Math.ceil(timeoutMs / 1000));\n await runInSandbox(\n sandbox,\n [\n 'i=0',\n `while ! mkdir ${shellQuote(lock)} 2>/dev/null; do`,\n ` if [ \"$i\" -ge ${attempts} ]; then echo ${shellQuote(`${label} lock timeout`)} >&2; exit 1; fi`,\n ' sleep 1; i=$((i + 1))',\n 'done',\n ].join('\\n'),\n { timeout: timeoutMs, label: `acquire ${label} lock` },\n );\n}\n\nasync function installDependencies(\n sandbox: WorkspaceSandbox,\n remoteDir: string,\n installHash: string | undefined,\n installCommand: string,\n timeout?: number,\n): Promise<void> {\n if (!installHash) return;\n const marker = `${remoteDir}/${INSTALL_MARKER}`;\n const lock = `${remoteDir}/${INSTALL_LOCK}`;\n await acquireLock(sandbox, lock, timeout, 'dependency install');\n try {\n const script = [\n `current=\"$(cat ${shellQuote(marker)} 2>/dev/null || true)\"`,\n `if [ \"$current\" != ${shellQuote(installHash)} ]; then`,\n ` cd ${shellQuote(remoteDir)} && ${installCommand}`,\n ` printf %s ${shellQuote(installHash)} > ${shellQuote(`${marker}.tmp`)}`,\n ` mv ${shellQuote(`${marker}.tmp`)} ${shellQuote(marker)}`,\n 'fi',\n ].join('\\n');\n await runInSandbox(sandbox, script, {\n timeout: timeout ?? 600_000,\n label: 'install worker dependencies',\n });\n } finally {\n await runInSandbox(sandbox, `rm -rf ${shellQuote(lock)}`, {\n allowFailure: true,\n label: 'release dependency install lock',\n });\n }\n}\n\nasync function createExecution(\n config: WorkerConfig,\n executionId: string,\n input?: SandboxWorkerInput,\n): Promise<SandboxWorkerDeployment> {\n validateExecutionId(executionId);\n const paths = executionPaths(config.remoteDir, executionId);\n await runInSandbox(\n config.sandbox,\n `mkdir -p ${shellQuote(`${config.remoteDir}/${RUNTIME_DIR}`)} && mkdir -m 700 ${shellQuote(paths.dir)}`,\n { label: 'create worker execution namespace' },\n );\n const stdinPath = await stageInput(config, paths, input);\n const script = buildExecutionScript(config, paths, stdinPath);\n await uploadFile(config.sandbox, paths.script, Buffer.from(script));\n await runInSandbox(config.sandbox, `chmod 700 ${shellQuote(paths.script)}`);\n\n try {\n await launchExecution(config.sandbox, paths);\n } catch (error) {\n await writeFailedStatus(config.sandbox, paths, executionId, 'launch', error);\n throw workerPhaseError('launch', error);\n }\n\n const startup = await waitForStartup(config, executionId, paths);\n if (startup.state === 'timed_out') await cancelExecution(config, executionId, paths, 'startup');\n if (startup.state === 'failed' || startup.state === 'timed_out' || startup.state === 'provider_unavailable') {\n throw new Error(\n `Worker ${startup.state} during startup${'message' in startup && startup.message ? `: ${startup.message}` : ''}.`,\n );\n }\n\n const info = await getInfoSafe(config.sandbox);\n return deployment(config, executionId, paths, info?.id ?? config.sandbox.id ?? 'unknown', info?.timeoutAt);\n}\n\nfunction deployment(\n config: WorkerConfig,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n sandboxId: string,\n expiresAt?: Date,\n): SandboxWorkerDeployment {\n return {\n sandboxId,\n executionId,\n expiresAt,\n status: options => readWorkerStatus(config.sandbox, executionId, paths, options),\n readOutput: (stream, options) => readOutput(config.sandbox, executionId, paths, stream, options),\n cancel: () => cancelExecution(config, executionId, paths),\n stop: async () => {\n if (!config.sandbox.stop) throw new Error(`Sandbox provider \"${config.sandbox.provider}\" does not support stop.`);\n await config.sandbox.stop();\n },\n destroy: options => destroyWithRetry(config.sandbox, options),\n relaunch: async options => {\n if (options.executionId === executionId) throw new Error('Relaunch requires a new executionId.');\n validateInput(options.input);\n return createExecution(config, options.executionId, options.input);\n },\n };\n}\n\nasync function stageInput(\n config: WorkerConfig,\n paths: ReturnType<typeof executionPaths>,\n input?: SandboxWorkerInput,\n): Promise<string | undefined> {\n if (!input) return undefined;\n const data = typeof input.data === 'string' ? Buffer.from(input.data) : Buffer.from(input.data);\n if (data.byteLength > config.inputLimitBytes) {\n throw new Error(`Worker input exceeds inputLimitBytes (${data.byteLength} > ${config.inputLimitBytes}).`);\n }\n const path = input.type === 'stdin' ? paths.stdin : posix.resolve(config.remoteDir, input.path);\n await uploadFile(config.sandbox, path, data);\n await runInSandbox(config.sandbox, `chmod 600 ${shellQuote(path)}`);\n return input.type === 'stdin' ? path : undefined;\n}\n\nfunction buildExecutionScript(\n config: WorkerConfig,\n paths: ReturnType<typeof executionPaths>,\n stdinPath?: string,\n): string {\n const cwd = posix.resolve(config.remoteDir, config.workingDirectory);\n const envPrefix = Object.entries(config.env)\n .map(([key, value]) => `${key}=${shellQuote(value)}`)\n .join(' ');\n const executable = [shellQuote(config.command), ...config.args.map(shellQuote)].join(' ');\n const target = `${envPrefix ? `env ${envPrefix} ` : ''}${executable}`;\n const graceAttempts = Math.max(1, Math.ceil(config.terminationGraceMs / 1000));\n const state = (value: string) =>\n `tmp=${shellQuote(`${paths.status}.tmp.$$`)}; printf '%s\\\\n' ${shellQuote(value)} > \"$tmp\"; mv \"$tmp\" ${shellQuote(paths.status)};`;\n\n return [\n '#!/bin/sh',\n `cd ${shellQuote(cwd)}`,\n `execution_id=${shellQuote(paths.executionId)}`,\n `stdout=${shellQuote(paths.stdout)}`,\n `stderr=${shellQuote(paths.stderr)}`,\n `pidfile=${shellQuote(paths.pid)}`,\n `tokenfile=${shellQuote(paths.pidToken)}`,\n `: > \"$stdout\"; : > \"$stderr\"`,\n state(`starting|${paths.executionId}`),\n `setsid sh -c ${shellQuote(`exec ${target}${stdinPath ? ` < ${shellQuote(stdinPath)}` : ''}`)} > \"$stdout\" 2> \"$stderr\" &`,\n 'child=$!',\n 'printf %s \"$child\" > \"$pidfile\"',\n `if [ -r \"/proc/$child/stat\" ]; then awk '{print $22}' \"/proc/$child/stat\" > \"$tokenfile\"; else : > \"$tokenfile\"; fi`,\n state(`running|${paths.executionId}`),\n 'cancelled=0',\n `trap 'cancelled=1; kill -TERM -\"$child\" 2>/dev/null || kill -TERM \"$child\" 2>/dev/null || true' TERM INT`,\n ...(config.executionTimeoutMs\n ? [\n `(sleep ${Math.max(1, Math.ceil(config.executionTimeoutMs / 1000))}; if kill -0 \"$child\" 2>/dev/null; then ${state(\n `timed_out|${paths.executionId}|execution`,\n )} kill -TERM -\"$child\" 2>/dev/null || kill -TERM \"$child\" 2>/dev/null || true; i=0; while kill -0 \"$child\" 2>/dev/null && [ \"$i\" -lt ${graceAttempts} ]; do sleep 1; i=$((i + 1)); done; kill -KILL -\"$child\" 2>/dev/null || kill -KILL \"$child\" 2>/dev/null || true; fi) &`,\n 'watchdog=$!',\n ]\n : []),\n 'wait \"$child\"',\n 'code=$?',\n ...(config.executionTimeoutMs ? ['kill \"$watchdog\" 2>/dev/null || true'] : []),\n `current=\"$(cat ${shellQuote(paths.status)} 2>/dev/null || true)\"`,\n `case \"$current\" in timed_out*) ;; *) if [ \"$cancelled\" -eq 1 ]; then ${state(\n `cancelled|${paths.executionId}|TERM`,\n )} else signal=''; if [ \"$code\" -gt 128 ]; then signal=\"SIG$((code - 128))\"; fi; tmp=${shellQuote(\n `${paths.status}.tmp.$$`,\n )}; printf 'exited|%s|%s|%s\\\\n' \"$execution_id\" \"$code\" \"$signal\" > \"$tmp\"; mv \"$tmp\" ${shellQuote(\n paths.status,\n )}; fi ;; esac`,\n 'rm -f \"$pidfile\" \"$tokenfile\"',\n 'exit \"$code\"',\n ].join('\\n');\n}\n\nasync function launchExecution(sandbox: WorkspaceSandbox, paths: ReturnType<typeof executionPaths>): Promise<void> {\n await runInSandbox(sandbox, `setsid nohup sh ${shellQuote(paths.script)} >/dev/null 2>&1 & echo $!`, {\n label: 'launch worker execution',\n });\n}\n\nasync function waitForStartup(\n config: WorkerConfig,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n): Promise<SandboxWorkerStatus> {\n const deadline = Date.now() + config.startupTimeoutMs;\n while (Date.now() < deadline) {\n const status = await readWorkerStatus(config.sandbox, executionId, paths);\n if (status.state !== 'unknown' && status.state !== 'starting') return status;\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n return { state: 'timed_out', executionId, phase: 'startup' };\n}\n\nasync function readWorkerStatus(\n sandbox: WorkspaceSandbox,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n options?: { wake?: boolean },\n): Promise<SandboxWorkerStatus> {\n const providerState = sandbox.status;\n if (providerState === 'destroyed' || providerState === 'destroying') {\n return { state: 'provider_unavailable', executionId, providerState };\n }\n if (providerState === 'stopped' || providerState === 'stopping') {\n if (!options?.wake || !sandbox.start) return { state: 'provider_unavailable', executionId, providerState };\n try {\n await sandbox.start();\n } catch (error) {\n return { state: 'provider_unavailable', executionId, providerState, message: errorMessage(error) };\n }\n }\n\n try {\n const result = await runInSandbox(\n sandbox,\n [\n `status=\"$(cat ${shellQuote(paths.status)} 2>/dev/null || true)\"`,\n `if [ -f ${shellQuote(paths.pid)} ]; then`,\n ` pid=\"$(cat ${shellQuote(paths.pid)})\"`,\n ` expected=\"$(cat ${shellQuote(paths.pidToken)} 2>/dev/null || true)\"`,\n ` actual=\"$(if [ -r \"/proc/$pid/stat\" ]; then awk '{print $22}' \"/proc/$pid/stat\"; fi)\"`,\n ` if kill -0 \"$pid\" 2>/dev/null && { [ -z \"$expected\" ] || [ \"$expected\" = \"$actual\" ]; }; then echo \"running|${executionId}\"; exit 0; fi`,\n ` if kill -0 \"$pid\" 2>/dev/null; then echo \"stale|${executionId}\"; exit 0; fi`,\n 'fi',\n `if [ -n \"$status\" ]; then printf '%s\\\\n' \"$status\"; else echo \"unknown|${executionId}\"; fi`,\n ].join('\\n'),\n { allowFailure: true, label: 'read worker status' },\n );\n if (result.exitCode !== 0) {\n return {\n state: 'provider_unavailable',\n executionId,\n providerState: sandbox.status,\n message: result.stderr || result.stdout || 'Sandbox status inspection failed.',\n };\n }\n return parseStatus(executionId, result.stdout.trim());\n } catch (error) {\n return { state: 'provider_unavailable', executionId, providerState: sandbox.status, message: errorMessage(error) };\n }\n}\n\nfunction parseStatus(executionId: string, value: string): SandboxWorkerStatus {\n const [state, recordedId, first, second] = value.split('|');\n if (recordedId !== executionId || state === 'stale') return { state: 'unknown', executionId };\n if (state === 'starting') return { state, executionId };\n if (state === 'running') return { state, executionId };\n if (state === 'exited') {\n const exitCode = Number(first);\n return Number.isInteger(exitCode)\n ? { state, executionId, exitCode, ...(second ? { signal: second } : {}) }\n : { state: 'unknown', executionId };\n }\n if (state === 'cancelled') return { state, executionId, ...(first ? { signal: first } : {}) };\n if (state === 'timed_out' && (first === 'startup' || first === 'execution')) {\n return { state, executionId, phase: first };\n }\n if (state === 'failed' && (first === 'upload' || first === 'install' || first === 'launch')) {\n return { state, executionId, phase: first, message: second ?? '' };\n }\n return { state: 'unknown', executionId };\n}\n\nasync function cancelExecution(\n config: WorkerConfig,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n timeoutPhase?: 'startup',\n): Promise<SandboxWorkerStatus> {\n const current = await readWorkerStatus(config.sandbox, executionId, paths);\n if (current.state !== 'running' && current.state !== 'starting') return current;\n const attempts = Math.max(1, Math.ceil(config.terminationGraceMs / 1000));\n const terminal = timeoutPhase ? `timed_out|${executionId}|startup` : `cancelled|${executionId}|TERM`;\n await runInSandbox(\n config.sandbox,\n [\n `pid=\"$(cat ${shellQuote(paths.pid)} 2>/dev/null || true)\"`,\n '[ -n \"$pid\" ] || exit 0',\n `expected=\"$(cat ${shellQuote(paths.pidToken)} 2>/dev/null || true)\"`,\n `actual=\"$(if [ -r \"/proc/$pid/stat\" ]; then awk '{print $22}' \"/proc/$pid/stat\"; fi)\"`,\n '[ -n \"$expected\" ] && [ \"$expected\" != \"$actual\" ] && exit 0',\n 'kill -TERM -\"$pid\" 2>/dev/null || kill -TERM \"$pid\" 2>/dev/null || true',\n `i=0; while kill -0 \"$pid\" 2>/dev/null && [ \"$i\" -lt ${attempts} ]; do sleep 1; i=$((i + 1)); done`,\n 'kill -KILL -\"$pid\" 2>/dev/null || kill -KILL \"$pid\" 2>/dev/null || true',\n `tmp=${shellQuote(`${paths.status}.tmp.$$`)}; printf '%s\\\\n' ${shellQuote(terminal)} > \"$tmp\"; mv \"$tmp\" ${shellQuote(paths.status)}`,\n `rm -f ${shellQuote(paths.pid)} ${shellQuote(paths.pidToken)}`,\n ].join('\\n'),\n { allowFailure: true, timeout: config.terminationGraceMs + 5_000, label: 'cancel worker execution' },\n );\n return parseStatus(executionId, terminal);\n}\n\nasync function readOutput(\n sandbox: WorkspaceSandbox,\n executionId: string,\n paths: ReturnType<typeof executionPaths>,\n stream: 'stdout' | 'stderr',\n options?: { offset?: number; maxBytes?: number },\n): Promise<SandboxWorkerOutput> {\n const offset = Math.max(0, Math.floor(options?.offset ?? 0));\n const maxBytes = Math.max(1, Math.floor(options?.maxBytes ?? DEFAULT_OUTPUT_READ_LIMIT));\n const path = stream === 'stdout' ? paths.stdout : paths.stderr;\n try {\n const result = await runInSandbox(\n sandbox,\n `size=$(wc -c < ${shellQuote(path)} 2>/dev/null || echo 0); printf '%s\\\\n' \"$size\"; tail -c +${offset + 1} ${shellQuote(\n path,\n )} 2>/dev/null | head -c ${maxBytes} | base64`,\n { allowFailure: true, label: `read worker ${stream}` },\n );\n if (result.exitCode !== 0) throw new Error(result.stderr || result.stdout || `Unable to read worker ${stream}.`);\n const newline = result.stdout.indexOf('\\n');\n const totalBytes = Number((newline === -1 ? result.stdout : result.stdout.slice(0, newline)).trim()) || 0;\n const encoded = newline === -1 ? '' : result.stdout.slice(newline + 1).replace(/\\s/g, '');\n const data = Buffer.from(encoded, 'base64');\n const nextOffset = offset + data.byteLength;\n const status = await readWorkerStatus(sandbox, executionId, paths);\n const terminal = ['exited', 'cancelled', 'timed_out', 'failed'].includes(status.state);\n const interrupted = status.state === 'provider_unavailable' || status.state === 'unknown';\n return {\n stream,\n data,\n offset,\n nextOffset,\n totalBytes,\n eof: terminal && nextOffset >= totalBytes,\n truncated: nextOffset < totalBytes,\n interrupted,\n };\n } catch {\n return {\n stream,\n data: new Uint8Array(),\n offset,\n nextOffset: offset,\n totalBytes: offset,\n eof: false,\n truncated: false,\n interrupted: true,\n };\n }\n}\n\nasync function destroyWithRetry(\n sandbox: WorkspaceSandbox,\n options?: { attempts?: number; delayMs?: number },\n): Promise<SandboxDestroyResult> {\n if (!sandbox.destroy) return { state: 'unsupported', attempts: 0 };\n const attempts = Math.max(1, Math.floor(options?.attempts ?? 3));\n const delayMs = Math.max(0, Math.floor(options?.delayMs ?? 250));\n let lastError: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n await sandbox.destroy();\n return { state: 'destroyed', attempts: attempt };\n } catch (error) {\n lastError = error;\n if (attempt < attempts) await new Promise(resolve => setTimeout(resolve, delayMs));\n }\n }\n return { state: 'exhausted', attempts, error: lastError };\n}\n\nasync function writeFailedStatus(\n sandbox: WorkspaceSandbox,\n paths: ReturnType<typeof executionPaths>,\n executionId: string,\n phase: 'upload' | 'install' | 'launch',\n error: unknown,\n): Promise<void> {\n await writeStatus(\n sandbox,\n paths.status,\n `failed|${executionId}|${phase}|${sanitizeStatusValue(errorMessage(error))}`,\n );\n}\n\nasync function writeStatus(sandbox: WorkspaceSandbox, path: string, value: string): Promise<void> {\n await runInSandbox(\n sandbox,\n `tmp=${shellQuote(`${path}.tmp.$$`)}; printf '%s\\\\n' ${shellQuote(value)} > \"$tmp\"; mv \"$tmp\" ${shellQuote(path)}`,\n { allowFailure: true, label: 'write worker status' },\n );\n}\n\nfunction executionPaths(remoteDir: string, executionId: string) {\n const dir = `${remoteDir}/${RUNTIME_DIR}/${executionId}`;\n return {\n executionId,\n dir,\n script: `${dir}/launch.sh`,\n pid: `${dir}/pid`,\n pidToken: `${dir}/pid-start`,\n status: `${dir}/status`,\n stdin: `${dir}/stdin`,\n stdout: `${dir}/stdout`,\n stderr: `${dir}/stderr`,\n };\n}\n\nfunction validateExecutionId(executionId: string): void {\n if (!executionId || !EXECUTION_ID_PATTERN.test(executionId)) {\n throw new Error('Worker executionId must contain only letters, numbers, dots, underscores, and hyphens.');\n }\n}\n\nfunction workerPhaseError(phase: 'upload' | 'install' | 'launch', error: unknown): Error {\n return new Error(`Worker ${phase} failed: ${errorMessage(error)}`, { cause: error });\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction sanitizeStatusValue(value: string): string {\n return value.replace(/[|\\r\\n]/g, ' ').slice(0, 500);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAOA,eAAsB,sBAAsB,SAA+D;CACzG,MAAM,EAAE,OAAO,WAAW;CAC1B,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,iFAAiF;CAGnG,MAAM,WAAW,IAAI,IAAI,yCAAyC,QAAQ,aAAa,OAAO;CAC9F,IAAI,QACF,SAAS,aAAa,IAAI,UAAU,MAAM;CAG5C,MAAM,MAAM,MAAM,MAAM,UAAU;EAChC,QAAQ;EACR,SAAS;GACP,eAAe,UAAU;GACzB,gBAAgB;EAClB;EACA,MAAM,KAAK,UAAU,EACnB,OAAO,CAAC;GAAE,WAAW;GAAU,KAAK,QAAQ;GAAK,OAAO,QAAQ;EAAI,CAAC,EACvE,CAAC;EAGD,QAAQ,YAAY,QAAQ,GAAM;CACpC,CAAC;CAED,IAAI,CAAC,IAAI,IAAI;EACX,MAAM,OAAO,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE;EAC5C,MAAM,IAA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;EACf,QAAQ,GAAG,IAAI;CACjB;AACF;AAEA,SAAS,oBAAoB,aAA2B;CACtD,IAAI,CAAC,eAAe,CAAC,qBAAqB,KAAK,WAAW,GACxD,MAAM,IAAI,MAAM,wFAAwF;AAE5G;AAEA,SAAS,iBAAiB,OAAwC,OAAuB;CACvF,OAAO,IAAI,MAAM,UAAU,MAAM,WAAW,aAAa,KAAK,KAAK,EAAE,OAAO,MAAM,CAAC;AACrF;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,oBAAoB,OAAuB;CAClD,OAAO,MAAM,QAAQ,YAAY,GAAG,CAAC,CAAC,MAAM,GAAG,GAAG;AACpD"}
@@ -1,4 +1,4 @@
1
- import{w as Be,s as gt,f as Xt,a as Zt,b as en,c as Je,h as tn}from"./main-BNh36EOV.js";import{c as nn,d as rn}from"./engine-compile-BkERmzkH.js";import"./preload-helper-PPVm8Dsz.js";let O=class extends Error{constructor(e){super(e),this.name="ShikiError"}},Me=class extends Error{constructor(e){super(e),this.name="ShikiError"}};function sn(){return 2147483648}function an(){return typeof performance<"u"?performance.now():Date.now()}const on=(n,e)=>n+(e-n%e)%e;async function cn(n){let e,t;const r={};function s(f){t=f,r.HEAPU8=new Uint8Array(f),r.HEAPU32=new Uint32Array(f)}function i(f,d,b){r.HEAPU8.copyWithin(f,d,d+b)}function a(f){try{return e.grow(f-t.byteLength+65535>>>16),s(e.buffer),1}catch{}}function c(f){const d=r.HEAPU8.length;f=f>>>0;const b=sn();if(f>b)return!1;for(let m=1;m<=4;m*=2){let _=d*(1+.2/m);_=Math.min(_,f+100663296);const p=Math.min(b,on(Math.max(f,_),65536));if(a(p))return!0}return!1}const o=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function l(f,d,b=1024){const m=d+b;let _=d;for(;f[_]&&!(_>=m);)++_;if(_-d>16&&f.buffer&&o)return o.decode(f.subarray(d,_));let p="";for(;d<_;){let y=f[d++];if(!(y&128)){p+=String.fromCharCode(y);continue}const w=f[d++]&63;if((y&224)===192){p+=String.fromCharCode((y&31)<<6|w);continue}const S=f[d++]&63;if((y&240)===224?y=(y&15)<<12|w<<6|S:y=(y&7)<<18|w<<12|S<<6|f[d++]&63,y<65536)p+=String.fromCharCode(y);else{const v=y-65536;p+=String.fromCharCode(55296|v>>10,56320|v&1023)}}return p}function u(f,d){return f?l(r.HEAPU8,f,d):""}const h={emscripten_get_now:an,emscripten_memcpy_big:i,emscripten_resize_heap:c,fd_write:()=>0};async function g(){const d=await n({env:h,wasi_snapshot_preview1:h});e=d.memory,s(e.buffer),Object.assign(r,d),r.UTF8ToString=u}return await g(),r}var ln=Object.defineProperty,un=(n,e,t)=>e in n?ln(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,C=(n,e,t)=>(un(n,typeof e!="symbol"?e+"":e,t),t);let R=null;function hn(n){throw new Me(n.UTF8ToString(n.getLastOnigError()))}class me{constructor(e){C(this,"utf16Length"),C(this,"utf8Length"),C(this,"utf16Value"),C(this,"utf8Value"),C(this,"utf16OffsetToUtf8"),C(this,"utf8OffsetToUtf16");const t=e.length,r=me._utf8ByteLength(e),s=r!==t,i=s?new Uint32Array(t+1):null;s&&(i[t]=r);const a=s?new Uint32Array(r+1):null;s&&(a[r]=t);const c=new Uint8Array(r);let o=0;for(let l=0;l<t;l++){const u=e.charCodeAt(l);let h=u,g=!1;if(u>=55296&&u<=56319&&l+1<t){const f=e.charCodeAt(l+1);f>=56320&&f<=57343&&(h=(u-55296<<10)+65536|f-56320,g=!0)}s&&(i[l]=o,g&&(i[l+1]=o),h<=127?a[o+0]=l:h<=2047?(a[o+0]=l,a[o+1]=l):h<=65535?(a[o+0]=l,a[o+1]=l,a[o+2]=l):(a[o+0]=l,a[o+1]=l,a[o+2]=l,a[o+3]=l)),h<=127?c[o++]=h:h<=2047?(c[o++]=192|(h&1984)>>>6,c[o++]=128|(h&63)>>>0):h<=65535?(c[o++]=224|(h&61440)>>>12,c[o++]=128|(h&4032)>>>6,c[o++]=128|(h&63)>>>0):(c[o++]=240|(h&1835008)>>>18,c[o++]=128|(h&258048)>>>12,c[o++]=128|(h&4032)>>>6,c[o++]=128|(h&63)>>>0),g&&l++}this.utf16Length=t,this.utf8Length=r,this.utf16Value=e,this.utf8Value=c,this.utf16OffsetToUtf8=i,this.utf8OffsetToUtf16=a}static _utf8ByteLength(e){let t=0;for(let r=0,s=e.length;r<s;r++){const i=e.charCodeAt(r);let a=i,c=!1;if(i>=55296&&i<=56319&&r+1<s){const o=e.charCodeAt(r+1);o>=56320&&o<=57343&&(a=(i-55296<<10)+65536|o-56320,c=!0)}a<=127?t+=1:a<=2047?t+=2:a<=65535?t+=3:t+=4,c&&r++}return t}createString(e){const t=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}}const E=class{constructor(n){if(C(this,"id",++E.LAST_ID),C(this,"_onigBinding"),C(this,"content"),C(this,"utf16Length"),C(this,"utf8Length"),C(this,"utf16OffsetToUtf8"),C(this,"utf8OffsetToUtf16"),C(this,"ptr"),!R)throw new Me("Must invoke loadWasm first.");this._onigBinding=R,this.content=n;const e=new me(n);this.utf16Length=e.utf16Length,this.utf8Length=e.utf8Length,this.utf16OffsetToUtf8=e.utf16OffsetToUtf8,this.utf8OffsetToUtf16=e.utf8OffsetToUtf16,this.utf8Length<1e4&&!E._sharedPtrInUse?(E._sharedPtr||(E._sharedPtr=R.omalloc(1e4)),E._sharedPtrInUse=!0,R.HEAPU8.set(e.utf8Value,E._sharedPtr),this.ptr=E._sharedPtr):this.ptr=e.createString(R)}convertUtf8OffsetToUtf16(n){return this.utf8OffsetToUtf16?n<0?0:n>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[n]:n}convertUtf16OffsetToUtf8(n){return this.utf16OffsetToUtf8?n<0?0:n>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[n]:n}dispose(){this.ptr===E._sharedPtr?E._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};let X=E;C(X,"LAST_ID",0);C(X,"_sharedPtr",0);C(X,"_sharedPtrInUse",!1);class fn{constructor(e){if(C(this,"_onigBinding"),C(this,"_ptr"),!R)throw new Me("Must invoke loadWasm first.");const t=[],r=[];for(let c=0,o=e.length;c<o;c++){const l=new me(e[c]);t[c]=l.createString(R),r[c]=l.utf8Length}const s=R.omalloc(4*e.length);R.HEAPU32.set(t,s/4);const i=R.omalloc(4*e.length);R.HEAPU32.set(r,i/4);const a=R.createOnigScanner(s,i,e.length);for(let c=0,o=e.length;c<o;c++)R.ofree(t[c]);R.ofree(i),R.ofree(s),a===0&&hn(R),this._onigBinding=R,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,t,r){let s=0;if(typeof r=="number"&&(s=r),typeof e=="string"){e=new X(e);const i=this._findNextMatchSync(e,t,!1,s);return e.dispose(),i}return this._findNextMatchSync(e,t,!1,s)}_findNextMatchSync(e,t,r,s){const i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),s);if(a===0)return null;const c=i.HEAPU32;let o=a/4;const l=c[o++],u=c[o++],h=[];for(let g=0;g<u;g++){const f=e.convertUtf8OffsetToUtf16(c[o++]),d=e.convertUtf8OffsetToUtf16(c[o++]);h[g]={start:f,end:d,length:d-f}}return{index:l,captureIndices:h}}}function dn(n){return typeof n.instantiator=="function"}function gn(n){return typeof n.default=="function"}function mn(n){return typeof n.data<"u"}function pn(n){return typeof Response<"u"&&n instanceof Response}function _n(n){return typeof ArrayBuffer<"u"&&(n instanceof ArrayBuffer||ArrayBuffer.isView(n))||typeof Buffer<"u"&&Buffer.isBuffer?.(n)||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer||typeof Uint32Array<"u"&&n instanceof Uint32Array}let ee;function mt(n){if(ee)return ee;async function e(){R=await cn(async t=>{let r=n;return r=await r,typeof r=="function"&&(r=await r(t)),typeof r=="function"&&(r=await r(t)),dn(r)?r=await r.instantiator(t):gn(r)?r=await r.default(t):(mn(r)&&(r=r.data),pn(r)?typeof WebAssembly.instantiateStreaming=="function"?r=await yn(r)(t):r=await bn(r)(t):_n(r)?r=await we(r)(t):r instanceof WebAssembly.Module?r=await we(r)(t):"default"in r&&r.default instanceof WebAssembly.Module&&(r=await we(r.default)(t))),"instance"in r&&(r=r.instance),"exports"in r&&(r=r.exports),r})}return ee=e(),ee}function we(n){return e=>WebAssembly.instantiate(n,e)}function yn(n){return e=>WebAssembly.instantiateStreaming(n,e)}function bn(n){return async e=>{const t=await n.arrayBuffer();return WebAssembly.instantiate(t,e)}}let Sn;function wn(){return Sn}async function $e(n){return n&&await mt(n),{createScanner(e){return new fn(e.map(t=>typeof t=="string"?t:t.source))},createString(e){return new X(e)}}}let se=!1,pt=!1;function Ks(n=!0,e=!1){se=n,pt=e}function I(n,e=3){if(se&&!(typeof se=="number"&&e>se)){if(pt)throw new Error(`[SHIKI DEPRECATE]: ${n}`);console.trace(`[SHIKI DEPRECATE]: ${n}`)}}function Cn(n){return je(n)}function je(n){return Array.isArray(n)?kn(n):n instanceof RegExp?n:typeof n=="object"?Rn(n):n}function kn(n){let e=[];for(let t=0,r=n.length;t<r;t++)e[t]=je(n[t]);return e}function Rn(n){let e={};for(let t in n)e[t]=je(n[t]);return e}function _t(n,...e){return e.forEach(t=>{for(let r in t)n[r]=t[r]}),n}function yt(n){const e=~n.lastIndexOf("/")||~n.lastIndexOf("\\");return e===0?n:~e===n.length-1?yt(n.substring(0,n.length-1)):n.substr(~e+1)}var Ce=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,te=class{static hasCaptures(n){return n===null?!1:(Ce.lastIndex=0,Ce.test(n))}static replaceCaptures(n,e,t){return n.replace(Ce,(r,s,i,a)=>{let c=t[parseInt(s||i,10)];if(c){let o=e.substring(c.start,c.end);for(;o[0]===".";)o=o.substring(1);switch(a){case"downcase":return o.toLowerCase();case"upcase":return o.toUpperCase();default:return o}}else return r})}};function bt(n,e){return n<e?-1:n>e?1:0}function St(n,e){if(n===null&&e===null)return 0;if(!n)return-1;if(!e)return 1;let t=n.length,r=e.length;if(t===r){for(let s=0;s<t;s++){let i=bt(n[s],e[s]);if(i!==0)return i}return 0}return t-r}function Ye(n){return!!(/^#[0-9a-f]{6}$/i.test(n)||/^#[0-9a-f]{8}$/i.test(n)||/^#[0-9a-f]{3}$/i.test(n)||/^#[0-9a-f]{4}$/i.test(n))}function wt(n){return n.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var Ct=class{constructor(n){this.fn=n}cache=new Map;get(n){if(this.cache.has(n))return this.cache.get(n);const e=this.fn(n);return this.cache.set(n,e),e}},oe=class{constructor(n,e,t){this._colorMap=n,this._defaults=e,this._root=t}static createFromRawTheme(n,e){return this.createFromParsedTheme(An(n),e)}static createFromParsedTheme(n,e){return In(n,e)}_cachedMatchRoot=new Ct(n=>this._root.match(n));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(n){if(n===null)return this._defaults;const e=n.scopeName,r=this._cachedMatchRoot.get(e).find(s=>Nn(n.parent,s.parentScopes));return r?new kt(r.fontStyle,r.foreground,r.background):null}},ke=class ie{constructor(e,t){this.parent=e,this.scopeName=t}static push(e,t){for(const r of t)e=new ie(e,r);return e}static from(...e){let t=null;for(let r=0;r<e.length;r++)t=new ie(t,e[r]);return t}push(e){return new ie(this,e)}getSegments(){let e=this;const t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(" ")}extends(e){return this===e?!0:this.parent===null?!1:this.parent.extends(e)}getExtensionIfDefined(e){const t=[];let r=this;for(;r&&r!==e;)t.push(r.scopeName),r=r.parent;return r===e?t.reverse():void 0}};function Nn(n,e){if(e.length===0)return!0;for(let t=0;t<e.length;t++){let r=e[t],s=!1;if(r===">"){if(t===e.length-1)return!1;r=e[++t],s=!0}for(;n&&!Tn(n.scopeName,r);){if(s)return!1;n=n.parent}if(!n)return!1;n=n.parent}return!0}function Tn(n,e){return e===n||n.startsWith(e)&&n[e.length]==="."}var kt=class{constructor(n,e,t){this.fontStyle=n,this.foregroundId=e,this.backgroundId=t}};function An(n){if(!n)return[];if(!n.settings||!Array.isArray(n.settings))return[];let e=n.settings,t=[],r=0;for(let s=0,i=e.length;s<i;s++){let a=e[s];if(!a.settings)continue;let c;if(typeof a.scope=="string"){let h=a.scope;h=h.replace(/^[,]+/,""),h=h.replace(/[,]+$/,""),c=h.split(",")}else Array.isArray(a.scope)?c=a.scope:c=[""];let o=-1;if(typeof a.settings.fontStyle=="string"){o=0;let h=a.settings.fontStyle.split(" ");for(let g=0,f=h.length;g<f;g++)switch(h[g]){case"italic":o=o|1;break;case"bold":o=o|2;break;case"underline":o=o|4;break;case"strikethrough":o=o|8;break}}let l=null;typeof a.settings.foreground=="string"&&Ye(a.settings.foreground)&&(l=a.settings.foreground);let u=null;typeof a.settings.background=="string"&&Ye(a.settings.background)&&(u=a.settings.background);for(let h=0,g=c.length;h<g;h++){let d=c[h].trim().split(" "),b=d[d.length-1],m=null;d.length>1&&(m=d.slice(0,d.length-1),m.reverse()),t[r++]=new vn(b,m,s,o,l,u)}}return t}var vn=class{constructor(n,e,t,r,s,i){this.scope=n,this.parentScopes=e,this.index=t,this.fontStyle=r,this.foreground=s,this.background=i}},x=(n=>(n[n.NotSet=-1]="NotSet",n[n.None=0]="None",n[n.Italic=1]="Italic",n[n.Bold=2]="Bold",n[n.Underline=4]="Underline",n[n.Strikethrough=8]="Strikethrough",n))(x||{});function In(n,e){n.sort((o,l)=>{let u=bt(o.scope,l.scope);return u!==0||(u=St(o.parentScopes,l.parentScopes),u!==0)?u:o.index-l.index});let t=0,r="#000000",s="#ffffff";for(;n.length>=1&&n[0].scope==="";){let o=n.shift();o.fontStyle!==-1&&(t=o.fontStyle),o.foreground!==null&&(r=o.foreground),o.background!==null&&(s=o.background)}let i=new En(e),a=new kt(t,i.getId(r),i.getId(s)),c=new Ln(new ve(0,null,-1,0,0),[]);for(let o=0,l=n.length;o<l;o++){let u=n[o];c.insert(0,u.scope,u.parentScopes,u.fontStyle,i.getId(u.foreground),i.getId(u.background))}return new oe(i,a,c)}var En=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(n){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(n)){this._isFrozen=!0;for(let e=0,t=n.length;e<t;e++)this._color2id[n[e]]=e,this._id2color[e]=n[e]}else this._isFrozen=!1}getId(n){if(n===null)return 0;n=n.toUpperCase();let e=this._color2id[n];if(e)return e;if(this._isFrozen)throw new Error(`Missing color in color map - ${n}`);return e=++this._lastColorId,this._color2id[n]=e,this._id2color[e]=n,e}getColorMap(){return this._id2color.slice(0)}},Pn=Object.freeze([]),ve=class Rt{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,r,s,i){this.scopeDepth=e,this.parentScopes=t||Pn,this.fontStyle=r,this.foreground=s,this.background=i}clone(){return new Rt(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let r=0,s=e.length;r<s;r++)t[r]=e[r].clone();return t}acceptOverwrite(e,t,r,s){this.scopeDepth>e?console.log("how did this happen?"):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),r!==0&&(this.foreground=r),s!==0&&(this.background=s)}},Ln=class Ie{constructor(e,t=[],r={}){this._mainRule=e,this._children=r,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let r=0,s=0;for(;e.parentScopes[r]===">"&&r++,t.parentScopes[s]===">"&&s++,!(r>=e.parentScopes.length||s>=t.parentScopes.length);){const i=t.parentScopes[s].length-e.parentScopes[r].length;if(i!==0)return i;r++,s++}return t.parentScopes.length-e.parentScopes.length}match(e){if(e!==""){let r=e.indexOf("."),s,i;if(r===-1?(s=e,i=""):(s=e.substring(0,r),i=e.substring(r+1)),this._children.hasOwnProperty(s))return this._children[s].match(i)}const t=this._rulesWithParentScopes.concat(this._mainRule);return t.sort(Ie._cmpBySpecificity),t}insert(e,t,r,s,i,a){if(t===""){this._doInsertHere(e,r,s,i,a);return}let c=t.indexOf("."),o,l;c===-1?(o=t,l=""):(o=t.substring(0,c),l=t.substring(c+1));let u;this._children.hasOwnProperty(o)?u=this._children[o]:(u=new Ie(this._mainRule.clone(),ve.cloneArr(this._rulesWithParentScopes)),this._children[o]=u),u.insert(e+1,l,r,s,i,a)}_doInsertHere(e,t,r,s,i){if(t===null){this._mainRule.acceptOverwrite(e,r,s,i);return}for(let a=0,c=this._rulesWithParentScopes.length;a<c;a++){let o=this._rulesWithParentScopes[a];if(St(o.parentScopes,t)===0){o.acceptOverwrite(e,r,s,i);return}}r===-1&&(r=this._mainRule.fontStyle),s===0&&(s=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new ve(e,t,r,s,i))}},W=class A{static toBinaryStr(e){return e.toString(2).padStart(32,"0")}static print(e){const t=A.getLanguageId(e),r=A.getTokenType(e),s=A.getFontStyle(e),i=A.getForeground(e),a=A.getBackground(e);console.log({languageId:t,tokenType:r,fontStyle:s,foreground:i,background:a})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return(e&1024)!==0}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(e,t,r,s,i,a,c){let o=A.getLanguageId(e),l=A.getTokenType(e),u=A.containsBalancedBrackets(e)?1:0,h=A.getFontStyle(e),g=A.getForeground(e),f=A.getBackground(e);return t!==0&&(o=t),r!==8&&(l=r),s!==null&&(u=s?1:0),i!==-1&&(h=i),a!==0&&(g=a),c!==0&&(f=c),(o<<0|l<<8|u<<10|h<<11|g<<15|f<<24)>>>0}};function ce(n,e){const t=[],r=xn(n);let s=r.next();for(;s!==null;){let o=0;if(s.length===2&&s.charAt(1)===":"){switch(s.charAt(0)){case"R":o=1;break;case"L":o=-1;break;default:console.log(`Unknown priority ${s} in scope selector`)}s=r.next()}let l=a();if(t.push({matcher:l,priority:o}),s!==",")break;s=r.next()}return t;function i(){if(s==="-"){s=r.next();const o=i();return l=>!!o&&!o(l)}if(s==="("){s=r.next();const o=c();return s===")"&&(s=r.next()),o}if(Qe(s)){const o=[];do o.push(s),s=r.next();while(Qe(s));return l=>e(o,l)}return null}function a(){const o=[];let l=i();for(;l;)o.push(l),l=i();return u=>o.every(h=>h(u))}function c(){const o=[];let l=a();for(;l&&(o.push(l),s==="|"||s===",");){do s=r.next();while(s==="|"||s===",");l=a()}return u=>o.some(h=>h(u))}}function Qe(n){return!!n&&!!n.match(/[\w\.:]+/)}function xn(n){let e=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,t=e.exec(n);return{next:()=>{if(!t)return null;const r=t[0];return t=e.exec(n),r}}}function Nt(n){typeof n.dispose=="function"&&n.dispose()}var z=class{constructor(n){this.scopeName=n}toKey(){return this.scopeName}},On=class{constructor(n,e){this.scopeName=n,this.ruleName=e}toKey(){return`${this.scopeName}#${this.ruleName}`}},Gn=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(n){const e=n.toKey();this._seenReferenceKeys.has(e)||(this._seenReferenceKeys.add(e),this._references.push(n))}},Bn=class{constructor(n,e){this.repo=n,this.initialScopeName=e,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new z(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){const n=this.Q;this.Q=[];const e=new Gn;for(const t of n)Mn(t,this.initialScopeName,this.repo,e);for(const t of e.references)if(t instanceof z){if(this.seenFullScopeRequests.has(t.scopeName))continue;this.seenFullScopeRequests.add(t.scopeName),this.Q.push(t)}else{if(this.seenFullScopeRequests.has(t.scopeName)||this.seenPartialScopeRequests.has(t.toKey()))continue;this.seenPartialScopeRequests.add(t.toKey()),this.Q.push(t)}}};function Mn(n,e,t,r){const s=t.lookup(n.scopeName);if(!s){if(n.scopeName===e)throw new Error(`No grammar provided for <${e}>`);return}const i=t.lookup(e);n instanceof z?ae({baseGrammar:i,selfGrammar:s},r):Ee(n.ruleName,{baseGrammar:i,selfGrammar:s,repository:s.repository},r);const a=t.injections(n.scopeName);if(a)for(const c of a)r.add(new z(c))}function Ee(n,e,t){if(e.repository&&e.repository[n]){const r=e.repository[n];le([r],e,t)}}function ae(n,e){n.selfGrammar.patterns&&Array.isArray(n.selfGrammar.patterns)&&le(n.selfGrammar.patterns,{...n,repository:n.selfGrammar.repository},e),n.selfGrammar.injections&&le(Object.values(n.selfGrammar.injections),{...n,repository:n.selfGrammar.repository},e)}function le(n,e,t){for(const r of n){if(t.visitedRule.has(r))continue;t.visitedRule.add(r);const s=r.repository?_t({},e.repository,r.repository):e.repository;Array.isArray(r.patterns)&&le(r.patterns,{...e,repository:s},t);const i=r.include;if(!i)continue;const a=Tt(i);switch(a.kind){case 0:ae({...e,selfGrammar:e.baseGrammar},t);break;case 1:ae(e,t);break;case 2:Ee(a.ruleName,{...e,repository:s},t);break;case 3:case 4:const c=a.scopeName===e.selfGrammar.scopeName?e.selfGrammar:a.scopeName===e.baseGrammar.scopeName?e.baseGrammar:void 0;if(c){const o={baseGrammar:e.baseGrammar,selfGrammar:c,repository:s};a.kind===4?Ee(a.ruleName,o,t):ae(o,t)}else a.kind===4?t.add(new On(a.scopeName,a.ruleName)):t.add(new z(a.scopeName));break}}}var $n=class{kind=0},jn=class{kind=1},Un=class{constructor(n){this.ruleName=n}kind=2},Wn=class{constructor(n){this.scopeName=n}kind=3},Dn=class{constructor(n,e){this.scopeName=n,this.ruleName=e}kind=4};function Tt(n){if(n==="$base")return new $n;if(n==="$self")return new jn;const e=n.indexOf("#");if(e===-1)return new Wn(n);if(e===0)return new Un(n.substring(1));{const t=n.substring(0,e),r=n.substring(e+1);return new Dn(t,r)}}var Hn=/\\(\d+)/,Xe=/\\(\d+)/g,Fn=-1,At=-2;var Z=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(n,e,t,r){this.$location=n,this.id=e,this._name=t||null,this._nameIsCapturing=te.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=te.hasCaptures(this._contentName)}get debugName(){const n=this.$location?`${yt(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${n}`}getName(n,e){return!this._nameIsCapturing||this._name===null||n===null||e===null?this._name:te.replaceCaptures(this._name,n,e)}getContentName(n,e){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:te.replaceCaptures(this._contentName,n,e)}},qn=class extends Z{retokenizeCapturedWithRuleId;constructor(n,e,t,r,s){super(n,e,t,r),this.retokenizeCapturedWithRuleId=s}dispose(){}collectPatterns(n,e){throw new Error("Not supported!")}compile(n,e){throw new Error("Not supported!")}compileAG(n,e,t,r){throw new Error("Not supported!")}},zn=class extends Z{_match;captures;_cachedCompiledPatterns;constructor(n,e,t,r,s){super(n,e,t,null),this._match=new V(r,this.id),this.captures=s,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(n,e){e.push(this._match)}compile(n,e){return this._getCachedCompiledPatterns(n).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n).compileAG(n,t,r)}_getCachedCompiledPatterns(n){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new K,this.collectPatterns(n,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Ze=class extends Z{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(n,e,t,r,s){super(n,e,t,r),this.patterns=s.patterns,this.hasMissingPatterns=s.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(n,e){for(const t of this.patterns)n.getRule(t).collectPatterns(n,e)}compile(n,e){return this._getCachedCompiledPatterns(n).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n).compileAG(n,t,r)}_getCachedCompiledPatterns(n){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new K,this.collectPatterns(n,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Pe=class extends Z{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(n,e,t,r,s,i,a,c,o,l){super(n,e,t,r),this._begin=new V(s,this.id),this.beginCaptures=i,this._end=new V(a||"￿",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=c,this.applyEndPatternLast=o||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(n,e){return this._end.resolveBackReferences(n,e)}collectPatterns(n,e){e.push(this._begin)}compile(n,e){return this._getCachedCompiledPatterns(n,e).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n,e).compileAG(n,t,r)}_getCachedCompiledPatterns(n,e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new K;for(const t of this.patterns)n.getRule(t).collectPatterns(n,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,e):this._cachedCompiledPatterns.setSource(0,e)),this._cachedCompiledPatterns}},ue=class extends Z{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(n,e,t,r,s,i,a,c,o){super(n,e,t,r),this._begin=new V(s,this.id),this.beginCaptures=i,this.whileCaptures=c,this._while=new V(a,At),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=o.patterns,this.hasMissingPatterns=o.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(n,e){return this._while.resolveBackReferences(n,e)}collectPatterns(n,e){e.push(this._begin)}compile(n,e){return this._getCachedCompiledPatterns(n).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n).compileAG(n,t,r)}_getCachedCompiledPatterns(n){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new K;for(const e of this.patterns)n.getRule(e).collectPatterns(n,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(n,e){return this._getCachedCompiledWhilePatterns(n,e).compile(n)}compileWhileAG(n,e,t,r){return this._getCachedCompiledWhilePatterns(n,e).compileAG(n,t,r)}_getCachedCompiledWhilePatterns(n,e){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new K,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,e||"￿"),this._cachedCompiledWhilePatterns}},vt=class N{static createCaptureRule(e,t,r,s,i){return e.registerRule(a=>new qn(t,a,r,s,i))}static getCompiledRuleId(e,t,r){return e.id||t.registerRule(s=>{if(e.id=s,e.match)return new zn(e.$vscodeTextmateLocation,e.id,e.name,e.match,N._compileCaptures(e.captures,t,r));if(typeof e.begin>"u"){e.repository&&(r=_t({},r,e.repository));let i=e.patterns;return typeof i>"u"&&e.include&&(i=[{include:e.include}]),new Ze(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,N._compilePatterns(i,t,r))}return e.while?new ue(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,N._compileCaptures(e.beginCaptures||e.captures,t,r),e.while,N._compileCaptures(e.whileCaptures||e.captures,t,r),N._compilePatterns(e.patterns,t,r)):new Pe(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,N._compileCaptures(e.beginCaptures||e.captures,t,r),e.end,N._compileCaptures(e.endCaptures||e.captures,t,r),e.applyEndPatternLast,N._compilePatterns(e.patterns,t,r))}),e.id}static _compileCaptures(e,t,r){let s=[];if(e){let i=0;for(const a in e){if(a==="$vscodeTextmateLocation")continue;const c=parseInt(a,10);c>i&&(i=c)}for(let a=0;a<=i;a++)s[a]=null;for(const a in e){if(a==="$vscodeTextmateLocation")continue;const c=parseInt(a,10);let o=0;e[a].patterns&&(o=N.getCompiledRuleId(e[a],t,r)),s[c]=N.createCaptureRule(t,e[a].$vscodeTextmateLocation,e[a].name,e[a].contentName,o)}}return s}static _compilePatterns(e,t,r){let s=[];if(e)for(let i=0,a=e.length;i<a;i++){const c=e[i];let o=-1;if(c.include){const l=Tt(c.include);switch(l.kind){case 0:case 1:o=N.getCompiledRuleId(r[c.include],t,r);break;case 2:let u=r[l.ruleName];u&&(o=N.getCompiledRuleId(u,t,r));break;case 3:case 4:const h=l.scopeName,g=l.kind===4?l.ruleName:null,f=t.getExternalGrammar(h,r);if(f)if(g){let d=f.repository[g];d&&(o=N.getCompiledRuleId(d,t,f.repository))}else o=N.getCompiledRuleId(f.repository.$self,t,f.repository);break}}else o=N.getCompiledRuleId(c,t,r);if(o!==-1){const l=t.getRule(o);let u=!1;if((l instanceof Ze||l instanceof Pe||l instanceof ue)&&l.hasMissingPatterns&&l.patterns.length===0&&(u=!0),u)continue;s.push(o)}}return{patterns:s,hasMissingPatterns:(e?e.length:0)!==s.length}}},V=class It{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e=="string"){const r=e.length;let s=0,i=[],a=!1;for(let c=0;c<r;c++)if(e.charAt(c)==="\\"&&c+1<r){const l=e.charAt(c+1);l==="z"?(i.push(e.substring(s,c)),i.push("$(?!\\n)(?<!\\n)"),s=c+2):(l==="A"||l==="G")&&(a=!0),c++}this.hasAnchor=a,s===0?this.source=e:(i.push(e.substring(s,r)),this.source=i.join(""))}else this.hasAnchor=!1,this.source=e;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=t,typeof this.source=="string"?this.hasBackReferences=Hn.test(this.source):this.hasBackReferences=!1}clone(){return new It(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let r=t.map(s=>e.substring(s.start,s.end));return Xe.lastIndex=0,this.source.replace(Xe,(s,i)=>wt(r[parseInt(i,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let e=[],t=[],r=[],s=[],i,a,c,o;for(i=0,a=this.source.length;i<a;i++)c=this.source.charAt(i),e[i]=c,t[i]=c,r[i]=c,s[i]=c,c==="\\"&&i+1<a&&(o=this.source.charAt(i+1),o==="A"?(e[i+1]="￿",t[i+1]="￿",r[i+1]="A",s[i+1]="A"):o==="G"?(e[i+1]="￿",t[i+1]="G",r[i+1]="￿",s[i+1]="G"):(e[i+1]=o,t[i+1]=o,r[i+1]=o,s[i+1]=o),i++);return{A0_G0:e.join(""),A0_G1:t.join(""),A1_G0:r.join(""),A1_G1:s.join("")}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},K=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(n){this._items.push(n),this._hasAnchors=this._hasAnchors||n.hasAnchor}unshift(n){this._items.unshift(n),this._hasAnchors=this._hasAnchors||n.hasAnchor}length(){return this._items.length}setSource(n,e){this._items[n].source!==e&&(this._disposeCaches(),this._items[n].setSource(e))}compile(n){if(!this._cached){let e=this._items.map(t=>t.source);this._cached=new et(n,e,this._items.map(t=>t.ruleId))}return this._cached}compileAG(n,e,t){return this._hasAnchors?e?t?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(n,e,t)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(n,e,t)),this._anchorCache.A1_G0):t?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(n,e,t)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(n,e,t)),this._anchorCache.A0_G0):this.compile(n)}_resolveAnchors(n,e,t){let r=this._items.map(s=>s.resolveAnchors(e,t));return new et(n,r,this._items.map(s=>s.ruleId))}},et=class{constructor(n,e,t){this.regExps=e,this.rules=t,this.scanner=n.createOnigScanner(e)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){const n=[];for(let e=0,t=this.rules.length;e<t;e++)n.push(" - "+this.rules[e]+": "+this.regExps[e]);return n.join(`
1
+ import{w as Be,s as gt,f as Xt,a as Zt,b as en,c as Je,h as tn}from"./main-DomdLuyE.js";import{c as nn,d as rn}from"./engine-compile-BkERmzkH.js";import"./preload-helper-PPVm8Dsz.js";let O=class extends Error{constructor(e){super(e),this.name="ShikiError"}},Me=class extends Error{constructor(e){super(e),this.name="ShikiError"}};function sn(){return 2147483648}function an(){return typeof performance<"u"?performance.now():Date.now()}const on=(n,e)=>n+(e-n%e)%e;async function cn(n){let e,t;const r={};function s(f){t=f,r.HEAPU8=new Uint8Array(f),r.HEAPU32=new Uint32Array(f)}function i(f,d,b){r.HEAPU8.copyWithin(f,d,d+b)}function a(f){try{return e.grow(f-t.byteLength+65535>>>16),s(e.buffer),1}catch{}}function c(f){const d=r.HEAPU8.length;f=f>>>0;const b=sn();if(f>b)return!1;for(let m=1;m<=4;m*=2){let _=d*(1+.2/m);_=Math.min(_,f+100663296);const p=Math.min(b,on(Math.max(f,_),65536));if(a(p))return!0}return!1}const o=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function l(f,d,b=1024){const m=d+b;let _=d;for(;f[_]&&!(_>=m);)++_;if(_-d>16&&f.buffer&&o)return o.decode(f.subarray(d,_));let p="";for(;d<_;){let y=f[d++];if(!(y&128)){p+=String.fromCharCode(y);continue}const w=f[d++]&63;if((y&224)===192){p+=String.fromCharCode((y&31)<<6|w);continue}const S=f[d++]&63;if((y&240)===224?y=(y&15)<<12|w<<6|S:y=(y&7)<<18|w<<12|S<<6|f[d++]&63,y<65536)p+=String.fromCharCode(y);else{const v=y-65536;p+=String.fromCharCode(55296|v>>10,56320|v&1023)}}return p}function u(f,d){return f?l(r.HEAPU8,f,d):""}const h={emscripten_get_now:an,emscripten_memcpy_big:i,emscripten_resize_heap:c,fd_write:()=>0};async function g(){const d=await n({env:h,wasi_snapshot_preview1:h});e=d.memory,s(e.buffer),Object.assign(r,d),r.UTF8ToString=u}return await g(),r}var ln=Object.defineProperty,un=(n,e,t)=>e in n?ln(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,C=(n,e,t)=>(un(n,typeof e!="symbol"?e+"":e,t),t);let R=null;function hn(n){throw new Me(n.UTF8ToString(n.getLastOnigError()))}class me{constructor(e){C(this,"utf16Length"),C(this,"utf8Length"),C(this,"utf16Value"),C(this,"utf8Value"),C(this,"utf16OffsetToUtf8"),C(this,"utf8OffsetToUtf16");const t=e.length,r=me._utf8ByteLength(e),s=r!==t,i=s?new Uint32Array(t+1):null;s&&(i[t]=r);const a=s?new Uint32Array(r+1):null;s&&(a[r]=t);const c=new Uint8Array(r);let o=0;for(let l=0;l<t;l++){const u=e.charCodeAt(l);let h=u,g=!1;if(u>=55296&&u<=56319&&l+1<t){const f=e.charCodeAt(l+1);f>=56320&&f<=57343&&(h=(u-55296<<10)+65536|f-56320,g=!0)}s&&(i[l]=o,g&&(i[l+1]=o),h<=127?a[o+0]=l:h<=2047?(a[o+0]=l,a[o+1]=l):h<=65535?(a[o+0]=l,a[o+1]=l,a[o+2]=l):(a[o+0]=l,a[o+1]=l,a[o+2]=l,a[o+3]=l)),h<=127?c[o++]=h:h<=2047?(c[o++]=192|(h&1984)>>>6,c[o++]=128|(h&63)>>>0):h<=65535?(c[o++]=224|(h&61440)>>>12,c[o++]=128|(h&4032)>>>6,c[o++]=128|(h&63)>>>0):(c[o++]=240|(h&1835008)>>>18,c[o++]=128|(h&258048)>>>12,c[o++]=128|(h&4032)>>>6,c[o++]=128|(h&63)>>>0),g&&l++}this.utf16Length=t,this.utf8Length=r,this.utf16Value=e,this.utf8Value=c,this.utf16OffsetToUtf8=i,this.utf8OffsetToUtf16=a}static _utf8ByteLength(e){let t=0;for(let r=0,s=e.length;r<s;r++){const i=e.charCodeAt(r);let a=i,c=!1;if(i>=55296&&i<=56319&&r+1<s){const o=e.charCodeAt(r+1);o>=56320&&o<=57343&&(a=(i-55296<<10)+65536|o-56320,c=!0)}a<=127?t+=1:a<=2047?t+=2:a<=65535?t+=3:t+=4,c&&r++}return t}createString(e){const t=e.omalloc(this.utf8Length);return e.HEAPU8.set(this.utf8Value,t),t}}const E=class{constructor(n){if(C(this,"id",++E.LAST_ID),C(this,"_onigBinding"),C(this,"content"),C(this,"utf16Length"),C(this,"utf8Length"),C(this,"utf16OffsetToUtf8"),C(this,"utf8OffsetToUtf16"),C(this,"ptr"),!R)throw new Me("Must invoke loadWasm first.");this._onigBinding=R,this.content=n;const e=new me(n);this.utf16Length=e.utf16Length,this.utf8Length=e.utf8Length,this.utf16OffsetToUtf8=e.utf16OffsetToUtf8,this.utf8OffsetToUtf16=e.utf8OffsetToUtf16,this.utf8Length<1e4&&!E._sharedPtrInUse?(E._sharedPtr||(E._sharedPtr=R.omalloc(1e4)),E._sharedPtrInUse=!0,R.HEAPU8.set(e.utf8Value,E._sharedPtr),this.ptr=E._sharedPtr):this.ptr=e.createString(R)}convertUtf8OffsetToUtf16(n){return this.utf8OffsetToUtf16?n<0?0:n>this.utf8Length?this.utf16Length:this.utf8OffsetToUtf16[n]:n}convertUtf16OffsetToUtf8(n){return this.utf16OffsetToUtf8?n<0?0:n>this.utf16Length?this.utf8Length:this.utf16OffsetToUtf8[n]:n}dispose(){this.ptr===E._sharedPtr?E._sharedPtrInUse=!1:this._onigBinding.ofree(this.ptr)}};let X=E;C(X,"LAST_ID",0);C(X,"_sharedPtr",0);C(X,"_sharedPtrInUse",!1);class fn{constructor(e){if(C(this,"_onigBinding"),C(this,"_ptr"),!R)throw new Me("Must invoke loadWasm first.");const t=[],r=[];for(let c=0,o=e.length;c<o;c++){const l=new me(e[c]);t[c]=l.createString(R),r[c]=l.utf8Length}const s=R.omalloc(4*e.length);R.HEAPU32.set(t,s/4);const i=R.omalloc(4*e.length);R.HEAPU32.set(r,i/4);const a=R.createOnigScanner(s,i,e.length);for(let c=0,o=e.length;c<o;c++)R.ofree(t[c]);R.ofree(i),R.ofree(s),a===0&&hn(R),this._onigBinding=R,this._ptr=a}dispose(){this._onigBinding.freeOnigScanner(this._ptr)}findNextMatchSync(e,t,r){let s=0;if(typeof r=="number"&&(s=r),typeof e=="string"){e=new X(e);const i=this._findNextMatchSync(e,t,!1,s);return e.dispose(),i}return this._findNextMatchSync(e,t,!1,s)}_findNextMatchSync(e,t,r,s){const i=this._onigBinding,a=i.findNextOnigScannerMatch(this._ptr,e.id,e.ptr,e.utf8Length,e.convertUtf16OffsetToUtf8(t),s);if(a===0)return null;const c=i.HEAPU32;let o=a/4;const l=c[o++],u=c[o++],h=[];for(let g=0;g<u;g++){const f=e.convertUtf8OffsetToUtf16(c[o++]),d=e.convertUtf8OffsetToUtf16(c[o++]);h[g]={start:f,end:d,length:d-f}}return{index:l,captureIndices:h}}}function dn(n){return typeof n.instantiator=="function"}function gn(n){return typeof n.default=="function"}function mn(n){return typeof n.data<"u"}function pn(n){return typeof Response<"u"&&n instanceof Response}function _n(n){return typeof ArrayBuffer<"u"&&(n instanceof ArrayBuffer||ArrayBuffer.isView(n))||typeof Buffer<"u"&&Buffer.isBuffer?.(n)||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer||typeof Uint32Array<"u"&&n instanceof Uint32Array}let ee;function mt(n){if(ee)return ee;async function e(){R=await cn(async t=>{let r=n;return r=await r,typeof r=="function"&&(r=await r(t)),typeof r=="function"&&(r=await r(t)),dn(r)?r=await r.instantiator(t):gn(r)?r=await r.default(t):(mn(r)&&(r=r.data),pn(r)?typeof WebAssembly.instantiateStreaming=="function"?r=await yn(r)(t):r=await bn(r)(t):_n(r)?r=await we(r)(t):r instanceof WebAssembly.Module?r=await we(r)(t):"default"in r&&r.default instanceof WebAssembly.Module&&(r=await we(r.default)(t))),"instance"in r&&(r=r.instance),"exports"in r&&(r=r.exports),r})}return ee=e(),ee}function we(n){return e=>WebAssembly.instantiate(n,e)}function yn(n){return e=>WebAssembly.instantiateStreaming(n,e)}function bn(n){return async e=>{const t=await n.arrayBuffer();return WebAssembly.instantiate(t,e)}}let Sn;function wn(){return Sn}async function $e(n){return n&&await mt(n),{createScanner(e){return new fn(e.map(t=>typeof t=="string"?t:t.source))},createString(e){return new X(e)}}}let se=!1,pt=!1;function Ks(n=!0,e=!1){se=n,pt=e}function I(n,e=3){if(se&&!(typeof se=="number"&&e>se)){if(pt)throw new Error(`[SHIKI DEPRECATE]: ${n}`);console.trace(`[SHIKI DEPRECATE]: ${n}`)}}function Cn(n){return je(n)}function je(n){return Array.isArray(n)?kn(n):n instanceof RegExp?n:typeof n=="object"?Rn(n):n}function kn(n){let e=[];for(let t=0,r=n.length;t<r;t++)e[t]=je(n[t]);return e}function Rn(n){let e={};for(let t in n)e[t]=je(n[t]);return e}function _t(n,...e){return e.forEach(t=>{for(let r in t)n[r]=t[r]}),n}function yt(n){const e=~n.lastIndexOf("/")||~n.lastIndexOf("\\");return e===0?n:~e===n.length-1?yt(n.substring(0,n.length-1)):n.substr(~e+1)}var Ce=/\$(\d+)|\${(\d+):\/(downcase|upcase)}/g,te=class{static hasCaptures(n){return n===null?!1:(Ce.lastIndex=0,Ce.test(n))}static replaceCaptures(n,e,t){return n.replace(Ce,(r,s,i,a)=>{let c=t[parseInt(s||i,10)];if(c){let o=e.substring(c.start,c.end);for(;o[0]===".";)o=o.substring(1);switch(a){case"downcase":return o.toLowerCase();case"upcase":return o.toUpperCase();default:return o}}else return r})}};function bt(n,e){return n<e?-1:n>e?1:0}function St(n,e){if(n===null&&e===null)return 0;if(!n)return-1;if(!e)return 1;let t=n.length,r=e.length;if(t===r){for(let s=0;s<t;s++){let i=bt(n[s],e[s]);if(i!==0)return i}return 0}return t-r}function Ye(n){return!!(/^#[0-9a-f]{6}$/i.test(n)||/^#[0-9a-f]{8}$/i.test(n)||/^#[0-9a-f]{3}$/i.test(n)||/^#[0-9a-f]{4}$/i.test(n))}function wt(n){return n.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&")}var Ct=class{constructor(n){this.fn=n}cache=new Map;get(n){if(this.cache.has(n))return this.cache.get(n);const e=this.fn(n);return this.cache.set(n,e),e}},oe=class{constructor(n,e,t){this._colorMap=n,this._defaults=e,this._root=t}static createFromRawTheme(n,e){return this.createFromParsedTheme(An(n),e)}static createFromParsedTheme(n,e){return In(n,e)}_cachedMatchRoot=new Ct(n=>this._root.match(n));getColorMap(){return this._colorMap.getColorMap()}getDefaults(){return this._defaults}match(n){if(n===null)return this._defaults;const e=n.scopeName,r=this._cachedMatchRoot.get(e).find(s=>Nn(n.parent,s.parentScopes));return r?new kt(r.fontStyle,r.foreground,r.background):null}},ke=class ie{constructor(e,t){this.parent=e,this.scopeName=t}static push(e,t){for(const r of t)e=new ie(e,r);return e}static from(...e){let t=null;for(let r=0;r<e.length;r++)t=new ie(t,e[r]);return t}push(e){return new ie(this,e)}getSegments(){let e=this;const t=[];for(;e;)t.push(e.scopeName),e=e.parent;return t.reverse(),t}toString(){return this.getSegments().join(" ")}extends(e){return this===e?!0:this.parent===null?!1:this.parent.extends(e)}getExtensionIfDefined(e){const t=[];let r=this;for(;r&&r!==e;)t.push(r.scopeName),r=r.parent;return r===e?t.reverse():void 0}};function Nn(n,e){if(e.length===0)return!0;for(let t=0;t<e.length;t++){let r=e[t],s=!1;if(r===">"){if(t===e.length-1)return!1;r=e[++t],s=!0}for(;n&&!Tn(n.scopeName,r);){if(s)return!1;n=n.parent}if(!n)return!1;n=n.parent}return!0}function Tn(n,e){return e===n||n.startsWith(e)&&n[e.length]==="."}var kt=class{constructor(n,e,t){this.fontStyle=n,this.foregroundId=e,this.backgroundId=t}};function An(n){if(!n)return[];if(!n.settings||!Array.isArray(n.settings))return[];let e=n.settings,t=[],r=0;for(let s=0,i=e.length;s<i;s++){let a=e[s];if(!a.settings)continue;let c;if(typeof a.scope=="string"){let h=a.scope;h=h.replace(/^[,]+/,""),h=h.replace(/[,]+$/,""),c=h.split(",")}else Array.isArray(a.scope)?c=a.scope:c=[""];let o=-1;if(typeof a.settings.fontStyle=="string"){o=0;let h=a.settings.fontStyle.split(" ");for(let g=0,f=h.length;g<f;g++)switch(h[g]){case"italic":o=o|1;break;case"bold":o=o|2;break;case"underline":o=o|4;break;case"strikethrough":o=o|8;break}}let l=null;typeof a.settings.foreground=="string"&&Ye(a.settings.foreground)&&(l=a.settings.foreground);let u=null;typeof a.settings.background=="string"&&Ye(a.settings.background)&&(u=a.settings.background);for(let h=0,g=c.length;h<g;h++){let d=c[h].trim().split(" "),b=d[d.length-1],m=null;d.length>1&&(m=d.slice(0,d.length-1),m.reverse()),t[r++]=new vn(b,m,s,o,l,u)}}return t}var vn=class{constructor(n,e,t,r,s,i){this.scope=n,this.parentScopes=e,this.index=t,this.fontStyle=r,this.foreground=s,this.background=i}},x=(n=>(n[n.NotSet=-1]="NotSet",n[n.None=0]="None",n[n.Italic=1]="Italic",n[n.Bold=2]="Bold",n[n.Underline=4]="Underline",n[n.Strikethrough=8]="Strikethrough",n))(x||{});function In(n,e){n.sort((o,l)=>{let u=bt(o.scope,l.scope);return u!==0||(u=St(o.parentScopes,l.parentScopes),u!==0)?u:o.index-l.index});let t=0,r="#000000",s="#ffffff";for(;n.length>=1&&n[0].scope==="";){let o=n.shift();o.fontStyle!==-1&&(t=o.fontStyle),o.foreground!==null&&(r=o.foreground),o.background!==null&&(s=o.background)}let i=new En(e),a=new kt(t,i.getId(r),i.getId(s)),c=new Ln(new ve(0,null,-1,0,0),[]);for(let o=0,l=n.length;o<l;o++){let u=n[o];c.insert(0,u.scope,u.parentScopes,u.fontStyle,i.getId(u.foreground),i.getId(u.background))}return new oe(i,a,c)}var En=class{_isFrozen;_lastColorId;_id2color;_color2id;constructor(n){if(this._lastColorId=0,this._id2color=[],this._color2id=Object.create(null),Array.isArray(n)){this._isFrozen=!0;for(let e=0,t=n.length;e<t;e++)this._color2id[n[e]]=e,this._id2color[e]=n[e]}else this._isFrozen=!1}getId(n){if(n===null)return 0;n=n.toUpperCase();let e=this._color2id[n];if(e)return e;if(this._isFrozen)throw new Error(`Missing color in color map - ${n}`);return e=++this._lastColorId,this._color2id[n]=e,this._id2color[e]=n,e}getColorMap(){return this._id2color.slice(0)}},Pn=Object.freeze([]),ve=class Rt{scopeDepth;parentScopes;fontStyle;foreground;background;constructor(e,t,r,s,i){this.scopeDepth=e,this.parentScopes=t||Pn,this.fontStyle=r,this.foreground=s,this.background=i}clone(){return new Rt(this.scopeDepth,this.parentScopes,this.fontStyle,this.foreground,this.background)}static cloneArr(e){let t=[];for(let r=0,s=e.length;r<s;r++)t[r]=e[r].clone();return t}acceptOverwrite(e,t,r,s){this.scopeDepth>e?console.log("how did this happen?"):this.scopeDepth=e,t!==-1&&(this.fontStyle=t),r!==0&&(this.foreground=r),s!==0&&(this.background=s)}},Ln=class Ie{constructor(e,t=[],r={}){this._mainRule=e,this._children=r,this._rulesWithParentScopes=t}_rulesWithParentScopes;static _cmpBySpecificity(e,t){if(e.scopeDepth!==t.scopeDepth)return t.scopeDepth-e.scopeDepth;let r=0,s=0;for(;e.parentScopes[r]===">"&&r++,t.parentScopes[s]===">"&&s++,!(r>=e.parentScopes.length||s>=t.parentScopes.length);){const i=t.parentScopes[s].length-e.parentScopes[r].length;if(i!==0)return i;r++,s++}return t.parentScopes.length-e.parentScopes.length}match(e){if(e!==""){let r=e.indexOf("."),s,i;if(r===-1?(s=e,i=""):(s=e.substring(0,r),i=e.substring(r+1)),this._children.hasOwnProperty(s))return this._children[s].match(i)}const t=this._rulesWithParentScopes.concat(this._mainRule);return t.sort(Ie._cmpBySpecificity),t}insert(e,t,r,s,i,a){if(t===""){this._doInsertHere(e,r,s,i,a);return}let c=t.indexOf("."),o,l;c===-1?(o=t,l=""):(o=t.substring(0,c),l=t.substring(c+1));let u;this._children.hasOwnProperty(o)?u=this._children[o]:(u=new Ie(this._mainRule.clone(),ve.cloneArr(this._rulesWithParentScopes)),this._children[o]=u),u.insert(e+1,l,r,s,i,a)}_doInsertHere(e,t,r,s,i){if(t===null){this._mainRule.acceptOverwrite(e,r,s,i);return}for(let a=0,c=this._rulesWithParentScopes.length;a<c;a++){let o=this._rulesWithParentScopes[a];if(St(o.parentScopes,t)===0){o.acceptOverwrite(e,r,s,i);return}}r===-1&&(r=this._mainRule.fontStyle),s===0&&(s=this._mainRule.foreground),i===0&&(i=this._mainRule.background),this._rulesWithParentScopes.push(new ve(e,t,r,s,i))}},W=class A{static toBinaryStr(e){return e.toString(2).padStart(32,"0")}static print(e){const t=A.getLanguageId(e),r=A.getTokenType(e),s=A.getFontStyle(e),i=A.getForeground(e),a=A.getBackground(e);console.log({languageId:t,tokenType:r,fontStyle:s,foreground:i,background:a})}static getLanguageId(e){return(e&255)>>>0}static getTokenType(e){return(e&768)>>>8}static containsBalancedBrackets(e){return(e&1024)!==0}static getFontStyle(e){return(e&30720)>>>11}static getForeground(e){return(e&16744448)>>>15}static getBackground(e){return(e&4278190080)>>>24}static set(e,t,r,s,i,a,c){let o=A.getLanguageId(e),l=A.getTokenType(e),u=A.containsBalancedBrackets(e)?1:0,h=A.getFontStyle(e),g=A.getForeground(e),f=A.getBackground(e);return t!==0&&(o=t),r!==8&&(l=r),s!==null&&(u=s?1:0),i!==-1&&(h=i),a!==0&&(g=a),c!==0&&(f=c),(o<<0|l<<8|u<<10|h<<11|g<<15|f<<24)>>>0}};function ce(n,e){const t=[],r=xn(n);let s=r.next();for(;s!==null;){let o=0;if(s.length===2&&s.charAt(1)===":"){switch(s.charAt(0)){case"R":o=1;break;case"L":o=-1;break;default:console.log(`Unknown priority ${s} in scope selector`)}s=r.next()}let l=a();if(t.push({matcher:l,priority:o}),s!==",")break;s=r.next()}return t;function i(){if(s==="-"){s=r.next();const o=i();return l=>!!o&&!o(l)}if(s==="("){s=r.next();const o=c();return s===")"&&(s=r.next()),o}if(Qe(s)){const o=[];do o.push(s),s=r.next();while(Qe(s));return l=>e(o,l)}return null}function a(){const o=[];let l=i();for(;l;)o.push(l),l=i();return u=>o.every(h=>h(u))}function c(){const o=[];let l=a();for(;l&&(o.push(l),s==="|"||s===",");){do s=r.next();while(s==="|"||s===",");l=a()}return u=>o.some(h=>h(u))}}function Qe(n){return!!n&&!!n.match(/[\w\.:]+/)}function xn(n){let e=/([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g,t=e.exec(n);return{next:()=>{if(!t)return null;const r=t[0];return t=e.exec(n),r}}}function Nt(n){typeof n.dispose=="function"&&n.dispose()}var z=class{constructor(n){this.scopeName=n}toKey(){return this.scopeName}},On=class{constructor(n,e){this.scopeName=n,this.ruleName=e}toKey(){return`${this.scopeName}#${this.ruleName}`}},Gn=class{_references=[];_seenReferenceKeys=new Set;get references(){return this._references}visitedRule=new Set;add(n){const e=n.toKey();this._seenReferenceKeys.has(e)||(this._seenReferenceKeys.add(e),this._references.push(n))}},Bn=class{constructor(n,e){this.repo=n,this.initialScopeName=e,this.seenFullScopeRequests.add(this.initialScopeName),this.Q=[new z(this.initialScopeName)]}seenFullScopeRequests=new Set;seenPartialScopeRequests=new Set;Q;processQueue(){const n=this.Q;this.Q=[];const e=new Gn;for(const t of n)Mn(t,this.initialScopeName,this.repo,e);for(const t of e.references)if(t instanceof z){if(this.seenFullScopeRequests.has(t.scopeName))continue;this.seenFullScopeRequests.add(t.scopeName),this.Q.push(t)}else{if(this.seenFullScopeRequests.has(t.scopeName)||this.seenPartialScopeRequests.has(t.toKey()))continue;this.seenPartialScopeRequests.add(t.toKey()),this.Q.push(t)}}};function Mn(n,e,t,r){const s=t.lookup(n.scopeName);if(!s){if(n.scopeName===e)throw new Error(`No grammar provided for <${e}>`);return}const i=t.lookup(e);n instanceof z?ae({baseGrammar:i,selfGrammar:s},r):Ee(n.ruleName,{baseGrammar:i,selfGrammar:s,repository:s.repository},r);const a=t.injections(n.scopeName);if(a)for(const c of a)r.add(new z(c))}function Ee(n,e,t){if(e.repository&&e.repository[n]){const r=e.repository[n];le([r],e,t)}}function ae(n,e){n.selfGrammar.patterns&&Array.isArray(n.selfGrammar.patterns)&&le(n.selfGrammar.patterns,{...n,repository:n.selfGrammar.repository},e),n.selfGrammar.injections&&le(Object.values(n.selfGrammar.injections),{...n,repository:n.selfGrammar.repository},e)}function le(n,e,t){for(const r of n){if(t.visitedRule.has(r))continue;t.visitedRule.add(r);const s=r.repository?_t({},e.repository,r.repository):e.repository;Array.isArray(r.patterns)&&le(r.patterns,{...e,repository:s},t);const i=r.include;if(!i)continue;const a=Tt(i);switch(a.kind){case 0:ae({...e,selfGrammar:e.baseGrammar},t);break;case 1:ae(e,t);break;case 2:Ee(a.ruleName,{...e,repository:s},t);break;case 3:case 4:const c=a.scopeName===e.selfGrammar.scopeName?e.selfGrammar:a.scopeName===e.baseGrammar.scopeName?e.baseGrammar:void 0;if(c){const o={baseGrammar:e.baseGrammar,selfGrammar:c,repository:s};a.kind===4?Ee(a.ruleName,o,t):ae(o,t)}else a.kind===4?t.add(new On(a.scopeName,a.ruleName)):t.add(new z(a.scopeName));break}}}var $n=class{kind=0},jn=class{kind=1},Un=class{constructor(n){this.ruleName=n}kind=2},Wn=class{constructor(n){this.scopeName=n}kind=3},Dn=class{constructor(n,e){this.scopeName=n,this.ruleName=e}kind=4};function Tt(n){if(n==="$base")return new $n;if(n==="$self")return new jn;const e=n.indexOf("#");if(e===-1)return new Wn(n);if(e===0)return new Un(n.substring(1));{const t=n.substring(0,e),r=n.substring(e+1);return new Dn(t,r)}}var Hn=/\\(\d+)/,Xe=/\\(\d+)/g,Fn=-1,At=-2;var Z=class{$location;id;_nameIsCapturing;_name;_contentNameIsCapturing;_contentName;constructor(n,e,t,r){this.$location=n,this.id=e,this._name=t||null,this._nameIsCapturing=te.hasCaptures(this._name),this._contentName=r||null,this._contentNameIsCapturing=te.hasCaptures(this._contentName)}get debugName(){const n=this.$location?`${yt(this.$location.filename)}:${this.$location.line}`:"unknown";return`${this.constructor.name}#${this.id} @ ${n}`}getName(n,e){return!this._nameIsCapturing||this._name===null||n===null||e===null?this._name:te.replaceCaptures(this._name,n,e)}getContentName(n,e){return!this._contentNameIsCapturing||this._contentName===null?this._contentName:te.replaceCaptures(this._contentName,n,e)}},qn=class extends Z{retokenizeCapturedWithRuleId;constructor(n,e,t,r,s){super(n,e,t,r),this.retokenizeCapturedWithRuleId=s}dispose(){}collectPatterns(n,e){throw new Error("Not supported!")}compile(n,e){throw new Error("Not supported!")}compileAG(n,e,t,r){throw new Error("Not supported!")}},zn=class extends Z{_match;captures;_cachedCompiledPatterns;constructor(n,e,t,r,s){super(n,e,t,null),this._match=new V(r,this.id),this.captures=s,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugMatchRegExp(){return`${this._match.source}`}collectPatterns(n,e){e.push(this._match)}compile(n,e){return this._getCachedCompiledPatterns(n).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n).compileAG(n,t,r)}_getCachedCompiledPatterns(n){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new K,this.collectPatterns(n,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Ze=class extends Z{hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(n,e,t,r,s){super(n,e,t,r),this.patterns=s.patterns,this.hasMissingPatterns=s.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}collectPatterns(n,e){for(const t of this.patterns)n.getRule(t).collectPatterns(n,e)}compile(n,e){return this._getCachedCompiledPatterns(n).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n).compileAG(n,t,r)}_getCachedCompiledPatterns(n){return this._cachedCompiledPatterns||(this._cachedCompiledPatterns=new K,this.collectPatterns(n,this._cachedCompiledPatterns)),this._cachedCompiledPatterns}},Pe=class extends Z{_begin;beginCaptures;_end;endHasBackReferences;endCaptures;applyEndPatternLast;hasMissingPatterns;patterns;_cachedCompiledPatterns;constructor(n,e,t,r,s,i,a,c,o,l){super(n,e,t,r),this._begin=new V(s,this.id),this.beginCaptures=i,this._end=new V(a||"￿",-1),this.endHasBackReferences=this._end.hasBackReferences,this.endCaptures=c,this.applyEndPatternLast=o||!1,this.patterns=l.patterns,this.hasMissingPatterns=l.hasMissingPatterns,this._cachedCompiledPatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugEndRegExp(){return`${this._end.source}`}getEndWithResolvedBackReferences(n,e){return this._end.resolveBackReferences(n,e)}collectPatterns(n,e){e.push(this._begin)}compile(n,e){return this._getCachedCompiledPatterns(n,e).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n,e).compileAG(n,t,r)}_getCachedCompiledPatterns(n,e){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new K;for(const t of this.patterns)n.getRule(t).collectPatterns(n,this._cachedCompiledPatterns);this.applyEndPatternLast?this._cachedCompiledPatterns.push(this._end.hasBackReferences?this._end.clone():this._end):this._cachedCompiledPatterns.unshift(this._end.hasBackReferences?this._end.clone():this._end)}return this._end.hasBackReferences&&(this.applyEndPatternLast?this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length()-1,e):this._cachedCompiledPatterns.setSource(0,e)),this._cachedCompiledPatterns}},ue=class extends Z{_begin;beginCaptures;whileCaptures;_while;whileHasBackReferences;hasMissingPatterns;patterns;_cachedCompiledPatterns;_cachedCompiledWhilePatterns;constructor(n,e,t,r,s,i,a,c,o){super(n,e,t,r),this._begin=new V(s,this.id),this.beginCaptures=i,this.whileCaptures=c,this._while=new V(a,At),this.whileHasBackReferences=this._while.hasBackReferences,this.patterns=o.patterns,this.hasMissingPatterns=o.hasMissingPatterns,this._cachedCompiledPatterns=null,this._cachedCompiledWhilePatterns=null}dispose(){this._cachedCompiledPatterns&&(this._cachedCompiledPatterns.dispose(),this._cachedCompiledPatterns=null),this._cachedCompiledWhilePatterns&&(this._cachedCompiledWhilePatterns.dispose(),this._cachedCompiledWhilePatterns=null)}get debugBeginRegExp(){return`${this._begin.source}`}get debugWhileRegExp(){return`${this._while.source}`}getWhileWithResolvedBackReferences(n,e){return this._while.resolveBackReferences(n,e)}collectPatterns(n,e){e.push(this._begin)}compile(n,e){return this._getCachedCompiledPatterns(n).compile(n)}compileAG(n,e,t,r){return this._getCachedCompiledPatterns(n).compileAG(n,t,r)}_getCachedCompiledPatterns(n){if(!this._cachedCompiledPatterns){this._cachedCompiledPatterns=new K;for(const e of this.patterns)n.getRule(e).collectPatterns(n,this._cachedCompiledPatterns)}return this._cachedCompiledPatterns}compileWhile(n,e){return this._getCachedCompiledWhilePatterns(n,e).compile(n)}compileWhileAG(n,e,t,r){return this._getCachedCompiledWhilePatterns(n,e).compileAG(n,t,r)}_getCachedCompiledWhilePatterns(n,e){return this._cachedCompiledWhilePatterns||(this._cachedCompiledWhilePatterns=new K,this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences?this._while.clone():this._while)),this._while.hasBackReferences&&this._cachedCompiledWhilePatterns.setSource(0,e||"￿"),this._cachedCompiledWhilePatterns}},vt=class N{static createCaptureRule(e,t,r,s,i){return e.registerRule(a=>new qn(t,a,r,s,i))}static getCompiledRuleId(e,t,r){return e.id||t.registerRule(s=>{if(e.id=s,e.match)return new zn(e.$vscodeTextmateLocation,e.id,e.name,e.match,N._compileCaptures(e.captures,t,r));if(typeof e.begin>"u"){e.repository&&(r=_t({},r,e.repository));let i=e.patterns;return typeof i>"u"&&e.include&&(i=[{include:e.include}]),new Ze(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,N._compilePatterns(i,t,r))}return e.while?new ue(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,N._compileCaptures(e.beginCaptures||e.captures,t,r),e.while,N._compileCaptures(e.whileCaptures||e.captures,t,r),N._compilePatterns(e.patterns,t,r)):new Pe(e.$vscodeTextmateLocation,e.id,e.name,e.contentName,e.begin,N._compileCaptures(e.beginCaptures||e.captures,t,r),e.end,N._compileCaptures(e.endCaptures||e.captures,t,r),e.applyEndPatternLast,N._compilePatterns(e.patterns,t,r))}),e.id}static _compileCaptures(e,t,r){let s=[];if(e){let i=0;for(const a in e){if(a==="$vscodeTextmateLocation")continue;const c=parseInt(a,10);c>i&&(i=c)}for(let a=0;a<=i;a++)s[a]=null;for(const a in e){if(a==="$vscodeTextmateLocation")continue;const c=parseInt(a,10);let o=0;e[a].patterns&&(o=N.getCompiledRuleId(e[a],t,r)),s[c]=N.createCaptureRule(t,e[a].$vscodeTextmateLocation,e[a].name,e[a].contentName,o)}}return s}static _compilePatterns(e,t,r){let s=[];if(e)for(let i=0,a=e.length;i<a;i++){const c=e[i];let o=-1;if(c.include){const l=Tt(c.include);switch(l.kind){case 0:case 1:o=N.getCompiledRuleId(r[c.include],t,r);break;case 2:let u=r[l.ruleName];u&&(o=N.getCompiledRuleId(u,t,r));break;case 3:case 4:const h=l.scopeName,g=l.kind===4?l.ruleName:null,f=t.getExternalGrammar(h,r);if(f)if(g){let d=f.repository[g];d&&(o=N.getCompiledRuleId(d,t,f.repository))}else o=N.getCompiledRuleId(f.repository.$self,t,f.repository);break}}else o=N.getCompiledRuleId(c,t,r);if(o!==-1){const l=t.getRule(o);let u=!1;if((l instanceof Ze||l instanceof Pe||l instanceof ue)&&l.hasMissingPatterns&&l.patterns.length===0&&(u=!0),u)continue;s.push(o)}}return{patterns:s,hasMissingPatterns:(e?e.length:0)!==s.length}}},V=class It{source;ruleId;hasAnchor;hasBackReferences;_anchorCache;constructor(e,t){if(e&&typeof e=="string"){const r=e.length;let s=0,i=[],a=!1;for(let c=0;c<r;c++)if(e.charAt(c)==="\\"&&c+1<r){const l=e.charAt(c+1);l==="z"?(i.push(e.substring(s,c)),i.push("$(?!\\n)(?<!\\n)"),s=c+2):(l==="A"||l==="G")&&(a=!0),c++}this.hasAnchor=a,s===0?this.source=e:(i.push(e.substring(s,r)),this.source=i.join(""))}else this.hasAnchor=!1,this.source=e;this.hasAnchor?this._anchorCache=this._buildAnchorCache():this._anchorCache=null,this.ruleId=t,typeof this.source=="string"?this.hasBackReferences=Hn.test(this.source):this.hasBackReferences=!1}clone(){return new It(this.source,this.ruleId)}setSource(e){this.source!==e&&(this.source=e,this.hasAnchor&&(this._anchorCache=this._buildAnchorCache()))}resolveBackReferences(e,t){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let r=t.map(s=>e.substring(s.start,s.end));return Xe.lastIndex=0,this.source.replace(Xe,(s,i)=>wt(r[parseInt(i,10)]||""))}_buildAnchorCache(){if(typeof this.source!="string")throw new Error("This method should only be called if the source is a string");let e=[],t=[],r=[],s=[],i,a,c,o;for(i=0,a=this.source.length;i<a;i++)c=this.source.charAt(i),e[i]=c,t[i]=c,r[i]=c,s[i]=c,c==="\\"&&i+1<a&&(o=this.source.charAt(i+1),o==="A"?(e[i+1]="￿",t[i+1]="￿",r[i+1]="A",s[i+1]="A"):o==="G"?(e[i+1]="￿",t[i+1]="G",r[i+1]="￿",s[i+1]="G"):(e[i+1]=o,t[i+1]=o,r[i+1]=o,s[i+1]=o),i++);return{A0_G0:e.join(""),A0_G1:t.join(""),A1_G0:r.join(""),A1_G1:s.join("")}}resolveAnchors(e,t){return!this.hasAnchor||!this._anchorCache||typeof this.source!="string"?this.source:e?t?this._anchorCache.A1_G1:this._anchorCache.A1_G0:t?this._anchorCache.A0_G1:this._anchorCache.A0_G0}},K=class{_items;_hasAnchors;_cached;_anchorCache;constructor(){this._items=[],this._hasAnchors=!1,this._cached=null,this._anchorCache={A0_G0:null,A0_G1:null,A1_G0:null,A1_G1:null}}dispose(){this._disposeCaches()}_disposeCaches(){this._cached&&(this._cached.dispose(),this._cached=null),this._anchorCache.A0_G0&&(this._anchorCache.A0_G0.dispose(),this._anchorCache.A0_G0=null),this._anchorCache.A0_G1&&(this._anchorCache.A0_G1.dispose(),this._anchorCache.A0_G1=null),this._anchorCache.A1_G0&&(this._anchorCache.A1_G0.dispose(),this._anchorCache.A1_G0=null),this._anchorCache.A1_G1&&(this._anchorCache.A1_G1.dispose(),this._anchorCache.A1_G1=null)}push(n){this._items.push(n),this._hasAnchors=this._hasAnchors||n.hasAnchor}unshift(n){this._items.unshift(n),this._hasAnchors=this._hasAnchors||n.hasAnchor}length(){return this._items.length}setSource(n,e){this._items[n].source!==e&&(this._disposeCaches(),this._items[n].setSource(e))}compile(n){if(!this._cached){let e=this._items.map(t=>t.source);this._cached=new et(n,e,this._items.map(t=>t.ruleId))}return this._cached}compileAG(n,e,t){return this._hasAnchors?e?t?(this._anchorCache.A1_G1||(this._anchorCache.A1_G1=this._resolveAnchors(n,e,t)),this._anchorCache.A1_G1):(this._anchorCache.A1_G0||(this._anchorCache.A1_G0=this._resolveAnchors(n,e,t)),this._anchorCache.A1_G0):t?(this._anchorCache.A0_G1||(this._anchorCache.A0_G1=this._resolveAnchors(n,e,t)),this._anchorCache.A0_G1):(this._anchorCache.A0_G0||(this._anchorCache.A0_G0=this._resolveAnchors(n,e,t)),this._anchorCache.A0_G0):this.compile(n)}_resolveAnchors(n,e,t){let r=this._items.map(s=>s.resolveAnchors(e,t));return new et(n,r,this._items.map(s=>s.ruleId))}},et=class{constructor(n,e,t){this.regExps=e,this.rules=t,this.scanner=n.createOnigScanner(e)}scanner;dispose(){typeof this.scanner.dispose=="function"&&this.scanner.dispose()}toString(){const n=[];for(let e=0,t=this.rules.length;e<t;e++)n.push(" - "+this.rules[e]+": "+this.regExps[e]);return n.join(`
2
2
  `)}findNextMatchSync(n,e,t){const r=this.scanner.findNextMatchSync(n,e,t);return r?{ruleId:this.rules[r.index],captureIndices:r.captureIndices}:null}},Re=class{constructor(n,e){this.languageId=n,this.tokenType=e}},Vn=class Le{_defaultAttributes;_embeddedLanguagesMatcher;constructor(e,t){this._defaultAttributes=new Re(e,8),this._embeddedLanguagesMatcher=new Kn(Object.entries(t||{}))}getDefaultAttributes(){return this._defaultAttributes}getBasicScopeAttributes(e){return e===null?Le._NULL_SCOPE_METADATA:this._getBasicScopeAttributes.get(e)}static _NULL_SCOPE_METADATA=new Re(0,0);_getBasicScopeAttributes=new Ct(e=>{const t=this._scopeToLanguage(e),r=this._toStandardTokenType(e);return new Re(t,r)});_scopeToLanguage(e){return this._embeddedLanguagesMatcher.match(e)||0}_toStandardTokenType(e){const t=e.match(Le.STANDARD_TOKEN_TYPE_REGEXP);if(!t)return 8;switch(t[1]){case"comment":return 1;case"string":return 2;case"regex":return 3;case"meta.embedded":return 0}throw new Error("Unexpected match for standard token type!")}static STANDARD_TOKEN_TYPE_REGEXP=/\b(comment|string|regex|meta\.embedded)\b/},Kn=class{values;scopesRegExp;constructor(n){if(n.length===0)this.values=null,this.scopesRegExp=null;else{this.values=new Map(n);const e=n.map(([t,r])=>wt(t));e.sort(),e.reverse(),this.scopesRegExp=new RegExp(`^((${e.join(")|(")}))($|\\.)`,"")}}match(n){if(!this.scopesRegExp)return;const e=n.match(this.scopesRegExp);if(e)return this.values.get(e[1])}},tt=class{constructor(n,e){this.stack=n,this.stoppedEarly=e}};function Et(n,e,t,r,s,i,a,c){const o=e.content.length;let l=!1,u=-1;if(a){const f=Jn(n,e,t,r,s,i);s=f.stack,r=f.linePos,t=f.isFirstLine,u=f.anchorPosition}const h=Date.now();for(;!l;){if(c!==0&&Date.now()-h>c)return new tt(s,!0);g()}return new tt(s,!1);function g(){const f=Yn(n,e,t,r,s,u);if(!f){i.produce(s,o),l=!0;return}const d=f.captureIndices,b=f.matchedRuleId,m=d&&d.length>0?d[0].end>r:!1;if(b===Fn){const _=s.getRule(n);i.produce(s,d[0].start),s=s.withContentNameScopesList(s.nameScopesList),F(n,e,t,s,i,_.endCaptures,d),i.produce(s,d[0].end);const p=s;if(s=s.parent,u=p.getAnchorPos(),!m&&p.getEnterPos()===r){s=p,i.produce(s,o),l=!0;return}}else{const _=n.getRule(b);i.produce(s,d[0].start);const p=s,y=_.getName(e.content,d),w=s.contentNameScopesList.pushAttributed(y,n);if(s=s.push(b,r,u,d[0].end===o,null,w,w),_ instanceof Pe){const S=_;F(n,e,t,s,i,S.beginCaptures,d),i.produce(s,d[0].end),u=d[0].end;const v=S.getContentName(e.content,d),G=w.pushAttributed(v,n);if(s=s.withContentNameScopesList(G),S.endHasBackReferences&&(s=s.withEndRule(S.getEndWithResolvedBackReferences(e.content,d))),!m&&p.hasSameRuleAs(s)){s=s.pop(),i.produce(s,o),l=!0;return}}else if(_ instanceof ue){const S=_;F(n,e,t,s,i,S.beginCaptures,d),i.produce(s,d[0].end),u=d[0].end;const v=S.getContentName(e.content,d),G=w.pushAttributed(v,n);if(s=s.withContentNameScopesList(G),S.whileHasBackReferences&&(s=s.withEndRule(S.getWhileWithResolvedBackReferences(e.content,d))),!m&&p.hasSameRuleAs(s)){s=s.pop(),i.produce(s,o),l=!0;return}}else if(F(n,e,t,s,i,_.captures,d),i.produce(s,d[0].end),s=s.pop(),!m){s=s.safePop(),i.produce(s,o),l=!0;return}}d[0].end>r&&(r=d[0].end,t=!1)}}function Jn(n,e,t,r,s,i){let a=s.beginRuleCapturedEOL?0:-1;const c=[];for(let o=s;o;o=o.pop()){const l=o.getRule(n);l instanceof ue&&c.push({rule:l,stack:o})}for(let o=c.pop();o;o=c.pop()){const{ruleScanner:l,findOptions:u}=Zn(o.rule,n,o.stack.endRule,t,r===a),h=l.findNextMatchSync(e,r,u);if(h){if(h.ruleId!==At){s=o.stack.pop();break}h.captureIndices&&h.captureIndices.length&&(i.produce(o.stack,h.captureIndices[0].start),F(n,e,t,o.stack,i,o.rule.whileCaptures,h.captureIndices),i.produce(o.stack,h.captureIndices[0].end),a=h.captureIndices[0].end,h.captureIndices[0].end>r&&(r=h.captureIndices[0].end,t=!1))}else{s=o.stack.pop();break}}return{stack:s,linePos:r,anchorPosition:a,isFirstLine:t}}function Yn(n,e,t,r,s,i){const a=Qn(n,e,t,r,s,i),c=n.getInjections();if(c.length===0)return a;const o=Xn(c,n,e,t,r,s,i);if(!o)return a;if(!a)return o;const l=a.captureIndices[0].start,u=o.captureIndices[0].start;return u<l||o.priorityMatch&&u===l?o:a}function Qn(n,e,t,r,s,i){const a=s.getRule(n),{ruleScanner:c,findOptions:o}=Pt(a,n,s.endRule,t,r===i),l=c.findNextMatchSync(e,r,o);return l?{captureIndices:l.captureIndices,matchedRuleId:l.ruleId}:null}function Xn(n,e,t,r,s,i,a){let c=Number.MAX_VALUE,o=null,l,u=0;const h=i.contentNameScopesList.getScopeNames();for(let g=0,f=n.length;g<f;g++){const d=n[g];if(!d.matcher(h))continue;const b=e.getRule(d.ruleId),{ruleScanner:m,findOptions:_}=Pt(b,e,null,r,s===a),p=m.findNextMatchSync(t,s,_);if(!p)continue;const y=p.captureIndices[0].start;if(!(y>=c)&&(c=y,o=p.captureIndices,l=p.ruleId,u=d.priority,c===s))break}return o?{priorityMatch:u===-1,captureIndices:o,matchedRuleId:l}:null}function Pt(n,e,t,r,s){return{ruleScanner:n.compileAG(e,t,r,s),findOptions:0}}function Zn(n,e,t,r,s){return{ruleScanner:n.compileWhileAG(e,t,r,s),findOptions:0}}function F(n,e,t,r,s,i,a){if(i.length===0)return;const c=e.content,o=Math.min(i.length,a.length),l=[],u=a[0].end;for(let h=0;h<o;h++){const g=i[h];if(g===null)continue;const f=a[h];if(f.length===0)continue;if(f.start>u)break;for(;l.length>0&&l[l.length-1].endPos<=f.start;)s.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop();if(l.length>0?s.produceFromScopes(l[l.length-1].scopes,f.start):s.produce(r,f.start),g.retokenizeCapturedWithRuleId){const b=g.getName(c,a),m=r.contentNameScopesList.pushAttributed(b,n),_=g.getContentName(c,a),p=m.pushAttributed(_,n),y=r.push(g.retokenizeCapturedWithRuleId,f.start,-1,!1,null,m,p),w=n.createOnigString(c.substring(0,f.end));Et(n,w,t&&f.start===0,f.start,y,s,!1,0),Nt(w);continue}const d=g.getName(c,a);if(d!==null){const m=(l.length>0?l[l.length-1].scopes:r.contentNameScopesList).pushAttributed(d,n);l.push(new er(m,f.end))}}for(;l.length>0;)s.produceFromScopes(l[l.length-1].scopes,l[l.length-1].endPos),l.pop()}var er=class{scopes;endPos;constructor(n,e){this.scopes=n,this.endPos=e}};function tr(n,e,t,r,s,i,a,c){return new rr(n,e,t,r,s,i,a,c)}function nt(n,e,t,r,s){const i=ce(e,he),a=vt.getCompiledRuleId(t,r,s.repository);for(const c of i)n.push({debugSelector:e,matcher:c.matcher,ruleId:a,grammar:s,priority:c.priority})}function he(n,e){if(e.length<n.length)return!1;let t=0;return n.every(r=>{for(let s=t;s<e.length;s++)if(nr(e[s],r))return t=s+1,!0;return!1})}function nr(n,e){if(!n)return!1;if(n===e)return!0;const t=e.length;return n.length>t&&n.substr(0,t)===e&&n[t]==="."}var rr=class{constructor(n,e,t,r,s,i,a,c){if(this._rootScopeName=n,this.balancedBracketSelectors=i,this._onigLib=c,this._basicScopeAttributesProvider=new Vn(t,r),this._rootId=-1,this._lastRuleId=0,this._ruleId2desc=[null],this._includedGrammars={},this._grammarRepository=a,this._grammar=rt(e,null),this._injections=null,this._tokenTypeMatchers=[],s)for(const o of Object.keys(s)){const l=ce(o,he);for(const u of l)this._tokenTypeMatchers.push({matcher:u.matcher,type:s[o]})}}_rootId;_lastRuleId;_ruleId2desc;_includedGrammars;_grammarRepository;_grammar;_injections;_basicScopeAttributesProvider;_tokenTypeMatchers;get themeProvider(){return this._grammarRepository}dispose(){for(const n of this._ruleId2desc)n&&n.dispose()}createOnigScanner(n){return this._onigLib.createOnigScanner(n)}createOnigString(n){return this._onigLib.createOnigString(n)}getMetadataForScope(n){return this._basicScopeAttributesProvider.getBasicScopeAttributes(n)}_collectInjections(){const n={lookup:s=>s===this._rootScopeName?this._grammar:this.getExternalGrammar(s),injections:s=>this._grammarRepository.injections(s)},e=[],t=this._rootScopeName,r=n.lookup(t);if(r){const s=r.injections;if(s)for(let a in s)nt(e,a,s[a],this,r);const i=this._grammarRepository.injections(t);i&&i.forEach(a=>{const c=this.getExternalGrammar(a);if(c){const o=c.injectionSelector;o&&nt(e,o,c,this,c)}})}return e.sort((s,i)=>s.priority-i.priority),e}getInjections(){return this._injections===null&&(this._injections=this._collectInjections()),this._injections}registerRule(n){const e=++this._lastRuleId,t=n(e);return this._ruleId2desc[e]=t,t}getRule(n){return this._ruleId2desc[n]}getExternalGrammar(n,e){if(this._includedGrammars[n])return this._includedGrammars[n];if(this._grammarRepository){const t=this._grammarRepository.lookup(n);if(t)return this._includedGrammars[n]=rt(t,e&&e.$base),this._includedGrammars[n]}}tokenizeLine(n,e,t=0){const r=this._tokenize(n,e,!1,t);return{tokens:r.lineTokens.getResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}tokenizeLine2(n,e,t=0){const r=this._tokenize(n,e,!0,t);return{tokens:r.lineTokens.getBinaryResult(r.ruleStack,r.lineLength),ruleStack:r.ruleStack,stoppedEarly:r.stoppedEarly}}_tokenize(n,e,t,r){this._rootId===-1&&(this._rootId=vt.getCompiledRuleId(this._grammar.repository.$self,this,this._grammar.repository),this.getInjections());let s;if(!e||e===xe.NULL){s=!0;const l=this._basicScopeAttributesProvider.getDefaultAttributes(),u=this.themeProvider.getDefaults(),h=W.set(0,l.languageId,l.tokenType,null,u.fontStyle,u.foregroundId,u.backgroundId),g=this.getRule(this._rootId).getName(null,null);let f;g?f=q.createRootAndLookUpScopeName(g,h,this):f=q.createRoot("unknown",h),e=new xe(null,this._rootId,-1,-1,!1,null,f,f)}else s=!1,e.reset();n=n+`
3
3
  `;const i=this.createOnigString(n),a=i.content.length,c=new ir(t,n,this._tokenTypeMatchers,this.balancedBracketSelectors),o=Et(this,i,s,0,e,c,!0,r);return Nt(i),{lineLength:a,lineTokens:c,ruleStack:o.stack,stoppedEarly:o.stoppedEarly}}};function rt(n,e){return n=Cn(n),n.repository=n.repository||{},n.repository.$self={$vscodeTextmateLocation:n.$vscodeTextmateLocation,patterns:n.patterns,name:n.scopeName},n.repository.$base=e||n.repository.$self,n}var q=class P{constructor(e,t,r){this.parent=e,this.scopePath=t,this.tokenAttributes=r}static fromExtension(e,t){let r=e,s=e?.scopePath??null;for(const i of t)s=ke.push(s,i.scopeNames),r=new P(r,s,i.encodedTokenAttributes);return r}static createRoot(e,t){return new P(null,new ke(null,e),t)}static createRootAndLookUpScopeName(e,t,r){const s=r.getMetadataForScope(e),i=new ke(null,e),a=r.themeProvider.themeMatch(i),c=P.mergeAttributes(t,s,a);return new P(null,i,c)}get scopeName(){return this.scopePath.scopeName}toString(){return this.getScopeNames().join(" ")}equals(e){return P.equals(this,e)}static equals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.scopeName!==t.scopeName||e.tokenAttributes!==t.tokenAttributes)return!1;e=e.parent,t=t.parent}while(!0)}static mergeAttributes(e,t,r){let s=-1,i=0,a=0;return r!==null&&(s=r.fontStyle,i=r.foregroundId,a=r.backgroundId),W.set(e,t.languageId,t.tokenType,null,s,i,a)}pushAttributed(e,t){if(e===null)return this;if(e.indexOf(" ")===-1)return P._pushAttributed(this,e,t);const r=e.split(/ /g);let s=this;for(const i of r)s=P._pushAttributed(s,i,t);return s}static _pushAttributed(e,t,r){const s=r.getMetadataForScope(t),i=e.scopePath.push(t),a=r.themeProvider.themeMatch(i),c=P.mergeAttributes(e.tokenAttributes,s,a);return new P(e,i,c)}getScopeNames(){return this.scopePath.getSegments()}getExtensionIfDefined(e){const t=[];let r=this;for(;r&&r!==e;)t.push({encodedTokenAttributes:r.tokenAttributes,scopeNames:r.scopePath.getExtensionIfDefined(r.parent?.scopePath??null)}),r=r.parent;return r===e?t.reverse():void 0}},xe=class B{constructor(e,t,r,s,i,a,c,o){this.parent=e,this.ruleId=t,this.beginRuleCapturedEOL=i,this.endRule=a,this.nameScopesList=c,this.contentNameScopesList=o,this.depth=this.parent?this.parent.depth+1:1,this._enterPos=r,this._anchorPos=s}_stackElementBrand=void 0;static NULL=new B(null,0,0,0,!1,null,null,null);_enterPos;_anchorPos;depth;equals(e){return e===null?!1:B._equals(this,e)}static _equals(e,t){return e===t?!0:this._structuralEquals(e,t)?q.equals(e.contentNameScopesList,t.contentNameScopesList):!1}static _structuralEquals(e,t){do{if(e===t||!e&&!t)return!0;if(!e||!t||e.depth!==t.depth||e.ruleId!==t.ruleId||e.endRule!==t.endRule)return!1;e=e.parent,t=t.parent}while(!0)}clone(){return this}static _reset(e){for(;e;)e._enterPos=-1,e._anchorPos=-1,e=e.parent}reset(){B._reset(this)}pop(){return this.parent}safePop(){return this.parent?this.parent:this}push(e,t,r,s,i,a,c){return new B(this,e,t,r,s,i,a,c)}getEnterPos(){return this._enterPos}getAnchorPos(){return this._anchorPos}getRule(e){return e.getRule(this.ruleId)}toString(){const e=[];return this._writeString(e,0),"["+e.join(",")+"]"}_writeString(e,t){return this.parent&&(t=this.parent._writeString(e,t)),e[t++]=`(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`,t}withContentNameScopesList(e){return this.contentNameScopesList===e?this:this.parent.push(this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,this.endRule,this.nameScopesList,e)}withEndRule(e){return this.endRule===e?this:new B(this.parent,this.ruleId,this._enterPos,this._anchorPos,this.beginRuleCapturedEOL,e,this.nameScopesList,this.contentNameScopesList)}hasSameRuleAs(e){let t=this;for(;t&&t._enterPos===e._enterPos;){if(t.ruleId===e.ruleId)return!0;t=t.parent}return!1}toStateStackFrame(){return{ruleId:this.ruleId,beginRuleCapturedEOL:this.beginRuleCapturedEOL,endRule:this.endRule,nameScopesList:this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList??null)??[],contentNameScopesList:this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList)??[]}}static pushFrame(e,t){const r=q.fromExtension(e?.nameScopesList??null,t.nameScopesList);return new B(e,t.ruleId,t.enterPos??-1,t.anchorPos??-1,t.beginRuleCapturedEOL,t.endRule,r,q.fromExtension(r,t.contentNameScopesList))}},sr=class{balancedBracketScopes;unbalancedBracketScopes;allowAny=!1;constructor(n,e){this.balancedBracketScopes=n.flatMap(t=>t==="*"?(this.allowAny=!0,[]):ce(t,he).map(r=>r.matcher)),this.unbalancedBracketScopes=e.flatMap(t=>ce(t,he).map(r=>r.matcher))}get matchesAlways(){return this.allowAny&&this.unbalancedBracketScopes.length===0}get matchesNever(){return this.balancedBracketScopes.length===0&&!this.allowAny}match(n){for(const e of this.unbalancedBracketScopes)if(e(n))return!1;for(const e of this.balancedBracketScopes)if(e(n))return!0;return this.allowAny}},ir=class{constructor(n,e,t,r){this.balancedBracketSelectors=r,this._emitBinaryTokens=n,this._tokenTypeOverrides=t,this._lineText=null,this._tokens=[],this._binaryTokens=[],this._lastTokenEndIndex=0}_emitBinaryTokens;_lineText;_tokens;_binaryTokens;_lastTokenEndIndex;_tokenTypeOverrides;produce(n,e){this.produceFromScopes(n.contentNameScopesList,e)}produceFromScopes(n,e){if(this._lastTokenEndIndex>=e)return;if(this._emitBinaryTokens){let r=n?.tokenAttributes??0,s=!1;if(this.balancedBracketSelectors?.matchesAlways&&(s=!0),this._tokenTypeOverrides.length>0||this.balancedBracketSelectors&&!this.balancedBracketSelectors.matchesAlways&&!this.balancedBracketSelectors.matchesNever){const i=n?.getScopeNames()??[];for(const a of this._tokenTypeOverrides)a.matcher(i)&&(r=W.set(r,0,a.type,null,-1,0,0));this.balancedBracketSelectors&&(s=this.balancedBracketSelectors.match(i))}if(s&&(r=W.set(r,0,8,s,-1,0,0)),this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-1]===r){this._lastTokenEndIndex=e;return}this._binaryTokens.push(this._lastTokenEndIndex),this._binaryTokens.push(r),this._lastTokenEndIndex=e;return}const t=n?.getScopeNames()??[];this._tokens.push({startIndex:this._lastTokenEndIndex,endIndex:e,scopes:t}),this._lastTokenEndIndex=e}getResult(n,e){return this._tokens.length>0&&this._tokens[this._tokens.length-1].startIndex===e-1&&this._tokens.pop(),this._tokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(n,e),this._tokens[this._tokens.length-1].startIndex=0),this._tokens}getBinaryResult(n,e){this._binaryTokens.length>0&&this._binaryTokens[this._binaryTokens.length-2]===e-1&&(this._binaryTokens.pop(),this._binaryTokens.pop()),this._binaryTokens.length===0&&(this._lastTokenEndIndex=-1,this.produce(n,e),this._binaryTokens[this._binaryTokens.length-2]=0);const t=new Uint32Array(this._binaryTokens.length);for(let r=0,s=this._binaryTokens.length;r<s;r++)t[r]=this._binaryTokens[r];return t}},ar=class{constructor(n,e){this._onigLib=e,this._theme=n}_grammars=new Map;_rawGrammars=new Map;_injectionGrammars=new Map;_theme;dispose(){for(const n of this._grammars.values())n.dispose()}setTheme(n){this._theme=n}getColorMap(){return this._theme.getColorMap()}addGrammar(n,e){this._rawGrammars.set(n.scopeName,n),e&&this._injectionGrammars.set(n.scopeName,e)}lookup(n){return this._rawGrammars.get(n)}injections(n){return this._injectionGrammars.get(n)}getDefaults(){return this._theme.getDefaults()}themeMatch(n){return this._theme.match(n)}grammarForScopeName(n,e,t,r,s){if(!this._grammars.has(n)){let i=this._rawGrammars.get(n);if(!i)return null;this._grammars.set(n,tr(n,i,e,t,r,s,this,this._onigLib))}return this._grammars.get(n)}},or=class{_options;_syncRegistry;_ensureGrammarCache;constructor(e){this._options=e,this._syncRegistry=new ar(oe.createFromRawTheme(e.theme,e.colorMap),e.onigLib),this._ensureGrammarCache=new Map}dispose(){this._syncRegistry.dispose()}setTheme(e,t){this._syncRegistry.setTheme(oe.createFromRawTheme(e,t))}getColorMap(){return this._syncRegistry.getColorMap()}loadGrammarWithEmbeddedLanguages(e,t,r){return this.loadGrammarWithConfiguration(e,t,{embeddedLanguages:r})}loadGrammarWithConfiguration(e,t,r){return this._loadGrammar(e,t,r.embeddedLanguages,r.tokenTypes,new sr(r.balancedBracketSelectors||[],r.unbalancedBracketSelectors||[]))}loadGrammar(e){return this._loadGrammar(e,0,null,null,null)}_loadGrammar(e,t,r,s,i){const a=new Bn(this._syncRegistry,e);for(;a.Q.length>0;)a.Q.map(c=>this._loadSingleGrammar(c.scopeName)),a.processQueue();return this._grammarForScopeName(e,t,r,s,i)}_loadSingleGrammar(e){this._ensureGrammarCache.has(e)||(this._doLoadSingleGrammar(e),this._ensureGrammarCache.set(e,!0))}_doLoadSingleGrammar(e){const t=this._options.loadGrammar(e);if(t){const r=typeof this._options.getInjections=="function"?this._options.getInjections(e):void 0;this._syncRegistry.addGrammar(t,r)}}addGrammar(e,t=[],r=0,s=null){return this._syncRegistry.addGrammar(e,t),this._grammarForScopeName(e.scopeName,r,s)}_grammarForScopeName(e,t=0,r=null,s=null,i=null){return this._syncRegistry.grammarForScopeName(e,t,r,s,i)}},Oe=xe.NULL;const cr=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"],st={}.hasOwnProperty;function lr(n,e){const t=e||{};function r(s,...i){let a=r.invalid;const c=r.handlers;if(s&&st.call(s,n)){const o=String(s[n]);a=st.call(c,o)?c[o]:r.unknown}if(a)return a.call(this,s,...i)}return r.handlers=t.handlers||{},r.invalid=t.invalid,r.unknown=t.unknown,r}const ur=/["&'<>`]/g,hr=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,fr=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,dr=/[|\\{}()[\]^$+*?.]/g,it=new WeakMap;function gr(n,e){if(n=n.replace(e.subset?mr(e.subset):ur,r),e.subset||e.escapeOnly)return n;return n.replace(hr,t).replace(fr,r);function t(s,i,a){return e.format((s.charCodeAt(0)-55296)*1024+s.charCodeAt(1)-56320+65536,a.charCodeAt(i+2),e)}function r(s,i,a){return e.format(s.charCodeAt(0),a.charCodeAt(i+1),e)}}function mr(n){let e=it.get(n);return e||(e=pr(n),it.set(n,e)),e}function pr(n){const e=[];let t=-1;for(;++t<n.length;)e.push(n[t].replace(dr,"\\$&"));return new RegExp("(?:"+e.join("|")+")","g")}const _r=/[\dA-Fa-f]/;function yr(n,e,t){const r="&#x"+n.toString(16).toUpperCase();return t&&e&&!_r.test(String.fromCharCode(e))?r:r+";"}const br=/\d/;function Sr(n,e,t){const r="&#"+String(n);return t&&e&&!br.test(String.fromCharCode(e))?r:r+";"}const wr=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"],Ne={nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",fnof:"ƒ",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",bull:"•",hellip:"…",prime:"′",Prime:"″",oline:"‾",frasl:"⁄",weierp:"℘",image:"ℑ",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",quot:'"',amp:"&",lt:"<",gt:">",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",permil:"‰",lsaquo:"‹",rsaquo:"›",euro:"€"},Cr=["cent","copy","divide","gt","lt","not","para","times"],Lt={}.hasOwnProperty,Ge={};let ne;for(ne in Ne)Lt.call(Ne,ne)&&(Ge[Ne[ne]]=ne);const kr=/[^\dA-Za-z]/;function Rr(n,e,t,r){const s=String.fromCharCode(n);if(Lt.call(Ge,s)){const i=Ge[s],a="&"+i;return t&&wr.includes(i)&&!Cr.includes(i)&&(!r||e&&e!==61&&kr.test(String.fromCharCode(e)))?a:a+";"}return""}function Nr(n,e,t){let r=yr(n,e,t.omitOptionalSemicolons),s;if((t.useNamedReferences||t.useShortestReferences)&&(s=Rr(n,e,t.omitOptionalSemicolons,t.attribute)),(t.useShortestReferences||!s)&&t.useShortestReferences){const i=Sr(n,e,t.omitOptionalSemicolons);i.length<r.length&&(r=i)}return s&&(!t.useShortestReferences||s.length<r.length)?s:r}function U(n,e){return gr(n,Object.assign({format:Nr},e))}const Tr=/^>|^->|<!--|-->|--!>|<!-$/g,Ar=[">"],vr=["<",">"];function Ir(n,e,t,r){return r.settings.bogusComments?"<?"+U(n.value,Object.assign({},r.settings.characterReferences,{subset:Ar}))+">":"<!--"+n.value.replace(Tr,s)+"-->";function s(i){return U(i,Object.assign({},r.settings.characterReferences,{subset:vr}))}}function Er(n,e,t,r){return"<!"+(r.settings.upperDoctype?"DOCTYPE":"doctype")+(r.settings.tightDoctype?"":" ")+"html>"}const k=Ot(1),xt=Ot(-1),Pr=[];function Ot(n){return e;function e(t,r,s){const i=t?t.children:Pr;let a=(r||0)+n,c=i[a];if(!s)for(;c&&Be(c);)a+=n,c=i[a];return c}}const Lr={}.hasOwnProperty;function Gt(n){return e;function e(t,r,s){return Lr.call(n,t.tagName)&&n[t.tagName](t,r,s)}}const Ue=Gt({body:Or,caption:Te,colgroup:Te,dd:$r,dt:Mr,head:Te,html:xr,li:Br,optgroup:jr,option:Ur,p:Gr,rp:at,rt:at,tbody:Dr,td:ot,tfoot:Hr,th:ot,thead:Wr,tr:Fr});function Te(n,e,t){const r=k(t,e,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&Be(r.value.charAt(0)))}function xr(n,e,t){const r=k(t,e);return!r||r.type!=="comment"}function Or(n,e,t){const r=k(t,e);return!r||r.type!=="comment"}function Gr(n,e,t){const r=k(t,e);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!t||!(t.type==="element"&&(t.tagName==="a"||t.tagName==="audio"||t.tagName==="del"||t.tagName==="ins"||t.tagName==="map"||t.tagName==="noscript"||t.tagName==="video"))}function Br(n,e,t){const r=k(t,e);return!r||r.type==="element"&&r.tagName==="li"}function Mr(n,e,t){const r=k(t,e);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function $r(n,e,t){const r=k(t,e);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function at(n,e,t){const r=k(t,e);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function jr(n,e,t){const r=k(t,e);return!r||r.type==="element"&&r.tagName==="optgroup"}function Ur(n,e,t){const r=k(t,e);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function Wr(n,e,t){const r=k(t,e);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function Dr(n,e,t){const r=k(t,e);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function Hr(n,e,t){return!k(t,e)}function Fr(n,e,t){const r=k(t,e);return!r||r.type==="element"&&r.tagName==="tr"}function ot(n,e,t){const r=k(t,e);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}const qr=Gt({body:Kr,colgroup:Jr,head:Vr,html:zr,tbody:Yr});function zr(n){const e=k(n,-1);return!e||e.type!=="comment"}function Vr(n){const e=new Set;for(const r of n.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(e.has(r.tagName))return!1;e.add(r.tagName)}const t=n.children[0];return!t||t.type==="element"}function Kr(n){const e=k(n,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&Be(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function Jr(n,e,t){const r=xt(t,e),s=k(n,-1,!0);return t&&r&&r.type==="element"&&r.tagName==="colgroup"&&Ue(r,t.children.indexOf(r),t)?!1:!!(s&&s.type==="element"&&s.tagName==="col")}function Yr(n,e,t){const r=xt(t,e),s=k(n,-1);return t&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&Ue(r,t.children.indexOf(r),t)?!1:!!(s&&s.type==="element"&&s.tagName==="tr")}const re={name:[[`
4
4
  \f\r &/=>`.split(""),`
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-BNh36EOV.js","./preload-helper-PPVm8Dsz.js"])))=>i.map(i=>d[i]);
2
- import{_ as a}from"./preload-helper-PPVm8Dsz.js";(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))n(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const s of t.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function i(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function n(e){if(e.ep)return;e.ep=!0;const t=i(e);fetch(e.href,t)}})();const c=!1;function d(r){return r instanceof Error?r.stack||r.message:String(r)}function l(r,{showDetails:o=c}={}){const i=document.getElementById("root");if(!i||i.childElementCount>0)return;const n=document.createElement("main");n.setAttribute("role","alert"),n.style.cssText='min-height:100vh;background:#0b0d10;color:#f4f4f5;font-family:"Mona Sans",ui-sans-serif,system-ui,sans-serif;font-feature-settings:"ss06" on;padding:32px;box-sizing:border-box;';const e=document.createElement("h1");e.textContent="Mastra Studio failed to start",e.style.cssText="font-size:20px;line-height:1.4;margin:0 0 8px;";const t=document.createElement("p");if(t.textContent=o?"The startup module failed before React could render. Check the Vite terminal and browser console for the original request details.":"The startup module failed before React could render. Run Studio in development mode to view detailed diagnostics.",t.style.cssText="color:#a1a1aa;max-width:760px;margin:0 0 20px;line-height:1.6;",n.append(e,t),o){const s=document.createElement("pre");s.textContent=d(r),s.style.cssText="white-space:pre-wrap;overflow:auto;background:#18181b;border:1px solid #3f3f46;border-radius:8px;padding:16px;max-width:100%;line-height:1.5;",n.append(s)}i.replaceChildren(n)}try{const{startStudio:r}=await a(async()=>{const{startStudio:o}=await import("./main-BNh36EOV.js").then(i=>i.m);return{startStudio:o}},__vite__mapDeps([0,1]),import.meta.url);r()}catch(r){console.error("Mastra Studio failed to start",r),l(r)}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-DomdLuyE.js","./preload-helper-PPVm8Dsz.js"])))=>i.map(i=>d[i]);
2
+ import{_ as a}from"./preload-helper-PPVm8Dsz.js";(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))n(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const s of t.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&n(s)}).observe(document,{childList:!0,subtree:!0});function i(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function n(e){if(e.ep)return;e.ep=!0;const t=i(e);fetch(e.href,t)}})();const c=!1;function d(r){return r instanceof Error?r.stack||r.message:String(r)}function l(r,{showDetails:o=c}={}){const i=document.getElementById("root");if(!i||i.childElementCount>0)return;const n=document.createElement("main");n.setAttribute("role","alert"),n.style.cssText='min-height:100vh;background:#0b0d10;color:#f4f4f5;font-family:"Mona Sans",ui-sans-serif,system-ui,sans-serif;font-feature-settings:"ss06" on;padding:32px;box-sizing:border-box;';const e=document.createElement("h1");e.textContent="Mastra Studio failed to start",e.style.cssText="font-size:20px;line-height:1.4;margin:0 0 8px;";const t=document.createElement("p");if(t.textContent=o?"The startup module failed before React could render. Check the Vite terminal and browser console for the original request details.":"The startup module failed before React could render. Run Studio in development mode to view detailed diagnostics.",t.style.cssText="color:#a1a1aa;max-width:760px;margin:0 0 20px;line-height:1.6;",n.append(e,t),o){const s=document.createElement("pre");s.textContent=d(r),s.style.cssText="white-space:pre-wrap;overflow:auto;background:#18181b;border:1px solid #3f3f46;border-radius:8px;padding:16px;max-width:100%;line-height:1.5;",n.append(s)}i.replaceChildren(n)}try{const{startStudio:r}=await a(async()=>{const{startStudio:o}=await import("./main-DomdLuyE.js").then(i=>i.m);return{startStudio:o}},__vite__mapDeps([0,1]),import.meta.url);r()}catch(r){console.error("Mastra Studio failed to start",r),l(r)}