From 6f4542131c997454798bc554c5c21b5c7168d31e Mon Sep 17 00:00:00 2001 From: vutnguyen Date: Wed, 6 Aug 2025 17:44:44 +0700 Subject: [PATCH 01/18] update publish function --- .../src/server/api/routers/publish/manager.ts | 189 ++++++++++++++++-- 1 file changed, 169 insertions(+), 20 deletions(-) diff --git a/apps/web/client/src/server/api/routers/publish/manager.ts b/apps/web/client/src/server/api/routers/publish/manager.ts index f151d2743..1136b8cdb 100644 --- a/apps/web/client/src/server/api/routers/publish/manager.ts +++ b/apps/web/client/src/server/api/routers/publish/manager.ts @@ -237,54 +237,203 @@ export class PublishManager { } /** - * Serializes all files in a directory for deployment using parallel processing + * Serialize files from a directory into a record of file paths to their content + * Memory-optimized version using chunking + batching approach * @param currentDir - The directory path to serialize * @returns Record of file paths to their content (base64 for binary, utf-8 for text) */ private async serializeFiles(currentDir: string): Promise> { const timer = new LogTimer('File Serialization'); + const startTime = Date.now(); try { const allFilePaths = await this.getAllFilePathsFlat(currentDir); timer.log(`File discovery completed - ${allFilePaths.length} files found`); - const filteredPaths = allFilePaths.filter((filePath) => !this.shouldSkipFile(filePath)); + const filteredPaths = allFilePaths.filter(filePath => !this.shouldSkipFile(filePath)); + timer.log(`Filtered to ${filteredPaths.length} files after exclusions`); const { binaryFiles, textFiles } = this.categorizeFiles(filteredPaths); + timer.log(`Categorized: ${textFiles.length} text files, ${binaryFiles.length} binary files`); - const BATCH_SIZE = 50; const files: Record = {}; - + if (textFiles.length > 0) { - timer.log(`Processing ${textFiles.length} text files in batches of ${BATCH_SIZE}`); - for (let i = 0; i < textFiles.length; i += BATCH_SIZE) { - const batch = textFiles.slice(i, i + BATCH_SIZE); - const batchFiles = await this.processTextFilesBatch(batch, currentDir); - Object.assign(files, batchFiles); - } + timer.log(`Processing ${textFiles.length} text files using chunking + batching`); + const textResults = await this.processFilesWithChunkingAndBatching(textFiles, currentDir, false); + Object.assign(files, textResults); timer.log('Text files processing completed'); } if (binaryFiles.length > 0) { - timer.log( - `Processing ${binaryFiles.length} binary files in batches of ${BATCH_SIZE}`, - ); - for (let i = 0; i < binaryFiles.length; i += BATCH_SIZE) { - const batch = binaryFiles.slice(i, i + BATCH_SIZE); - const batchFiles = await this.processBinaryFilesBatch(batch, currentDir); - Object.assign(files, batchFiles); - } + timer.log(`Processing ${binaryFiles.length} binary files using chunking + batching`); + const binaryResults = await this.processFilesWithChunkingAndBatching(binaryFiles, currentDir, true); + Object.assign(files, binaryResults); timer.log('Binary files processing completed'); } - timer.log(`Serialization completed - ${Object.keys(files).length} files processed`); + const endTime = Date.now(); + const totalTime = endTime - startTime; + timer.log(`Serialization completed - ${Object.keys(files).length} files processed in ${totalTime}ms`); return files; } catch (error) { - console.error(`[serializeFiles] Error during serialization:`, error); + const endTime = Date.now(); + const totalTime = endTime - startTime; + console.error(`[serializeFiles] Error during serialization after ${totalTime}ms:`, error); throw error; } } + /** + * Process files using chunking + batching approach + * 1. Split files into chunks + * 2. Process each chunk in batches + * 3. Clean up memory after each chunk + */ + private async processFilesWithChunkingAndBatching( + filePaths: string[], + baseDir: string, + isBinary: boolean, + chunkSize = 100, + batchSize = 10 + ): Promise> { + const files: Record = {}; + const totalFiles = filePaths.length; + let processedCount = 0; + const chunkStartTime = Date.now(); + + for (let i = 0; i < filePaths.length; i += chunkSize) { + const chunk = filePaths.slice(i, i + chunkSize); + const chunkNumber = Math.floor(i / chunkSize) + 1; + const totalChunks = Math.ceil(filePaths.length / chunkSize); + console.log(`Processing chunk ${chunkNumber}/${totalChunks} (${chunk.length} files)`); + + const chunkResults = await this.processChunkInBatches(chunk, baseDir, isBinary, batchSize); + Object.assign(files, chunkResults); + + processedCount += chunk.length; + const chunkTime = Date.now() - chunkStartTime; + console.log(`Completed chunk ${chunkNumber}/${totalChunks}. Total processed: ${processedCount}/${totalFiles} (${chunkTime}ms elapsed)`); + + if (global.gc) { + global.gc(); + } + } + + const totalChunkTime = Date.now() - chunkStartTime; + console.log(`Completed all chunks in ${totalChunkTime}ms`); + return files; + } + + private async processChunkInBatches( + chunk: string[], + baseDir: string, + isBinary: boolean, + batchSize = 10 + ): Promise> { + const files: Record = {}; + const batchStartTime = Date.now(); + + for (let i = 0; i < chunk.length; i += batchSize) { + const batch = chunk.slice(i, i + batchSize); + const batchNumber = Math.floor(i / batchSize) + 1; + const totalBatches = Math.ceil(chunk.length / batchSize); + + const batchPromises = batch.map(filePath => + isBinary + ? this.processBinaryFile(filePath, baseDir) + : this.processTextFile(filePath, baseDir) + ); + + const batchResults = await Promise.all(batchPromises); + + // Add successful results to files + for (const result of batchResults) { + if (result) { + files[result.path] = result.file; + } + } + + const batchTime = Date.now() - batchStartTime; + console.log(` Batch ${batchNumber}/${totalBatches} completed (${batch.length} files) in ${batchTime}ms`); + } + + const totalBatchTime = Date.now() - batchStartTime; + console.log(` All batches completed in ${totalBatchTime}ms`); + return files; + } + + private async processTextFile(fullPath: string, baseDir: string): Promise<{ path: string; file: FreestyleFile } | null> { + const relativePath = fullPath.replace(baseDir + '/', ''); + + try { + const textContent = await this.session.fs.readTextFile(fullPath); + + if (textContent !== null) { + // Skip very large text files to prevent memory issues + const MAX_TEXT_SIZE = 5 * 1024 * 1024; // 5MB limit for text files + if (textContent.length > MAX_TEXT_SIZE) { + console.warn(`[processTextFile] Skipping large text file ${relativePath} (${textContent.length} bytes)`); + return null; + } + + return { + path: relativePath, + file: { + content: textContent, + encoding: 'utf-8' as const, + } + }; + } else { + console.warn(`[processTextFile] Failed to read text content for ${relativePath}`); + return null; + } + } catch (error) { + console.warn(`[processTextFile] Error processing ${relativePath}:`, error); + return null; + } + } + + + private async processBinaryFile(fullPath: string, baseDir: string): Promise<{ path: string; file: FreestyleFile } | null> { + const relativePath = fullPath.replace(baseDir + '/', ''); + + try { + const binaryContent = await this.session.fs.readFile(fullPath); + + if (binaryContent) { + // For very large binary files, consider skipping or compressing ?? + const MAX_BINARY_SIZE = 10 * 1024 * 1024; // 10MB limit + if (binaryContent.length > MAX_BINARY_SIZE) { + console.warn(`[processBinaryFile] Skipping large binary file ${relativePath} (${binaryContent.length} bytes)`); + return null; + } + + const base64String = convertToBase64(binaryContent); + + return { + path: relativePath, + file: { + content: base64String, + encoding: 'base64' as const, + } + }; + } else { + console.warn(`[processBinaryFile] Failed to read binary content for ${relativePath}`); + return null; + } + } catch (error) { + console.warn(`[processBinaryFile] Error processing ${relativePath}:`, error); + return null; + } + } + + + + /** + * Get all file paths in a directory tree using memory-efficient streaming + * Instead of accumulating all paths in memory, we yield them one by one + */ private async getAllFilePathsFlat(rootDir: string): Promise { const allPaths: string[] = []; const dirsToProcess = [rootDir]; From d4353f2af47a4d37e2cf083b23ed5b32bba3e593 Mon Sep 17 00:00:00 2001 From: vutnguyen Date: Thu, 7 Aug 2025 10:42:10 +0700 Subject: [PATCH 02/18] reduce batch size --- .../src/server/api/routers/publish/manager.ts | 196 ++---------------- 1 file changed, 20 insertions(+), 176 deletions(-) diff --git a/apps/web/client/src/server/api/routers/publish/manager.ts b/apps/web/client/src/server/api/routers/publish/manager.ts index 1136b8cdb..40ff10e47 100644 --- a/apps/web/client/src/server/api/routers/publish/manager.ts +++ b/apps/web/client/src/server/api/routers/publish/manager.ts @@ -237,203 +237,52 @@ export class PublishManager { } /** - * Serialize files from a directory into a record of file paths to their content - * Memory-optimized version using chunking + batching approach + * Serializes all files in a directory for deployment using parallel processing * @param currentDir - The directory path to serialize * @returns Record of file paths to their content (base64 for binary, utf-8 for text) */ private async serializeFiles(currentDir: string): Promise> { const timer = new LogTimer('File Serialization'); - const startTime = Date.now(); try { const allFilePaths = await this.getAllFilePathsFlat(currentDir); timer.log(`File discovery completed - ${allFilePaths.length} files found`); const filteredPaths = allFilePaths.filter(filePath => !this.shouldSkipFile(filePath)); - timer.log(`Filtered to ${filteredPaths.length} files after exclusions`); const { binaryFiles, textFiles } = this.categorizeFiles(filteredPaths); - timer.log(`Categorized: ${textFiles.length} text files, ${binaryFiles.length} binary files`); + const BATCH_SIZE = 10; const files: Record = {}; - + if (textFiles.length > 0) { - timer.log(`Processing ${textFiles.length} text files using chunking + batching`); - const textResults = await this.processFilesWithChunkingAndBatching(textFiles, currentDir, false); - Object.assign(files, textResults); + timer.log(`Processing ${textFiles.length} text files in batches of ${BATCH_SIZE}`); + for (let i = 0; i < textFiles.length; i += BATCH_SIZE) { + const batch = textFiles.slice(i, i + BATCH_SIZE); + const batchFiles = await this.processTextFilesBatch(batch, currentDir); + Object.assign(files, batchFiles); + } timer.log('Text files processing completed'); } if (binaryFiles.length > 0) { - timer.log(`Processing ${binaryFiles.length} binary files using chunking + batching`); - const binaryResults = await this.processFilesWithChunkingAndBatching(binaryFiles, currentDir, true); - Object.assign(files, binaryResults); + timer.log(`Processing ${binaryFiles.length} binary files in batches of ${BATCH_SIZE}`); + for (let i = 0; i < binaryFiles.length; i += BATCH_SIZE) { + const batch = binaryFiles.slice(i, i + BATCH_SIZE); + const batchFiles = await this.processBinaryFilesBatch(batch, currentDir); + Object.assign(files, batchFiles); + } timer.log('Binary files processing completed'); } - const endTime = Date.now(); - const totalTime = endTime - startTime; - timer.log(`Serialization completed - ${Object.keys(files).length} files processed in ${totalTime}ms`); + timer.log(`Serialization completed - ${Object.keys(files).length} files processed`); return files; } catch (error) { - const endTime = Date.now(); - const totalTime = endTime - startTime; - console.error(`[serializeFiles] Error during serialization after ${totalTime}ms:`, error); + console.error(`[serializeFiles] Error during serialization:`, error); throw error; } } - /** - * Process files using chunking + batching approach - * 1. Split files into chunks - * 2. Process each chunk in batches - * 3. Clean up memory after each chunk - */ - private async processFilesWithChunkingAndBatching( - filePaths: string[], - baseDir: string, - isBinary: boolean, - chunkSize = 100, - batchSize = 10 - ): Promise> { - const files: Record = {}; - const totalFiles = filePaths.length; - let processedCount = 0; - const chunkStartTime = Date.now(); - - for (let i = 0; i < filePaths.length; i += chunkSize) { - const chunk = filePaths.slice(i, i + chunkSize); - const chunkNumber = Math.floor(i / chunkSize) + 1; - const totalChunks = Math.ceil(filePaths.length / chunkSize); - console.log(`Processing chunk ${chunkNumber}/${totalChunks} (${chunk.length} files)`); - - const chunkResults = await this.processChunkInBatches(chunk, baseDir, isBinary, batchSize); - Object.assign(files, chunkResults); - - processedCount += chunk.length; - const chunkTime = Date.now() - chunkStartTime; - console.log(`Completed chunk ${chunkNumber}/${totalChunks}. Total processed: ${processedCount}/${totalFiles} (${chunkTime}ms elapsed)`); - - if (global.gc) { - global.gc(); - } - } - - const totalChunkTime = Date.now() - chunkStartTime; - console.log(`Completed all chunks in ${totalChunkTime}ms`); - return files; - } - - private async processChunkInBatches( - chunk: string[], - baseDir: string, - isBinary: boolean, - batchSize = 10 - ): Promise> { - const files: Record = {}; - const batchStartTime = Date.now(); - - for (let i = 0; i < chunk.length; i += batchSize) { - const batch = chunk.slice(i, i + batchSize); - const batchNumber = Math.floor(i / batchSize) + 1; - const totalBatches = Math.ceil(chunk.length / batchSize); - - const batchPromises = batch.map(filePath => - isBinary - ? this.processBinaryFile(filePath, baseDir) - : this.processTextFile(filePath, baseDir) - ); - - const batchResults = await Promise.all(batchPromises); - - // Add successful results to files - for (const result of batchResults) { - if (result) { - files[result.path] = result.file; - } - } - - const batchTime = Date.now() - batchStartTime; - console.log(` Batch ${batchNumber}/${totalBatches} completed (${batch.length} files) in ${batchTime}ms`); - } - - const totalBatchTime = Date.now() - batchStartTime; - console.log(` All batches completed in ${totalBatchTime}ms`); - return files; - } - - private async processTextFile(fullPath: string, baseDir: string): Promise<{ path: string; file: FreestyleFile } | null> { - const relativePath = fullPath.replace(baseDir + '/', ''); - - try { - const textContent = await this.session.fs.readTextFile(fullPath); - - if (textContent !== null) { - // Skip very large text files to prevent memory issues - const MAX_TEXT_SIZE = 5 * 1024 * 1024; // 5MB limit for text files - if (textContent.length > MAX_TEXT_SIZE) { - console.warn(`[processTextFile] Skipping large text file ${relativePath} (${textContent.length} bytes)`); - return null; - } - - return { - path: relativePath, - file: { - content: textContent, - encoding: 'utf-8' as const, - } - }; - } else { - console.warn(`[processTextFile] Failed to read text content for ${relativePath}`); - return null; - } - } catch (error) { - console.warn(`[processTextFile] Error processing ${relativePath}:`, error); - return null; - } - } - - - private async processBinaryFile(fullPath: string, baseDir: string): Promise<{ path: string; file: FreestyleFile } | null> { - const relativePath = fullPath.replace(baseDir + '/', ''); - - try { - const binaryContent = await this.session.fs.readFile(fullPath); - - if (binaryContent) { - // For very large binary files, consider skipping or compressing ?? - const MAX_BINARY_SIZE = 10 * 1024 * 1024; // 10MB limit - if (binaryContent.length > MAX_BINARY_SIZE) { - console.warn(`[processBinaryFile] Skipping large binary file ${relativePath} (${binaryContent.length} bytes)`); - return null; - } - - const base64String = convertToBase64(binaryContent); - - return { - path: relativePath, - file: { - content: base64String, - encoding: 'base64' as const, - } - }; - } else { - console.warn(`[processBinaryFile] Failed to read binary content for ${relativePath}`); - return null; - } - } catch (error) { - console.warn(`[processBinaryFile] Error processing ${relativePath}:`, error); - return null; - } - } - - - - /** - * Get all file paths in a directory tree using memory-efficient streaming - * Instead of accumulating all paths in memory, we yield them one by one - */ private async getAllFilePathsFlat(rootDir: string): Promise { const allPaths: string[] = []; const dirsToProcess = [rootDir]; @@ -497,10 +346,8 @@ export class PublishManager { return { binaryFiles, textFiles }; } - private async processTextFilesBatch( - filePaths: string[], - baseDir: string, - ): Promise> { + + private async processTextFilesBatch(filePaths: string[], baseDir: string): Promise> { const promises = filePaths.map(async (fullPath) => { const relativePath = fullPath.replace(baseDir + '/', ''); @@ -535,10 +382,7 @@ export class PublishManager { return files; } - private async processBinaryFilesBatch( - filePaths: string[], - baseDir: string, - ): Promise> { + private async processBinaryFilesBatch(filePaths: string[], baseDir: string): Promise> { const promises = filePaths.map(async (fullPath) => { const relativePath = fullPath.replace(baseDir + '/', ''); From 9b1ceabdfacd8925cfe3ed902bca5ac5806b0e96 Mon Sep 17 00:00:00 2001 From: vutnguyen Date: Thu, 7 Aug 2025 15:07:30 +0700 Subject: [PATCH 03/18] update chunk function --- .../src/server/api/routers/publish/manager.ts | 290 ++++++++++++++---- 1 file changed, 225 insertions(+), 65 deletions(-) diff --git a/apps/web/client/src/server/api/routers/publish/manager.ts b/apps/web/client/src/server/api/routers/publish/manager.ts index 40ff10e47..c13a025a5 100644 --- a/apps/web/client/src/server/api/routers/publish/manager.ts +++ b/apps/web/client/src/server/api/routers/publish/manager.ts @@ -22,10 +22,17 @@ import { import { type FreestyleFile } from 'freestyle-sandboxes'; import type { z } from 'zod'; +type ChunkProcessor = (chunk: Record, chunkInfo: { + index: number; + total: number; + filesProcessed: number; + totalFiles: number; +}) => Promise; + export class PublishManager { constructor(private readonly provider: Provider) { } - private get fileOps(): FileOperations { + private get fileOperations(): FileOperations { return { readFile: async (path: string) => { const { file } = await this.provider.readFile({ @@ -54,7 +61,7 @@ export class PublishManager { }); return stat.type === 'file'; } catch (error) { - console.error(`[fileExists] Error checking if file exists at ${path}:`, error); + console.error(`Error checking file existence at ${path}:`, error); return false; } }, @@ -99,7 +106,7 @@ export class PublishManager { deployment: z.infer, ) => Promise; }): Promise> { - await this.runPrepareStep(); + await this.prepareProject(); await updateDeployment({ status: DeploymentStatus.IN_PROGRESS, message: 'Preparing deployment...', @@ -128,13 +135,11 @@ export class PublishManager { message: 'Postprocessing project...', progress: 50, }); - const { success: postprocessSuccess, error: postprocessError } = - await this.postprocessNextBuild(); + + const { success: postprocessSuccess, error: postprocessError } = await this.postprocessBuild(); if (!postprocessSuccess) { - throw new Error( - `Failed to postprocess project for deployment, error: ${postprocessError}`, - ); + throw new Error(`Failed to postprocess project for deployment: ${postprocessError}`); } await updateDeployment({ @@ -143,26 +148,32 @@ export class PublishManager { progress: 60, }); - // Serialize the files for deployment const NEXT_BUILD_OUTPUT_PATH = `${CUSTOM_OUTPUT_DIR}/standalone`; - return await this.serializeFiles(NEXT_BUILD_OUTPUT_PATH); + return await this.serializeFiles(NEXT_BUILD_OUTPUT_PATH, { + onProgress: async (processed, total) => { + const progress = Math.floor(60 + (processed / total) * 35); + await updateDeployment({ + status: DeploymentStatus.IN_PROGRESS, + message: `Processing files... ${processed}/${total}`, + progress, + }); + } + }); } private async addBadge(folderPath: string) { - await injectBuiltWithScript(folderPath, this.fileOps); - await addBuiltWithScript(folderPath, this.fileOps); + await injectBuiltWithScript(folderPath, this.fileOperations); + await addBuiltWithScript(folderPath, this.fileOperations); } - private async runPrepareStep() { - // Preprocess the project - const preprocessSuccess = await addNextBuildConfig(this.fileOps); + private async prepareProject() { + const preprocessSuccess = await addNextBuildConfig(this.fileOperations); if (!preprocessSuccess) { - throw new Error(`Failed to prepare project for deployment`); + throw new Error('Failed to prepare project for deployment'); } - // Update .gitignore to ignore the custom output directory - const gitignoreSuccess = await updateGitignore(CUSTOM_OUTPUT_DIR, this.fileOps); + const gitignoreSuccess = await updateGitignore(CUSTOM_OUTPUT_DIR, this.fileOperations); if (!gitignoreSuccess) { console.warn('Failed to update .gitignore'); } @@ -170,12 +181,11 @@ export class PublishManager { private async runBuildStep(buildScript: string, buildFlags: string): Promise { try { - // Use default build flags if no build flags are provided - const buildFlagsString: string = isNullOrUndefined(buildFlags) + const buildFlagsString = isNullOrUndefined(buildFlags) ? DefaultSettings.EDITOR_SETTINGS.buildFlags : buildFlags; - const BUILD_SCRIPT_NO_LINT = isEmptyString(buildFlagsString) + const buildCommand = isEmptyString(buildFlagsString) ? buildScript : `${buildScript} -- ${buildFlagsString}`; @@ -191,13 +201,14 @@ export class PublishManager { } } - private async postprocessNextBuild(): Promise<{ + private async postprocessBuild(): Promise<{ success: boolean; error?: string; }> { - const entrypointExists = await this.fileOps.fileExists( + const entrypointExists = await this.fileOperations.fileExists( `${CUSTOM_OUTPUT_DIR}/standalone/server.js`, ); + if (!entrypointExists) { return { success: false, @@ -205,8 +216,8 @@ export class PublishManager { }; } - await this.fileOps.copy(`public`, `${CUSTOM_OUTPUT_DIR}/standalone/public`, true, true); - await this.fileOps.copy( + await this.fileOperations.copy(`public`, `${CUSTOM_OUTPUT_DIR}/standalone/public`, true, true); + await this.fileOperations.copy( `${CUSTOM_OUTPUT_DIR}/static`, `${CUSTOM_OUTPUT_DIR}/standalone/${CUSTOM_OUTPUT_DIR}/static`, true, @@ -214,76 +225,229 @@ export class PublishManager { ); for (const lockFile of SUPPORTED_LOCK_FILES) { - const lockFileExists = await this.fileOps.fileExists(`./${lockFile}`); + const lockFileExists = await this.fileOperations.fileExists(`./${lockFile}`); if (lockFileExists) { - await this.fileOps.copy( + await this.fileOperations.copy( `./${lockFile}`, `${CUSTOM_OUTPUT_DIR}/standalone/${lockFile}`, true, true, ); return { success: true }; - } else { - console.error(`lockFile not found: ${lockFile}`); } } return { success: false, - error: - 'Failed to find lock file. Supported lock files: ' + - SUPPORTED_LOCK_FILES.join(', '), + error: 'Failed to find lock file. Supported lock files: ' + SUPPORTED_LOCK_FILES.join(', '), }; } - /** - * Serializes all files in a directory for deployment using parallel processing - * @param currentDir - The directory path to serialize - * @returns Record of file paths to their content (base64 for binary, utf-8 for text) - */ - private async serializeFiles(currentDir: string): Promise> { + private async serializeFiles( + currentDir: string, + options: { + chunkSize?: number; + batchSize?: number; + onProgress?: (processed: number, total: number) => Promise; + onChunkComplete?: ChunkProcessor; + } = {} + ): Promise> { + const { + chunkSize = 100, + batchSize = 10, + onProgress, + onChunkComplete = this.handleChunkComplete.bind(this) + } = options; + const timer = new LogTimer('File Serialization'); try { - const allFilePaths = await this.getAllFilePathsFlat(currentDir); + const allFilePaths = await this.collectAllFilePaths(currentDir); timer.log(`File discovery completed - ${allFilePaths.length} files found`); const filteredPaths = allFilePaths.filter(filePath => !this.shouldSkipFile(filePath)); + timer.log(`Filtered to ${filteredPaths.length} files after exclusions`); const { binaryFiles, textFiles } = this.categorizeFiles(filteredPaths); + timer.log(`Categorized: ${textFiles.length} text files, ${binaryFiles.length} binary files`); - const BATCH_SIZE = 10; - const files: Record = {}; + let totalProcessed = 0; + const totalFiles = filteredPaths.length; if (textFiles.length > 0) { - timer.log(`Processing ${textFiles.length} text files in batches of ${BATCH_SIZE}`); - for (let i = 0; i < textFiles.length; i += BATCH_SIZE) { - const batch = textFiles.slice(i, i + BATCH_SIZE); - const batchFiles = await this.processTextFilesBatch(batch, currentDir); - Object.assign(files, batchFiles); - } + timer.log(`Processing ${textFiles.length} text files`); + await this.processFilesInChunks( + textFiles, + currentDir, + chunkSize, + batchSize, + 'text', + async (chunk, chunkInfo) => { + await onChunkComplete(chunk, chunkInfo); + totalProcessed += Object.keys(chunk).length; + if (onProgress) { + await onProgress(totalProcessed, totalFiles); + } + } + ); timer.log('Text files processing completed'); } if (binaryFiles.length > 0) { - timer.log(`Processing ${binaryFiles.length} binary files in batches of ${BATCH_SIZE}`); - for (let i = 0; i < binaryFiles.length; i += BATCH_SIZE) { - const batch = binaryFiles.slice(i, i + BATCH_SIZE); - const batchFiles = await this.processBinaryFilesBatch(batch, currentDir); - Object.assign(files, batchFiles); - } + timer.log(`Processing ${binaryFiles.length} binary files`); + await this.processFilesInChunks( + binaryFiles, + currentDir, + chunkSize, + batchSize, + 'binary', + async (chunk, chunkInfo) => { + await onChunkComplete(chunk, chunkInfo); + totalProcessed += Object.keys(chunk).length; + if (onProgress) { + await onProgress(totalProcessed, totalFiles); + } + } + ); timer.log('Binary files processing completed'); } - timer.log(`Serialization completed - ${Object.keys(files).length} files processed`); - return files; + timer.log(`Serialization completed - ${filteredPaths.length} files processed in ${timer.getElapsed()}ms`); + + return this.getFinalSummary(); + } catch (error) { - console.error(`[serializeFiles] Error during serialization:`, error); + console.error('Error during serialization:', error); throw error; } } - private async getAllFilePathsFlat(rootDir: string): Promise { + private async processFilesInChunks( + filePaths: string[], + currentDir: string, + chunkSize: number, + batchSize: number, + fileType: 'text' | 'binary', + onChunkComplete: ChunkProcessor + ): Promise { + const chunks = this.createChunks(filePaths, chunkSize); + const timer = new LogTimer('Chunking'); + + console.log(`Starting processing of ${filePaths.length} files in chunks of ${chunkSize}`); + + for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) { + const chunk = chunks[chunkIndex]; + if (!chunk) { + continue; + } + + console.log(`Processing chunk ${chunkIndex + 1}/${chunks.length} (${chunk.length} files)`); + + const chunkData = await this.processChunkWithBatching( + chunk, + currentDir, + batchSize, + fileType + ); + + await onChunkComplete(chunkData, { + index: chunkIndex, + total: chunks.length, + filesProcessed: (chunkIndex * chunkSize) + chunk.length, + totalFiles: filePaths.length + }); + + console.log(`Completed chunk ${chunkIndex + 1}/${chunks.length}. Total processed: ${(chunkIndex + 1) * chunkSize}/${filePaths.length} (${timer.getElapsed()}ms elapsed)`); + + this.clearChunkData(chunkData, chunk); + await this.yieldForGarbageCollection(); + } + + console.log(`Completed all chunks in ${timer.getElapsed()}ms`); + } + + private async processChunkWithBatching( + filePaths: string[], + currentDir: string, + batchSize: number, + fileType: 'text' | 'binary' + ): Promise> { + console.log(`Processing ${filePaths.length} files in batches of ${batchSize}`); + + const chunkData: Record = {}; + + for (let i = 0; i < filePaths.length; i += batchSize) { + const batch = filePaths.slice(i, i + batchSize); + const batchIndex = Math.floor(i / batchSize) + 1; + const totalBatches = Math.ceil(filePaths.length / batchSize); + + const startTime = Date.now(); + + let batchResults: Record; + if (fileType === 'text') { + batchResults = await this.processTextFilesBatch(batch, currentDir); + } else { + batchResults = await this.processBinaryFilesBatch(batch, currentDir); + } + + const endTime = Date.now(); + console.log(`Batch ${batchIndex}/${totalBatches} completed (${batch.length} files) in ${endTime - startTime}ms`); + + Object.assign(chunkData, batchResults); + Object.keys(batchResults).forEach(key => delete batchResults[key]); + } + + return chunkData; + } + + private async handleChunkComplete( + chunk: Record, + chunkInfo: { index: number; total: number; filesProcessed: number; totalFiles: number } + ): Promise { + console.log(`Processing chunk ${chunkInfo.index + 1}/${chunkInfo.total} with ${Object.keys(chunk).length} files`); + + const chunkSize = JSON.stringify(chunk).length; + console.log(`Chunk ${chunkInfo.index + 1} size: ${(chunkSize / 1024 / 1024).toFixed(2)}MB`); + } + + private clearChunkData(chunkData: Record, filePaths: string[]): void { + Object.keys(chunkData).forEach(key => { + delete chunkData[key]; + }); + filePaths.length = 0; + + if (global.gc && process.env.NODE_ENV === 'development') { + global.gc(); + } + } + + private async yieldForGarbageCollection(): Promise { + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setTimeout(resolve, 0)); + } + + private getFinalSummary(): Record { + return { + '__summary__': { + content: JSON.stringify({ + message: 'Files processed in chunks and sent to server', + timestamp: new Date().toISOString(), + processedAt: Date.now() + }), + encoding: 'utf-8' as const + } + }; + } + + private createChunks(array: T[], chunkSize: number): T[][] { + const chunks: T[][] = []; + for (let i = 0; i < array.length; i += chunkSize) { + chunks.push(array.slice(i, i + chunkSize)); + } + return chunks; + } + + private async collectAllFilePaths(rootDir: string): Promise { const allPaths: string[] = []; const dirsToProcess = [rootDir]; @@ -300,7 +464,6 @@ export class PublishManager { const fullPath = `${currentDir}/${entry.name}`; if (entry.type === 'directory') { - // Skip node_modules and other heavy directories early if (!EXCLUDED_PUBLISH_DIRECTORIES.includes(entry.name)) { dirsToProcess.push(fullPath); } @@ -309,15 +472,13 @@ export class PublishManager { } } } catch (error) { - console.warn(`[getAllFilePathsFlat] Error reading directory ${currentDir}:`, error); + console.warn(`Error reading directory ${currentDir}:`, error); } } return allPaths; } - /** - * Check if a file should be skipped - */ + private shouldSkipFile(filePath: string): boolean { return ( filePath.includes('node_modules') || @@ -346,7 +507,6 @@ export class PublishManager { return { binaryFiles, textFiles }; } - private async processTextFilesBatch(filePaths: string[], baseDir: string): Promise> { const promises = filePaths.map(async (fullPath) => { const relativePath = fullPath.replace(baseDir + '/', ''); @@ -365,7 +525,7 @@ export class PublishManager { }, }; } catch (error) { - console.warn(`[processTextFilesBatch] Error processing ${relativePath}:`, error); + console.warn(`Error processing ${relativePath}:`, error); return null; } }); @@ -409,7 +569,7 @@ export class PublishManager { return null; } } catch (error) { - console.warn(`[processBinaryFilesBatch] Error processing ${relativePath}:`, error); + console.warn(`Error processing ${relativePath}:`, error); return null; } }); From 59d77f981b055e476824e162640ef0e1ee136787 Mon Sep 17 00:00:00 2001 From: vutnguyen Date: Fri, 8 Aug 2025 10:02:34 +0700 Subject: [PATCH 04/18] update clean up function --- .../src/server/api/routers/publish/manager.ts | 58 +++++++++---------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/apps/web/client/src/server/api/routers/publish/manager.ts b/apps/web/client/src/server/api/routers/publish/manager.ts index c13a025a5..5eee232b9 100644 --- a/apps/web/client/src/server/api/routers/publish/manager.ts +++ b/apps/web/client/src/server/api/routers/publish/manager.ts @@ -260,6 +260,7 @@ export class PublishManager { } = options; const timer = new LogTimer('File Serialization'); + const allFiles: Record = {}; try { const allFilePaths = await this.collectAllFilePaths(currentDir); @@ -274,6 +275,11 @@ export class PublishManager { let totalProcessed = 0; const totalFiles = filteredPaths.length; + const handleAndMergeChunk: ChunkProcessor = async (chunk, chunkInfo) => { + Object.assign(allFiles, chunk); + await onChunkComplete(chunk, chunkInfo); + }; + if (textFiles.length > 0) { timer.log(`Processing ${textFiles.length} text files`); await this.processFilesInChunks( @@ -283,7 +289,7 @@ export class PublishManager { batchSize, 'text', async (chunk, chunkInfo) => { - await onChunkComplete(chunk, chunkInfo); + await handleAndMergeChunk(chunk, chunkInfo); totalProcessed += Object.keys(chunk).length; if (onProgress) { await onProgress(totalProcessed, totalFiles); @@ -302,7 +308,7 @@ export class PublishManager { batchSize, 'binary', async (chunk, chunkInfo) => { - await onChunkComplete(chunk, chunkInfo); + await handleAndMergeChunk(chunk, chunkInfo); totalProcessed += Object.keys(chunk).length; if (onProgress) { await onProgress(totalProcessed, totalFiles); @@ -313,8 +319,8 @@ export class PublishManager { } timer.log(`Serialization completed - ${filteredPaths.length} files processed in ${timer.getElapsed()}ms`); - - return this.getFinalSummary(); + + return allFiles; } catch (error) { console.error('Error during serialization:', error); @@ -343,7 +349,7 @@ export class PublishManager { console.log(`Processing chunk ${chunkIndex + 1}/${chunks.length} (${chunk.length} files)`); - const chunkData = await this.processChunkWithBatching( + let chunkData: Record | null = await this.processChunkWithBatching( chunk, currentDir, batchSize, @@ -359,7 +365,7 @@ export class PublishManager { console.log(`Completed chunk ${chunkIndex + 1}/${chunks.length}. Total processed: ${(chunkIndex + 1) * chunkSize}/${filePaths.length} (${timer.getElapsed()}ms elapsed)`); - this.clearChunkData(chunkData, chunk); + chunkData = null; await this.yieldForGarbageCollection(); } @@ -394,7 +400,6 @@ export class PublishManager { console.log(`Batch ${batchIndex}/${totalBatches} completed (${batch.length} files) in ${endTime - startTime}ms`); Object.assign(chunkData, batchResults); - Object.keys(batchResults).forEach(key => delete batchResults[key]); } return chunkData; @@ -405,40 +410,31 @@ export class PublishManager { chunkInfo: { index: number; total: number; filesProcessed: number; totalFiles: number } ): Promise { console.log(`Processing chunk ${chunkInfo.index + 1}/${chunkInfo.total} with ${Object.keys(chunk).length} files`); - - const chunkSize = JSON.stringify(chunk).length; - console.log(`Chunk ${chunkInfo.index + 1} size: ${(chunkSize / 1024 / 1024).toFixed(2)}MB`); + const chunkSizeBytes = this.computeChunkSizeBytes(chunk); + console.log(`Chunk ${chunkInfo.index + 1} size: ${(chunkSizeBytes / 1024 / 1024).toFixed(2)}MB`); } - private clearChunkData(chunkData: Record, filePaths: string[]): void { - Object.keys(chunkData).forEach(key => { - delete chunkData[key]; - }); - filePaths.length = 0; - - if (global.gc && process.env.NODE_ENV === 'development') { - global.gc(); - } - } private async yieldForGarbageCollection(): Promise { await new Promise(resolve => setImmediate(resolve)); await new Promise(resolve => setTimeout(resolve, 0)); } - private getFinalSummary(): Record { - return { - '__summary__': { - content: JSON.stringify({ - message: 'Files processed in chunks and sent to server', - timestamp: new Date().toISOString(), - processedAt: Date.now() - }), - encoding: 'utf-8' as const + private computeChunkSizeBytes(chunk: Record): number { + let total = 0; + const textEncoder = new TextEncoder(); + for (const file of Object.values(chunk)) { + const content = file.content; + if (file.encoding === 'base64') { + const len = content.length; + const padding = content.endsWith('==') ? 2 : content.endsWith('=') ? 1 : 0; + total += Math.max(0, Math.floor((len * 3) / 4) - padding); + } else { + total += textEncoder.encode(content).length; } - }; + } + return total; } - private createChunks(array: T[], chunkSize: number): T[][] { const chunks: T[][] = []; for (let i = 0; i < array.length; i += chunkSize) { From 9cb10a83c57030de23528ee9df1d91c3f1e38710 Mon Sep 17 00:00:00 2001 From: vutnguyen Date: Sat, 9 Aug 2025 10:07:03 +0700 Subject: [PATCH 05/18] update method publish --- .../client/public/onlook-preload-script.js | 20 +- apps/web/client/src/env.ts | 2 + .../api/routers/domain/adapters/freestyle.ts | 48 +++- .../server/api/routers/publish/deployment.ts | 6 + .../api/routers/publish/helpers/deploy.ts | 40 +-- .../api/routers/publish/helpers/logs.ts | 44 ++++ .../api/routers/publish/helpers/publish.ts | 28 +- .../src/server/api/routers/publish/manager.ts | 244 +++++++++++++----- .../server/utils/supabase/admin-storage.ts | 106 ++++++++ packages/models/src/hosting/index.ts | 5 +- 10 files changed, 426 insertions(+), 117 deletions(-) create mode 100644 apps/web/client/src/server/api/routers/publish/helpers/logs.ts create mode 100644 apps/web/client/src/server/utils/supabase/admin-storage.ts diff --git a/apps/web/client/public/onlook-preload-script.js b/apps/web/client/public/onlook-preload-script.js index c9e88a263..7c99ee81b 100644 --- a/apps/web/client/public/onlook-preload-script.js +++ b/apps/web/client/public/onlook-preload-script.js @@ -1,17 +1,17 @@ -var Rh=Object.create;var{getPrototypeOf:yh,defineProperty:Er,getOwnPropertyNames:Mh}=Object;var Uh=Object.prototype.hasOwnProperty;var rg=(l,i,t)=>{t=l!=null?Rh(yh(l)):{};let r=i||!l||!l.__esModule?Er(t,"default",{value:l,enumerable:!0}):t;for(let n of Mh(l))if(!Uh.call(r,n))Er(r,n,{get:()=>l[n],enumerable:!0});return r};var hl=(l,i)=>()=>(i||l((i={exports:{}}).exports,i),i.exports);var q=(l,i)=>{for(var t in i)Er(l,t,{get:i[t],enumerable:!0,configurable:!0,set:(r)=>i[t]=()=>r})};var Lr=hl((F5,ng)=>{function Ah(l){var i=typeof l;return l!=null&&(i=="object"||i=="function")}ng.exports=Ah});var fg=hl((V5,og)=>{var kh=typeof global=="object"&&global&&global.Object===Object&&global;og.exports=kh});var Hr=hl((E5,gg)=>{var Sh=fg(),Nh=typeof self=="object"&&self&&self.Object===Object&&self,Ph=Sh||Nh||Function("return this")();gg.exports=Ph});var eg=hl((L5,bg)=>{var Ch=Hr(),Ih=function(){return Ch.Date.now()};bg.exports=Ih});var cg=hl((H5,hg)=>{var Zh=/\s/;function Th(l){var i=l.length;while(i--&&Zh.test(l.charAt(i)));return i}hg.exports=Th});var wg=hl((K5,mg)=>{var dh=cg(),lc=/^\s+/;function ic(l){return l?l.slice(0,dh(l)+1).replace(lc,""):l}mg.exports=ic});var Kr=hl((R5,pg)=>{var tc=Hr(),rc=tc.Symbol;pg.exports=rc});var ag=hl((y5,xg)=>{var ug=Kr(),zg=Object.prototype,nc=zg.hasOwnProperty,oc=zg.toString,ht=ug?ug.toStringTag:void 0;function fc(l){var i=nc.call(l,ht),t=l[ht];try{l[ht]=void 0;var r=!0}catch(o){}var n=oc.call(l);if(r)if(i)l[ht]=t;else delete l[ht];return n}xg.exports=fc});var $g=hl((M5,vg)=>{var gc=Object.prototype,bc=gc.toString;function ec(l){return bc.call(l)}vg.exports=ec});var Dg=hl((U5,Jg)=>{var _g=Kr(),hc=ag(),cc=$g(),mc="[object Null]",wc="[object Undefined]",qg=_g?_g.toStringTag:void 0;function pc(l){if(l==null)return l===void 0?wc:mc;return qg&&qg in Object(l)?hc(l):cc(l)}Jg.exports=pc});var Wg=hl((A5,Xg)=>{function uc(l){return l!=null&&typeof l=="object"}Xg.exports=uc});var Og=hl((k5,sg)=>{var zc=Dg(),xc=Wg(),ac="[object Symbol]";function vc(l){return typeof l=="symbol"||xc(l)&&zc(l)==ac}sg.exports=vc});var Gg=hl((S5,Qg)=>{var $c=wg(),jg=Lr(),_c=Og(),Yg=NaN,qc=/^[-+]0x[0-9a-f]+$/i,Jc=/^0b[01]+$/i,Dc=/^0o[0-7]+$/i,Xc=parseInt;function Wc(l){if(typeof l=="number")return l;if(_c(l))return Yg;if(jg(l)){var i=typeof l.valueOf=="function"?l.valueOf():l;l=jg(i)?i+"":i}if(typeof l!="string")return l===0?l:+l;l=$c(l);var t=Jc.test(l);return t||Dc.test(l)?Xc(l.slice(2),t?2:8):qc.test(l)?Yg:+l}Qg.exports=Wc});var yr=hl((N5,Fg)=>{var sc=Lr(),Rr=eg(),Bg=Gg(),Oc="Expected a function",jc=Math.max,Yc=Math.min;function Qc(l,i,t){var r,n,o,f,b,e,g=0,h=!1,c=!1,m=!0;if(typeof l!="function")throw new TypeError(Oc);if(i=Bg(i)||0,sc(t))h=!!t.leading,c="maxWait"in t,o=c?jc(Bg(t.maxWait)||0,i):o,m="trailing"in t?!!t.trailing:m;function u(F){var M=r,T=n;return r=n=void 0,g=F,f=l.apply(T,M),f}function W(F){return g=F,b=setTimeout(D,i),h?u(F):f}function Z(F){var M=F-e,T=F-g,Vr=i-M;return c?Yc(Vr,o-T):Vr}function L(F){var M=F-e,T=F-g;return e===void 0||M>=i||M<0||c&&T>=o}function D(){var F=Rr();if(L(F))return H(F);b=setTimeout(D,Z(F))}function H(F){if(b=void 0,m&&r)return u(F);return r=n=void 0,f}function gl(){if(b!==void 0)clearTimeout(b);g=0,r=e=n=b=void 0}function K(){return b===void 0?f:H(Rr())}function B(){var F=Rr(),M=L(F);if(r=arguments,n=this,e=F,M){if(b===void 0)return W(e);if(c)return clearTimeout(b),b=setTimeout(D,i),u(e)}if(b===void 0)b=setTimeout(D,i);return f}return B.cancel=gl,B.flush=K,B}Fg.exports=Qc});var Vb=hl((Om)=>{var Fb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");Om.encode=function(l){if(0<=l&&l{var Eb=Vb(),rn=5,Lb=1<>1;return i?-t:t}Bm.encode=function l(i){var t="",r,n=Qm(i);do{if(r=n&Hb,n>>>=rn,n>0)r|=Kb;t+=Eb.encode(r)}while(n>0);return t};Bm.decode=function l(i,t,r){var n=i.length,o=0,f=0,b,e;do{if(t>=n)throw new Error("Expected more digits in base 64 VLQ value.");if(e=Eb.decode(i.charCodeAt(t++)),e===-1)throw new Error("Invalid base64 digit: "+i.charAt(t-1));b=!!(e&Kb),e&=Hb,o=o+(e<{function Em(l,i,t){if(i in l)return l[i];else if(arguments.length===3)return t;else throw new Error('"'+i+'" is a required argument.')}Im.getArg=Em;var yb=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,Lm=/^data:.+\,.+$/;function at(l){var i=l.match(yb);if(!i)return null;return{scheme:i[1],auth:i[2],host:i[3],port:i[4],path:i[5]}}Im.urlParse=at;function Hi(l){var i="";if(l.scheme)i+=l.scheme+":";if(i+="//",l.auth)i+=l.auth+"@";if(l.host)i+=l.host;if(l.port)i+=":"+l.port;if(l.path)i+=l.path;return i}Im.urlGenerate=Hi;var Hm=32;function Km(l){var i=[];return function(t){for(var r=0;rHm)i.pop();return o}}var nn=Km(function l(i){var t=i,r=at(i);if(r){if(!r.path)return i;t=r.path}var n=Im.isAbsolute(t),o=[],f=0,b=0;while(!0)if(f=b,b=t.indexOf("/",f),b===-1){o.push(t.slice(f));break}else{o.push(t.slice(f,b));while(b=0;b--)if(e=o[b],e===".")o.splice(b,1);else if(e==="..")g++;else if(g>0)if(e==="")o.splice(b+1,g),g=0;else o.splice(b,2),g--;if(t=o.join("/"),t==="")t=n?"/":".";if(r)return r.path=t,Hi(r);return t});Im.normalize=nn;function Mb(l,i){if(l==="")l=".";if(i==="")i=".";var t=at(i),r=at(l);if(r)l=r.path||"/";if(t&&!t.scheme){if(r)t.scheme=r.scheme;return Hi(t)}if(t||i.match(Lm))return i;if(r&&!r.host&&!r.path)return r.host=i,Hi(r);var n=i.charAt(0)==="/"?i:nn(l.replace(/\/+$/,"")+"/"+i);if(r)return r.path=n,Hi(r);return n}Im.join=Mb;Im.isAbsolute=function(l){return l.charAt(0)==="/"||yb.test(l)};function Rm(l,i){if(l==="")l=".";l=l.replace(/\/$/,"");var t=0;while(i.indexOf(l+"/")!==0){var r=l.lastIndexOf("/");if(r<0)return i;if(l=l.slice(0,r),l.match(/^([^\/]+:\/)?\/*$/))return i;++t}return Array(t+1).join("../")+i.substr(l.length+1)}Im.relative=Rm;var Ub=function(){var l=Object.create(null);return!("__proto__"in l)}();function Ab(l){return l}function ym(l){if(kb(l))return"$"+l;return l}Im.toSetString=Ub?Ab:ym;function Mm(l){if(kb(l))return l.slice(1);return l}Im.fromSetString=Ub?Ab:Mm;function kb(l){if(!l)return!1;var i=l.length;if(i<9)return!1;if(l.charCodeAt(i-1)!==95||l.charCodeAt(i-2)!==95||l.charCodeAt(i-3)!==111||l.charCodeAt(i-4)!==116||l.charCodeAt(i-5)!==111||l.charCodeAt(i-6)!==114||l.charCodeAt(i-7)!==112||l.charCodeAt(i-8)!==95||l.charCodeAt(i-9)!==95)return!1;for(var t=i-10;t>=0;t--)if(l.charCodeAt(t)!==36)return!1;return!0}function Um(l,i,t){var r=Tl(l.source,i.source);if(r!==0)return r;if(r=l.originalLine-i.originalLine,r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0||t)return r;if(r=l.generatedColumn-i.generatedColumn,r!==0)return r;if(r=l.generatedLine-i.generatedLine,r!==0)return r;return Tl(l.name,i.name)}Im.compareByOriginalPositions=Um;function Am(l,i,t){var r=l.originalLine-i.originalLine;if(r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0||t)return r;if(r=l.generatedColumn-i.generatedColumn,r!==0)return r;if(r=l.generatedLine-i.generatedLine,r!==0)return r;return Tl(l.name,i.name)}Im.compareByOriginalPositionsNoSource=Am;function km(l,i,t){var r=l.generatedLine-i.generatedLine;if(r!==0)return r;if(r=l.generatedColumn-i.generatedColumn,r!==0||t)return r;if(r=Tl(l.source,i.source),r!==0)return r;if(r=l.originalLine-i.originalLine,r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0)return r;return Tl(l.name,i.name)}Im.compareByGeneratedPositionsDeflated=km;function Sm(l,i,t){var r=l.generatedColumn-i.generatedColumn;if(r!==0||t)return r;if(r=Tl(l.source,i.source),r!==0)return r;if(r=l.originalLine-i.originalLine,r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0)return r;return Tl(l.name,i.name)}Im.compareByGeneratedPositionsDeflatedNoLine=Sm;function Tl(l,i){if(l===i)return 0;if(l===null)return 1;if(i===null)return-1;if(l>i)return 1;return-1}function Nm(l,i){var t=l.generatedLine-i.generatedLine;if(t!==0)return t;if(t=l.generatedColumn-i.generatedColumn,t!==0)return t;if(t=Tl(l.source,i.source),t!==0)return t;if(t=l.originalLine-i.originalLine,t!==0)return t;if(t=l.originalColumn-i.originalColumn,t!==0)return t;return Tl(l.name,i.name)}Im.compareByGeneratedPositionsInflated=Nm;function Pm(l){return JSON.parse(l.replace(/^\)]}'[^\n]*\n/,""))}Im.parseSourceMapInput=Pm;function Cm(l,i,t){if(i=i||"",l){if(l[l.length-1]!=="/"&&i[0]!=="/")l+="/";i=l+i}if(t){var r=at(t);if(!r)throw new Error("sourceMapURL could not be parsed");if(r.path){var n=r.path.lastIndexOf("/");if(n>=0)r.path=r.path.substring(0,n+1)}i=Mb(Hi(r),i)}return nn(i)}Im.computeSourceURL=Cm});var Sb=hl((ww)=>{var on=gr(),fn=Object.prototype.hasOwnProperty,$i=typeof Map!=="undefined";function dl(){this._array=[],this._set=$i?new Map:Object.create(null)}dl.fromArray=function l(i,t){var r=new dl;for(var n=0,o=i.length;n=0)return t}else{var r=on.toSetString(i);if(fn.call(this._set,r))return this._set[r]}throw new Error('"'+i+'" is not in the set.')};dl.prototype.at=function l(i){if(i>=0&&i{var Nb=gr();function uw(l,i){var t=l.generatedLine,r=i.generatedLine,n=l.generatedColumn,o=i.generatedColumn;return r>t||r==t&&o>=n||Nb.compareByGeneratedPositionsInflated(l,i)<=0}function br(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}br.prototype.unsortedForEach=function l(i,t){this._array.forEach(i,t)};br.prototype.add=function l(i){if(uw(this._last,i))this._last=i,this._array.push(i);else this._sorted=!1,this._array.push(i)};br.prototype.toArray=function l(){if(!this._sorted)this._array.sort(Nb.compareByGeneratedPositionsInflated),this._sorted=!0;return this._array};zw.MappingList=br});var Oi="PENPAL_CHILD";var Hh=rg(yr(),1);var Gc=class extends Error{code;constructor(l,i){super(i);this.name="PenpalError",this.code=l}},vl=Gc,Bc=(l)=>({name:l.name,message:l.message,stack:l.stack,penpalCode:l instanceof vl?l.code:void 0}),Fc=({name:l,message:i,stack:t,penpalCode:r})=>{let n=r?new vl(r,i):new Error(i);return n.name=l,n.stack=t,n},Vc=Symbol("Reply"),Ec=class{value;transferables;#l=Vc;constructor(l,i){this.value=l,this.transferables=i?.transferables}},Lc=Ec,Dl="penpal",At=(l)=>{return typeof l==="object"&&l!==null},Kg=(l)=>{return typeof l==="function"},Hc=(l)=>{return At(l)&&l.namespace===Dl},ji=(l)=>{return l.type==="SYN"},kt=(l)=>{return l.type==="ACK1"},ct=(l)=>{return l.type==="ACK2"},Rg=(l)=>{return l.type==="CALL"},yg=(l)=>{return l.type==="REPLY"},Kc=(l)=>{return l.type==="DESTROY"},Mg=(l,i=[])=>{let t=[];for(let r of Object.keys(l)){let n=l[r];if(Kg(n))t.push([...i,r]);else if(At(n))t.push(...Mg(n,[...i,r]))}return t},Rc=(l,i)=>{let t=l.reduce((r,n)=>{return At(r)?r[n]:void 0},i);return Kg(t)?t:void 0},oi=(l)=>{return l.join(".")},Vg=(l,i,t)=>({namespace:Dl,channel:l,type:"REPLY",callId:i,isError:!0,...t instanceof Error?{value:Bc(t),isSerializedErrorInstance:!0}:{value:t}}),yc=(l,i,t,r)=>{let n=!1,o=async(f)=>{if(n)return;if(!Rg(f))return;r?.(`Received ${oi(f.methodPath)}() call`,f);let{methodPath:b,args:e,id:g}=f,h,c;try{let m=Rc(b,i);if(!m)throw new vl("METHOD_NOT_FOUND",`Method \`${oi(b)}\` is not found.`);let u=await m(...e);if(u instanceof Lc)c=u.transferables,u=await u.value;h={namespace:Dl,channel:t,type:"REPLY",callId:g,value:u}}catch(m){h=Vg(t,g,m)}if(n)return;try{r?.(`Sending ${oi(b)}() reply`,h),l.sendMessage(h,c)}catch(m){if(m.name==="DataCloneError")h=Vg(t,g,m),r?.(`Sending ${oi(b)}() reply`,h),l.sendMessage(h);throw m}};return l.addMessageHandler(o),()=>{n=!0,l.removeMessageHandler(o)}},Mc=yc,Ug=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),Uc=Symbol("CallOptions"),Ac=class{transferables;timeout;#l=Uc;constructor(l){this.transferables=l?.transferables,this.timeout=l?.timeout}},kc=Ac,Sc=new Set(["apply","call","bind"]),Ag=(l,i,t=[])=>{return new Proxy(t.length?()=>{}:Object.create(null),{get(r,n){if(n==="then")return;if(t.length&&Sc.has(n))return Reflect.get(r,n);return Ag(l,i,[...t,n])},apply(r,n,o){return l(t,o)}})},Eg=(l)=>{return new vl("CONNECTION_DESTROYED",`Method call ${oi(l)}() failed due to destroyed connection`)},Nc=(l,i,t)=>{let r=!1,n=new Map,o=(e)=>{if(!yg(e))return;let{callId:g,value:h,isError:c,isSerializedErrorInstance:m}=e,u=n.get(g);if(!u)return;if(n.delete(g),t?.(`Received ${oi(u.methodPath)}() call`,e),c)u.reject(m?Fc(h):h);else u.resolve(h)};return l.addMessageHandler(o),{remoteProxy:Ag((e,g)=>{if(r)throw Eg(e);let h=Ug(),c=g[g.length-1],m=c instanceof kc,{timeout:u,transferables:W}=m?c:{},Z=m?g.slice(0,-1):g;return new Promise((L,D)=>{let H=u!==void 0?window.setTimeout(()=>{n.delete(h),D(new vl("METHOD_CALL_TIMEOUT",`Method call ${oi(e)}() timed out after ${u}ms`))},u):void 0;n.set(h,{methodPath:e,resolve:L,reject:D,timeoutId:H});try{let gl={namespace:Dl,channel:i,type:"CALL",id:h,methodPath:e,args:Z};t?.(`Sending ${oi(e)}() call`,gl),l.sendMessage(gl,W)}catch(gl){D(new vl("TRANSMISSION_FAILED",gl.message))}})},t),destroy:()=>{r=!0,l.removeMessageHandler(o);for(let{methodPath:e,reject:g,timeoutId:h}of n.values())clearTimeout(h),g(Eg(e));n.clear()}}},Pc=Nc,Cc=()=>{let l,i;return{promise:new Promise((r,n)=>{l=r,i=n}),resolve:l,reject:i}},Ic=Cc,Zc=class extends Error{constructor(l){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${l}`)}},Yi=Zc,Mr="deprecated-penpal",Tc=(l)=>{return At(l)&&"penpal"in l},dc=(l)=>l.split("."),Lg=(l)=>l.join("."),kg=(l)=>{return new Yi(`Unexpected message to translate: ${JSON.stringify(l)}`)},lm=(l)=>{if(l.penpal==="syn")return{namespace:Dl,channel:void 0,type:"SYN",participantId:Mr};if(l.penpal==="ack")return{namespace:Dl,channel:void 0,type:"ACK2"};if(l.penpal==="call")return{namespace:Dl,channel:void 0,type:"CALL",id:l.id,methodPath:dc(l.methodName),args:l.args};if(l.penpal==="reply")if(l.resolution==="fulfilled")return{namespace:Dl,channel:void 0,type:"REPLY",callId:l.id,value:l.returnValue};else return{namespace:Dl,channel:void 0,type:"REPLY",callId:l.id,isError:!0,...l.returnValueIsError?{value:l.returnValue,isSerializedErrorInstance:!0}:{value:l.returnValue}};throw kg(l)},im=(l)=>{if(kt(l))return{penpal:"synAck",methodNames:l.methodPaths.map(Lg)};if(Rg(l))return{penpal:"call",id:l.id,methodName:Lg(l.methodPath),args:l.args};if(yg(l))if(l.isError)return{penpal:"reply",id:l.callId,resolution:"rejected",...l.isSerializedErrorInstance?{returnValue:l.value,returnValueIsError:!0}:{returnValue:l.value}};else return{penpal:"reply",id:l.callId,resolution:"fulfilled",returnValue:l.value};throw kg(l)},tm=({messenger:l,methods:i,timeout:t,channel:r,log:n})=>{let o=Ug(),f,b=[],e=!1,g=Mg(i),{promise:h,resolve:c,reject:m}=Ic(),u=t!==void 0?setTimeout(()=>{m(new vl("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,W=()=>{for(let B of b)B()},Z=()=>{if(e)return;b.push(Mc(l,i,r,n));let{remoteProxy:B,destroy:F}=Pc(l,r,n);b.push(F),clearTimeout(u),e=!0,c({remoteProxy:B,destroy:W})},L=()=>{let B={namespace:Dl,type:"SYN",channel:r,participantId:o};n?.("Sending handshake SYN",B);try{l.sendMessage(B)}catch(F){m(new vl("TRANSMISSION_FAILED",F.message))}},D=(B)=>{if(n?.("Received handshake SYN",B),B.participantId===f&&f!==Mr)return;if(f=B.participantId,L(),!(o>f||f===Mr))return;let M={namespace:Dl,channel:r,type:"ACK1",methodPaths:g};n?.("Sending handshake ACK1",M);try{l.sendMessage(M)}catch(T){m(new vl("TRANSMISSION_FAILED",T.message));return}},H=(B)=>{n?.("Received handshake ACK1",B);let F={namespace:Dl,channel:r,type:"ACK2"};n?.("Sending handshake ACK2",F);try{l.sendMessage(F)}catch(M){m(new vl("TRANSMISSION_FAILED",M.message));return}Z()},gl=(B)=>{n?.("Received handshake ACK2",B),Z()},K=(B)=>{if(ji(B))D(B);if(kt(B))H(B);if(ct(B))gl(B)};return l.addMessageHandler(K),b.push(()=>l.removeMessageHandler(K)),L(),h},rm=tm,nm=(l)=>{let i=!1,t;return(...r)=>{if(!i)i=!0,t=l(...r);return t}},om=nm,Hg=new WeakSet,fm=({messenger:l,methods:i={},timeout:t,channel:r,log:n})=>{if(!l)throw new vl("INVALID_ARGUMENT","messenger must be defined");if(Hg.has(l))throw new vl("INVALID_ARGUMENT","A messenger can only be used for a single connection");Hg.add(l);let o=[l.destroy],f=om((g)=>{if(g){let h={namespace:Dl,channel:r,type:"DESTROY"};try{l.sendMessage(h)}catch(c){}}for(let h of o)h();n?.("Connection destroyed")}),b=(g)=>{return Hc(g)&&g.channel===r};return{promise:(async()=>{try{l.initialize({log:n,validateReceivedMessage:b}),l.addMessageHandler((c)=>{if(Kc(c))f(!1)});let{remoteProxy:g,destroy:h}=await rm({messenger:l,methods:i,timeout:t,channel:r,log:n});return o.push(h),g}catch(g){throw f(!0),g}})(),destroy:()=>{f(!0)}}},Sg=fm,gm=class{#l;#n;#t;#i;#f;#r=new Set;#o;#g=!1;constructor({remoteWindow:l,allowedOrigins:i}){if(!l)throw new vl("INVALID_ARGUMENT","remoteWindow must be defined");this.#l=l,this.#n=i?.length?i:[window.origin]}initialize=({log:l,validateReceivedMessage:i})=>{this.#t=l,this.#i=i,window.addEventListener("message",this.#c)};sendMessage=(l,i)=>{if(ji(l)){let t=this.#b(l);this.#l.postMessage(l,{targetOrigin:t,transfer:i});return}if(kt(l)||this.#g){let t=this.#g?im(l):l,r=this.#b(l);this.#l.postMessage(t,{targetOrigin:r,transfer:i});return}if(ct(l)){let{port1:t,port2:r}=new MessageChannel;this.#o=t,t.addEventListener("message",this.#e),t.start();let n=[r,...i||[]],o=this.#b(l);this.#l.postMessage(l,{targetOrigin:o,transfer:n});return}if(this.#o){this.#o.postMessage(l,{transfer:i});return}throw new Yi("Port is undefined")};addMessageHandler=(l)=>{this.#r.add(l)};removeMessageHandler=(l)=>{this.#r.delete(l)};destroy=()=>{window.removeEventListener("message",this.#c),this.#h(),this.#r.clear()};#m=(l)=>{return this.#n.some((i)=>i instanceof RegExp?i.test(l):i===l||i==="*")};#b=(l)=>{if(ji(l))return"*";if(!this.#f)throw new Yi("Concrete remote origin not set");return this.#f==="null"&&this.#n.includes("*")?"*":this.#f};#h=()=>{this.#o?.removeEventListener("message",this.#e),this.#o?.close(),this.#o=void 0};#c=({source:l,origin:i,ports:t,data:r})=>{if(l!==this.#l)return;if(Tc(r))this.#t?.("Please upgrade the child window to the latest version of Penpal."),this.#g=!0,r=lm(r);if(!this.#i?.(r))return;if(!this.#m(i)){this.#t?.(`Received a message from origin \`${i}\` which did not match allowed origins \`[${this.#n.join(", ")}]\``);return}if(ji(r))this.#h(),this.#f=i;if(ct(r)&&!this.#g){if(this.#o=t[0],!this.#o)throw new Yi("No port received on ACK2");this.#o.addEventListener("message",this.#e),this.#o.start()}for(let n of this.#r)n(r)};#e=({data:l})=>{if(!this.#i?.(l))return;for(let i of this.#r)i(l)}},Ng=gm,P5=class{#l;#n;#t=new Set;#i;constructor({worker:l}){if(!l)throw new vl("INVALID_ARGUMENT","worker must be defined");this.#l=l}initialize=({validateReceivedMessage:l})=>{this.#n=l,this.#l.addEventListener("message",this.#r)};sendMessage=(l,i)=>{if(ji(l)||kt(l)){this.#l.postMessage(l,{transfer:i});return}if(ct(l)){let{port1:t,port2:r}=new MessageChannel;this.#i=t,t.addEventListener("message",this.#r),t.start(),this.#l.postMessage(l,{transfer:[r,...i||[]]});return}if(this.#i){this.#i.postMessage(l,{transfer:i});return}throw new Yi("Port is undefined")};addMessageHandler=(l)=>{this.#t.add(l)};removeMessageHandler=(l)=>{this.#t.delete(l)};destroy=()=>{this.#l.removeEventListener("message",this.#r),this.#f(),this.#t.clear()};#f=()=>{this.#i?.removeEventListener("message",this.#r),this.#i?.close(),this.#i=void 0};#r=({ports:l,data:i})=>{if(!this.#n?.(i))return;if(ji(i))this.#f();if(ct(i)){if(this.#i=l[0],!this.#i)throw new Yi("No port received on ACK2");this.#i.addEventListener("message",this.#r),this.#i.start()}for(let t of this.#t)t(i)}};var C5=class{#l;#n;#t=new Set;constructor({port:l}){if(!l)throw new vl("INVALID_ARGUMENT","port must be defined");this.#l=l}initialize=({validateReceivedMessage:l})=>{this.#n=l,this.#l.addEventListener("message",this.#i),this.#l.start()};sendMessage=(l,i)=>{this.#l?.postMessage(l,{transfer:i})};addMessageHandler=(l)=>{this.#t.add(l)};removeMessageHandler=(l)=>{this.#t.delete(l)};destroy=()=>{this.#l.removeEventListener("message",this.#i),this.#l.close(),this.#t.clear()};#i=({data:l})=>{if(!this.#n?.(l))return;for(let i of this.#t)i(l)}};var Pg=["SCRIPT","STYLE","LINK","META","NOSCRIPT"],Cg=new Set(["a","abbr","area","audio","b","bdi","bdo","br","button","canvas","cite","code","data","datalist","del","dfn","em","embed","h1","h2","h3","h4","h5","h6","i","iframe","img","input","ins","kbd","label","li","map","mark","meter","noscript","object","output","p","picture","progress","q","ruby","s","samp","script","select","slot","small","span","strong","sub","sup","svg","template","textarea","time","u","var","video","wbr"]);var Ur=".next-prod";var cx={SCALE:0.7,PAN_POSITION:{x:175,y:100},URL:"http://localhost:3000/",FRAME_POSITION:{x:0,y:0},FRAME_DIMENSION:{width:1536,height:960},ASPECT_RATIO_LOCKED:!1,DEVICE:"Custom:Custom",THEME:"system",ORIENTATION:"Portrait",MIN_DIMENSIONS:{width:"280px",height:"360px"},COMMANDS:{run:"bun run dev",build:"bun run build",install:"bun install"},IMAGE_FOLDER:"public",IMAGE_DIMENSION:{width:"100px",height:"100px"},FONT_FOLDER:"fonts",FONT_CONFIG:"app/fonts.ts",TAILWIND_CONFIG:"tailwind.config.ts",CHAT_SETTINGS:{showSuggestions:!0,autoApplyCode:!0,expandCodeBlocks:!1,showMiniChat:!0},EDITOR_SETTINGS:{shouldWarnDelete:!1,enableBunReplace:!0,buildFlags:"--no-lint"}};var Ar=["node_modules","dist","build",".git",".next"],px=[...Ar,"static","out",Ur],ux=[...Ar,Ur],zx=[...Ar,"coverage"],bm=[".jsx",".tsx"],em=[".js",".ts",".mjs",".cjs"],xx=[...bm,...em];var $x={["en"]:"English",["ja"]:"日本語",["zh"]:"中文",["ko"]:"한국어"};var dg=rg(yr(),1);function R(l){return document.querySelector(`[${"data-odid"}="${l}"]`)}function kr(l,i=!1){let t=`[${"data-odid"}="${l}"]`;if(!i)return t;return hm(t)}function hm(l){return CSS.escape(l)}function zi(l){return l&&l instanceof Node&&l.nodeType===Node.ELEMENT_NODE&&!Pg.includes(l.tagName)&&!l.hasAttribute("data-onlook-ignore")&&l.style.display!=="none"}var cm="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ig=(l=21)=>{let i="",t=l|0;while(t--)i+=cm[Math.random()*64|0];return i};function Xl(l){let i=l.getAttribute("data-odid");if(!i)i=`odid-${Ig()}`,l.setAttribute("data-odid",i);return i}function Hl(l){return l.getAttribute("data-oid")}function Kl(l){return l.getAttribute("data-oiid")}function Zg(l,i){if(!$l)return;$l.onDomProcessed({layerMap:Object.fromEntries(l),rootNode:i}).catch((t)=>{console.error("Failed to send DOM processed event:",t)})}function Sr(l){window._onlookFrameId=l}function Qi(){let l=window._onlookFrameId;if(!l)return console.warn("Frame id not found"),$l?.getFrameId().then((i)=>{Sr(i)}),"";return l}function mm(l=document.body){if(!Qi())return console.warn("frameView id not found, skipping dom processing"),null;let t=zl(l);if(!t)return console.warn("Error building layer tree, root element is null"),null;let r=l.getAttribute("data-odid");if(!r)return console.warn("Root dom id not found"),null;let n=t.get(r);if(!n)return console.warn("Root node not found"),null;return Zg(t,n),{rootDomId:r,layerMap:Array.from(t.entries())}}var St=dg.default(mm,500),wm=[(l)=>{let i=l.parentElement;return i&&i.tagName.toLowerCase()==="svg"},(l)=>{return l.tagName.toLowerCase()==="next-route-announcer"},(l)=>{return l.tagName.toLowerCase()==="nextjs-portal"}];function zl(l){if(!zi(l))return null;let i=new Map,t=document.createTreeWalker(l,NodeFilter.SHOW_ELEMENT,{acceptNode:(o)=>{let f=o;if(wm.some((b)=>b(f)))return NodeFilter.FILTER_REJECT;return zi(f)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),r=Tg(l);r.children=[],i.set(r.domId,r);let n=t.nextNode();while(n){let o=Tg(n);o.children=[];let f=n.parentElement;if(f){let b=f.getAttribute("data-odid");if(b){o.parent=b;let e=i.get(b);if(e&&e.children)e.children.push(o.domId)}}i.set(o.domId,o),n=t.nextNode()}return i}function Tg(l){let i=Xl(l),t=Hl(l),r=Kl(l),n=Array.from(l.childNodes).map((e)=>e.nodeType===Node.TEXT_NODE?e.textContent:"").join(" ").trim().slice(0,500),o=window.getComputedStyle(l),f=l.getAttribute("data-ocname");return{domId:i,oid:t||null,instanceId:r||null,textContent:n||"",tagName:l.tagName.toLowerCase(),isVisible:o.visibility!=="hidden",component:f||null,frameId:Qi(),children:null,parent:null,dynamicType:null,coreElementType:null}}function Nr(l){throw new Error(`Expected \`never\`, found: ${JSON.stringify(l)}`)}var lb=(l)=>JSON.parse(JSON.stringify(l));function ib(l){let i=rb(l),t=pm(l),r=um(l);return{defined:{width:"auto",height:"auto",...t,...r},computed:i}}function tb(l){let i=R(l);if(!i)return{};return rb(i)}function rb(l){return lb(window.getComputedStyle(l))}function pm(l){let i={},t=nb(l.style.cssText);return Object.entries(t).forEach(([r,n])=>{i[r]=n}),i}function um(l){let i={},t=document.styleSheets;for(let r=0;ri[g]=h)}}catch(b){console.warn("Error",b)}}return i}function nb(l){let i={};return l.split(";").forEach((t)=>{if(t=t.trim(),!t)return;let[r,...n]=t.split(":");i[r?.trim()??""]=n.join(":").trim()}),i}var ob=(l,i)=>{let t=document.elementFromPoint(l,i);if(!t)return;let r=(o)=>{if(o?.shadowRoot){let f=o.shadowRoot.elementFromPoint(l,i);if(f==o)return o;else if(f?.shadowRoot)return r(f);else return f||o}else return o};return r(t)||t},nl=(l,i)=>{let t=l.parentElement,r=t?{domId:t.getAttribute("data-odid"),frameId:Qi(),oid:t.getAttribute("data-oid"),instanceId:t.getAttribute("data-oiid"),rect:t.getBoundingClientRect()}:null,n=l.getBoundingClientRect(),o=i?ib(l):null;return{domId:l.getAttribute("data-odid"),oid:l.getAttribute("data-oid"),frameId:Qi(),instanceId:l.getAttribute("data-oiid"),rect:n,tagName:l.tagName,parent:r,styles:o}};function Nt(l){try{let i=l.getAttribute("data-onlook-drag-saved-style");if(i){let t=JSON.parse(i);for(let r in t)l.style[r]=t[r]}}catch(i){console.warn("Error restoring style",i)}}function fb(l){let i=l.parentElement;if(!i)return;return{type:"index",targetDomId:i.getAttribute("data-odid"),targetOid:Kl(i)||Hl(i)||null,index:Array.from(l.parentElement?.children||[]).indexOf(l),originalIndex:Array.from(l.parentElement?.children||[]).indexOf(l)}}var gb=(l)=>{let i=Array.from(l.childNodes).filter((t)=>t.nodeType===Node.TEXT_NODE).map((t)=>t.textContent);if(i.length===0)return;return i.join("")};var Pt=(l,i)=>{let t=R(l)||document.body;return nl(t,i)},bb=(l,i,t)=>{let r=zm(l,i)||document.body;return nl(r,t)},zm=(l,i)=>{let t=document.elementFromPoint(l,i);if(!t)return;let r=(o)=>{if(o?.shadowRoot){let f=o.shadowRoot.elementFromPoint(l,i);if(f==o)return o;else if(f?.shadowRoot)return r(f);else return f||o}else return o};return r(t)||t},eb=(l,i,t)=>{let r=R(l);if(!r){console.warn("Failed to updateElementInstanceId: Element not found");return}r.setAttribute("data-oiid",i),r.setAttribute("data-ocname",t)},hb=(l)=>{let i=R(l);if(!i?.parentElement)return null;return nl(i.parentElement,!1)},cb=(l)=>{let i=R(l);if(!i)return 0;return i.children.length},mb=(l)=>{let i=R(l);if(!i)return null;return nl(i.offsetParent,!1)};function wb(l,i,t){let r=R(l.domId);if(!r)return console.warn("Failed to find parent element",l.domId),null;let n=xm(i),o=new Set(t.map((g)=>g.domId)),f=Array.from(r.children).map((g,h)=>({element:g,index:h,domId:Xl(g)})).filter(({domId:g})=>o.has(g));if(f.length===0)return console.warn("No valid children found to group"),null;let b=Math.min(...f.map((g)=>g.index));return r.insertBefore(n,r.children[b]??null),f.forEach(({element:g})=>{let h=g.cloneNode(!0);h.setAttribute("data-onlook-inserted","true"),n.appendChild(h),g.style.display="none",ub(g)}),{domEl:nl(n,!0),newMap:zl(n)}}function pb(l,i){let t=R(l.domId);if(!t)return console.warn(`Parent element not found: ${l.domId}`),null;let r;if(i.domId)r=R(i.domId);else return console.warn("Container domId is required for ungrouping"),null;if(!r)return console.warn("Container element not found for ungrouping"),null;return Array.from(r.children).forEach((f)=>{t.appendChild(f)}),r.remove(),{domEl:nl(t,!0),newMap:zl(t)}}function xm(l){let i=document.createElement(l.tagName);return Object.entries(l.attributes).forEach(([t,r])=>{i.setAttribute(t,r)}),i.setAttribute("data-onlook-inserted","true"),i.setAttribute("data-odid",l.domId),i.setAttribute("data-oid",l.oid),i}function ub(l){l.removeAttribute("data-odid"),l.removeAttribute("data-oid"),l.removeAttribute("data-onlook-inserted");let i=Array.from(l.children);if(i.length===0)return;i.forEach((t)=>{ub(t)})}function Ct(l){let i=R(l);if(!i)return console.warn("Element not found for domId:",l),null;return zb(i)}function zb(l){let i=Array.from(l.attributes).reduce((r,n)=>{return r[n.name]=n.value,r},{}),t=Kl(l)||Hl(l)||null;if(!t)return console.warn("Element has no oid"),null;return{oid:t,domId:Xl(l),tagName:l.tagName.toLowerCase(),children:Array.from(l.children).map((r)=>zb(r)).filter(Boolean),attributes:i,textContent:gb(l)||null,styles:{}}}function xb(l){let i=R(l);if(!i)throw new Error("Element not found for domId: "+l);let t=i.parentElement;if(!t)throw new Error("Inserted element has no parent");let r=Kl(t)||Hl(t);if(!r)return console.warn("Parent element has no oid"),null;let n=Xl(t),o=Array.from(t.children).indexOf(i);if(o===-1)return{type:"append",targetDomId:n,targetOid:r};return{type:"index",targetDomId:n,targetOid:r,index:o,originalIndex:o}}function ab(l){let i=document.querySelector(`[${"data-odid"}="${l}"]`);if(!i)return console.warn("No element found",{domId:l}),{dynamicType:null,coreType:null};let t=i.getAttribute("data-onlook-dynamic-type")||null,r=i.getAttribute("data-onlook-core-element-type")||null;return{dynamicType:t,coreType:r}}function vb(l,i,t){let r=document.querySelector(`[${"data-odid"}="${l}"]`);if(r){if(i)r.setAttribute("data-onlook-dynamic-type",i);if(t)r.setAttribute("data-onlook-core-element-type",t)}}function $b(){let i=document.body.querySelector(`[${"data-oid"}]`);if(i)return nl(i,!0);return null}var Yl=0,w=1,v=2,S=3,E=4,bl=5,Gi=6,tl=7,wl=8,J=9,$=10,U=11,O=12,Y=13,Cl=14,cl=15,C=16,d=17,ll=18,el=19,pl=20,j=21,a=22,N=23,ml=24,A=25;function ol(l){return l>=48&&l<=57}function ql(l){return ol(l)||l>=65&&l<=70||l>=97&&l<=102}function Tt(l){return l>=65&&l<=90}function am(l){return l>=97&&l<=122}function vm(l){return Tt(l)||am(l)}function $m(l){return l>=128}function Zt(l){return vm(l)||$m(l)||l===95}function mt(l){return Zt(l)||ol(l)||l===45}function _m(l){return l>=0&&l<=8||l===11||l>=14&&l<=31||l===127}function wt(l){return l===10||l===13||l===12}function Rl(l){return wt(l)||l===32||l===9}function _l(l,i){if(l!==92)return!1;if(wt(i)||i===0)return!1;return!0}function Bi(l,i,t){if(l===45)return Zt(i)||i===45||_l(i,t);if(Zt(l))return!0;if(l===92)return _l(l,i);return!1}function dt(l,i,t){if(l===43||l===45){if(ol(i))return 2;return i===46&&ol(t)?3:0}if(l===46)return ol(i)?2:0;if(ol(l))return 1;return 0}function lr(l){if(l===65279)return 1;if(l===65534)return 1;return 0}var Pr=new Array(128),qm=128,pt=130,Cr=131,ir=132,Ir=133;for(let l=0;ll.length)return!1;for(let n=i;n=0;i--)if(!Rl(l.charCodeAt(i)))break;return i+1}function ut(l,i){for(;i=55296&&i<=57343||i>1114111)i=65533;return String.fromCodePoint(i)}var Vi=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"];function Ei(l=null,i){if(l===null||l.length0?lr(i.charCodeAt(0)):0,n=Ei(l.lines,t),o=Ei(l.columns,t),f=l.startLine,b=l.startColumn;for(let e=r;e{}){l=String(l||"");let t=l.length,r=Ei(this.offsetAndType,l.length+1),n=Ei(this.balance,l.length+1),o=0,f=-1,b=0,e=l.length;this.offsetAndType=null,this.balance=null,n.fill(0),i(l,(g,h,c)=>{let m=o++;if(r[m]=g<>Ul]}else if(Xb(g))e=m,b=ai[g]}),r[o]=Yl<o)n[g]=o}this.source=l,this.firstCharOffset=f===-1?0:f,this.tokenCount=o,this.offsetAndType=r,this.balance=n,this.reset(),this.next()}lookupType(l){if(l+=this.tokenIndex,l>Ul;return Yl}lookupTypeNonSC(l){for(let i=this.tokenIndex;i>Ul;if(t!==Y&&t!==A){if(l--===0)return t}}return Yl}lookupOffset(l){if(l+=this.tokenIndex,l>Ul;if(t!==Y&&t!==A){if(l--===0)return i-this.tokenIndex}}return Yl}lookupValue(l,i){if(l+=this.tokenIndex,l0)return l>Ul,this.tokenEnd=i&Ml;else this.tokenIndex=this.tokenCount,this.next()}next(){let l=this.tokenIndex+1;if(l>Ul,this.tokenEnd=l&Ml;else this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=Yl,this.tokenStart=this.tokenEnd=this.source.length}skipSC(){while(this.tokenType===Y||this.tokenType===A)this.next()}skipUntilBalanced(l,i){let t=l,r=0,n=0;l:for(;t0?this.offsetAndType[t-1]&Ml:this.firstCharOffset,i(this.source.charCodeAt(n))){case 1:break l;case 2:t++;break l;default:if(Xb(this.offsetAndType[t]>>Ul))t=r}}this.skip(t-this.tokenIndex)}forEachToken(l){for(let i=0,t=this.firstCharOffset;i>Ul;t=o,l(f,r,o,i)}}dump(){let l=new Array(this.tokenCount);return this.forEachToken((i,t,r,n)=>{l[n]={idx:n,type:Vi[i],chunk:this.source.substring(t,r),balance:this.balance[n]}}),l}}function fi(l,i){function t(c){return c=l.length){if(gString(W+D+1).padStart(m)+" |"+L).join(` +var Rh=Object.create;var{getPrototypeOf:yh,defineProperty:Er,getOwnPropertyNames:Mh}=Object;var Uh=Object.prototype.hasOwnProperty;var rg=(l,i,t)=>{t=l!=null?Rh(yh(l)):{};let r=i||!l||!l.__esModule?Er(t,"default",{value:l,enumerable:!0}):t;for(let n of Mh(l))if(!Uh.call(r,n))Er(r,n,{get:()=>l[n],enumerable:!0});return r};var hl=(l,i)=>()=>(i||l((i={exports:{}}).exports,i),i.exports);var q=(l,i)=>{for(var t in i)Er(l,t,{get:i[t],enumerable:!0,configurable:!0,set:(r)=>i[t]=()=>r})};var Lr=hl((F5,ng)=>{function Ah(l){var i=typeof l;return l!=null&&(i=="object"||i=="function")}ng.exports=Ah});var fg=hl((V5,og)=>{var kh=typeof global=="object"&&global&&global.Object===Object&&global;og.exports=kh});var Hr=hl((E5,gg)=>{var Sh=fg(),Nh=typeof self=="object"&&self&&self.Object===Object&&self,Ph=Sh||Nh||Function("return this")();gg.exports=Ph});var eg=hl((L5,bg)=>{var Ch=Hr(),Ih=function(){return Ch.Date.now()};bg.exports=Ih});var cg=hl((H5,hg)=>{var Zh=/\s/;function Th(l){var i=l.length;while(i--&&Zh.test(l.charAt(i)));return i}hg.exports=Th});var wg=hl((K5,mg)=>{var dh=cg(),lc=/^\s+/;function ic(l){return l?l.slice(0,dh(l)+1).replace(lc,""):l}mg.exports=ic});var Kr=hl((R5,pg)=>{var tc=Hr(),rc=tc.Symbol;pg.exports=rc});var ag=hl((y5,xg)=>{var ug=Kr(),zg=Object.prototype,nc=zg.hasOwnProperty,oc=zg.toString,ht=ug?ug.toStringTag:void 0;function fc(l){var i=nc.call(l,ht),t=l[ht];try{l[ht]=void 0;var r=!0}catch(o){}var n=oc.call(l);if(r)if(i)l[ht]=t;else delete l[ht];return n}xg.exports=fc});var $g=hl((M5,vg)=>{var gc=Object.prototype,bc=gc.toString;function ec(l){return bc.call(l)}vg.exports=ec});var Dg=hl((U5,Jg)=>{var _g=Kr(),hc=ag(),cc=$g(),mc="[object Null]",wc="[object Undefined]",qg=_g?_g.toStringTag:void 0;function pc(l){if(l==null)return l===void 0?wc:mc;return qg&&qg in Object(l)?hc(l):cc(l)}Jg.exports=pc});var sg=hl((A5,Xg)=>{function uc(l){return l!=null&&typeof l=="object"}Xg.exports=uc});var jg=hl((k5,Wg)=>{var zc=Dg(),xc=sg(),ac="[object Symbol]";function vc(l){return typeof l=="symbol"||xc(l)&&zc(l)==ac}Wg.exports=vc});var Gg=hl((S5,Qg)=>{var $c=wg(),Og=Lr(),_c=jg(),Yg=NaN,qc=/^[-+]0x[0-9a-f]+$/i,Jc=/^0b[01]+$/i,Dc=/^0o[0-7]+$/i,Xc=parseInt;function sc(l){if(typeof l=="number")return l;if(_c(l))return Yg;if(Og(l)){var i=typeof l.valueOf=="function"?l.valueOf():l;l=Og(i)?i+"":i}if(typeof l!="string")return l===0?l:+l;l=$c(l);var t=Jc.test(l);return t||Dc.test(l)?Xc(l.slice(2),t?2:8):qc.test(l)?Yg:+l}Qg.exports=sc});var yr=hl((N5,Fg)=>{var Wc=Lr(),Rr=eg(),Bg=Gg(),jc="Expected a function",Oc=Math.max,Yc=Math.min;function Qc(l,i,t){var r,n,o,f,b,e,g=0,h=!1,c=!1,m=!0;if(typeof l!="function")throw new TypeError(jc);if(i=Bg(i)||0,Wc(t))h=!!t.leading,c="maxWait"in t,o=c?Oc(Bg(t.maxWait)||0,i):o,m="trailing"in t?!!t.trailing:m;function u(F){var M=r,T=n;return r=n=void 0,g=F,f=l.apply(T,M),f}function s(F){return g=F,b=setTimeout(D,i),h?u(F):f}function Z(F){var M=F-e,T=F-g,Vr=i-M;return c?Yc(Vr,o-T):Vr}function L(F){var M=F-e,T=F-g;return e===void 0||M>=i||M<0||c&&T>=o}function D(){var F=Rr();if(L(F))return H(F);b=setTimeout(D,Z(F))}function H(F){if(b=void 0,m&&r)return u(F);return r=n=void 0,f}function gl(){if(b!==void 0)clearTimeout(b);g=0,r=e=n=b=void 0}function K(){return b===void 0?f:H(Rr())}function B(){var F=Rr(),M=L(F);if(r=arguments,n=this,e=F,M){if(b===void 0)return s(e);if(c)return clearTimeout(b),b=setTimeout(D,i),u(e)}if(b===void 0)b=setTimeout(D,i);return f}return B.cancel=gl,B.flush=K,B}Fg.exports=Qc});var Vb=hl((jm)=>{var Fb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");jm.encode=function(l){if(0<=l&&l{var Eb=Vb(),rn=5,Lb=1<>1;return i?-t:t}Bm.encode=function l(i){var t="",r,n=Qm(i);do{if(r=n&Hb,n>>>=rn,n>0)r|=Kb;t+=Eb.encode(r)}while(n>0);return t};Bm.decode=function l(i,t,r){var n=i.length,o=0,f=0,b,e;do{if(t>=n)throw new Error("Expected more digits in base 64 VLQ value.");if(e=Eb.decode(i.charCodeAt(t++)),e===-1)throw new Error("Invalid base64 digit: "+i.charAt(t-1));b=!!(e&Kb),e&=Hb,o=o+(e<{function Em(l,i,t){if(i in l)return l[i];else if(arguments.length===3)return t;else throw new Error('"'+i+'" is a required argument.')}Im.getArg=Em;var yb=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,Lm=/^data:.+\,.+$/;function at(l){var i=l.match(yb);if(!i)return null;return{scheme:i[1],auth:i[2],host:i[3],port:i[4],path:i[5]}}Im.urlParse=at;function Hi(l){var i="";if(l.scheme)i+=l.scheme+":";if(i+="//",l.auth)i+=l.auth+"@";if(l.host)i+=l.host;if(l.port)i+=":"+l.port;if(l.path)i+=l.path;return i}Im.urlGenerate=Hi;var Hm=32;function Km(l){var i=[];return function(t){for(var r=0;rHm)i.pop();return o}}var nn=Km(function l(i){var t=i,r=at(i);if(r){if(!r.path)return i;t=r.path}var n=Im.isAbsolute(t),o=[],f=0,b=0;while(!0)if(f=b,b=t.indexOf("/",f),b===-1){o.push(t.slice(f));break}else{o.push(t.slice(f,b));while(b=0;b--)if(e=o[b],e===".")o.splice(b,1);else if(e==="..")g++;else if(g>0)if(e==="")o.splice(b+1,g),g=0;else o.splice(b,2),g--;if(t=o.join("/"),t==="")t=n?"/":".";if(r)return r.path=t,Hi(r);return t});Im.normalize=nn;function Mb(l,i){if(l==="")l=".";if(i==="")i=".";var t=at(i),r=at(l);if(r)l=r.path||"/";if(t&&!t.scheme){if(r)t.scheme=r.scheme;return Hi(t)}if(t||i.match(Lm))return i;if(r&&!r.host&&!r.path)return r.host=i,Hi(r);var n=i.charAt(0)==="/"?i:nn(l.replace(/\/+$/,"")+"/"+i);if(r)return r.path=n,Hi(r);return n}Im.join=Mb;Im.isAbsolute=function(l){return l.charAt(0)==="/"||yb.test(l)};function Rm(l,i){if(l==="")l=".";l=l.replace(/\/$/,"");var t=0;while(i.indexOf(l+"/")!==0){var r=l.lastIndexOf("/");if(r<0)return i;if(l=l.slice(0,r),l.match(/^([^\/]+:\/)?\/*$/))return i;++t}return Array(t+1).join("../")+i.substr(l.length+1)}Im.relative=Rm;var Ub=function(){var l=Object.create(null);return!("__proto__"in l)}();function Ab(l){return l}function ym(l){if(kb(l))return"$"+l;return l}Im.toSetString=Ub?Ab:ym;function Mm(l){if(kb(l))return l.slice(1);return l}Im.fromSetString=Ub?Ab:Mm;function kb(l){if(!l)return!1;var i=l.length;if(i<9)return!1;if(l.charCodeAt(i-1)!==95||l.charCodeAt(i-2)!==95||l.charCodeAt(i-3)!==111||l.charCodeAt(i-4)!==116||l.charCodeAt(i-5)!==111||l.charCodeAt(i-6)!==114||l.charCodeAt(i-7)!==112||l.charCodeAt(i-8)!==95||l.charCodeAt(i-9)!==95)return!1;for(var t=i-10;t>=0;t--)if(l.charCodeAt(t)!==36)return!1;return!0}function Um(l,i,t){var r=Tl(l.source,i.source);if(r!==0)return r;if(r=l.originalLine-i.originalLine,r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0||t)return r;if(r=l.generatedColumn-i.generatedColumn,r!==0)return r;if(r=l.generatedLine-i.generatedLine,r!==0)return r;return Tl(l.name,i.name)}Im.compareByOriginalPositions=Um;function Am(l,i,t){var r=l.originalLine-i.originalLine;if(r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0||t)return r;if(r=l.generatedColumn-i.generatedColumn,r!==0)return r;if(r=l.generatedLine-i.generatedLine,r!==0)return r;return Tl(l.name,i.name)}Im.compareByOriginalPositionsNoSource=Am;function km(l,i,t){var r=l.generatedLine-i.generatedLine;if(r!==0)return r;if(r=l.generatedColumn-i.generatedColumn,r!==0||t)return r;if(r=Tl(l.source,i.source),r!==0)return r;if(r=l.originalLine-i.originalLine,r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0)return r;return Tl(l.name,i.name)}Im.compareByGeneratedPositionsDeflated=km;function Sm(l,i,t){var r=l.generatedColumn-i.generatedColumn;if(r!==0||t)return r;if(r=Tl(l.source,i.source),r!==0)return r;if(r=l.originalLine-i.originalLine,r!==0)return r;if(r=l.originalColumn-i.originalColumn,r!==0)return r;return Tl(l.name,i.name)}Im.compareByGeneratedPositionsDeflatedNoLine=Sm;function Tl(l,i){if(l===i)return 0;if(l===null)return 1;if(i===null)return-1;if(l>i)return 1;return-1}function Nm(l,i){var t=l.generatedLine-i.generatedLine;if(t!==0)return t;if(t=l.generatedColumn-i.generatedColumn,t!==0)return t;if(t=Tl(l.source,i.source),t!==0)return t;if(t=l.originalLine-i.originalLine,t!==0)return t;if(t=l.originalColumn-i.originalColumn,t!==0)return t;return Tl(l.name,i.name)}Im.compareByGeneratedPositionsInflated=Nm;function Pm(l){return JSON.parse(l.replace(/^\)]}'[^\n]*\n/,""))}Im.parseSourceMapInput=Pm;function Cm(l,i,t){if(i=i||"",l){if(l[l.length-1]!=="/"&&i[0]!=="/")l+="/";i=l+i}if(t){var r=at(t);if(!r)throw new Error("sourceMapURL could not be parsed");if(r.path){var n=r.path.lastIndexOf("/");if(n>=0)r.path=r.path.substring(0,n+1)}i=Mb(Hi(r),i)}return nn(i)}Im.computeSourceURL=Cm});var Sb=hl((ww)=>{var on=gr(),fn=Object.prototype.hasOwnProperty,$i=typeof Map!=="undefined";function dl(){this._array=[],this._set=$i?new Map:Object.create(null)}dl.fromArray=function l(i,t){var r=new dl;for(var n=0,o=i.length;n=0)return t}else{var r=on.toSetString(i);if(fn.call(this._set,r))return this._set[r]}throw new Error('"'+i+'" is not in the set.')};dl.prototype.at=function l(i){if(i>=0&&i{var Nb=gr();function uw(l,i){var t=l.generatedLine,r=i.generatedLine,n=l.generatedColumn,o=i.generatedColumn;return r>t||r==t&&o>=n||Nb.compareByGeneratedPositionsInflated(l,i)<=0}function br(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}br.prototype.unsortedForEach=function l(i,t){this._array.forEach(i,t)};br.prototype.add=function l(i){if(uw(this._last,i))this._last=i,this._array.push(i);else this._sorted=!1,this._array.push(i)};br.prototype.toArray=function l(){if(!this._sorted)this._array.sort(Nb.compareByGeneratedPositionsInflated),this._sorted=!0;return this._array};zw.MappingList=br});var ji="PENPAL_CHILD";var Hh=rg(yr(),1);var Gc=class extends Error{code;constructor(l,i){super(i);this.name="PenpalError",this.code=l}},vl=Gc,Bc=(l)=>({name:l.name,message:l.message,stack:l.stack,penpalCode:l instanceof vl?l.code:void 0}),Fc=({name:l,message:i,stack:t,penpalCode:r})=>{let n=r?new vl(r,i):new Error(i);return n.name=l,n.stack=t,n},Vc=Symbol("Reply"),Ec=class{value;transferables;#l=Vc;constructor(l,i){this.value=l,this.transferables=i?.transferables}},Lc=Ec,Dl="penpal",At=(l)=>{return typeof l==="object"&&l!==null},Kg=(l)=>{return typeof l==="function"},Hc=(l)=>{return At(l)&&l.namespace===Dl},Oi=(l)=>{return l.type==="SYN"},kt=(l)=>{return l.type==="ACK1"},ct=(l)=>{return l.type==="ACK2"},Rg=(l)=>{return l.type==="CALL"},yg=(l)=>{return l.type==="REPLY"},Kc=(l)=>{return l.type==="DESTROY"},Mg=(l,i=[])=>{let t=[];for(let r of Object.keys(l)){let n=l[r];if(Kg(n))t.push([...i,r]);else if(At(n))t.push(...Mg(n,[...i,r]))}return t},Rc=(l,i)=>{let t=l.reduce((r,n)=>{return At(r)?r[n]:void 0},i);return Kg(t)?t:void 0},oi=(l)=>{return l.join(".")},Vg=(l,i,t)=>({namespace:Dl,channel:l,type:"REPLY",callId:i,isError:!0,...t instanceof Error?{value:Bc(t),isSerializedErrorInstance:!0}:{value:t}}),yc=(l,i,t,r)=>{let n=!1,o=async(f)=>{if(n)return;if(!Rg(f))return;r?.(`Received ${oi(f.methodPath)}() call`,f);let{methodPath:b,args:e,id:g}=f,h,c;try{let m=Rc(b,i);if(!m)throw new vl("METHOD_NOT_FOUND",`Method \`${oi(b)}\` is not found.`);let u=await m(...e);if(u instanceof Lc)c=u.transferables,u=await u.value;h={namespace:Dl,channel:t,type:"REPLY",callId:g,value:u}}catch(m){h=Vg(t,g,m)}if(n)return;try{r?.(`Sending ${oi(b)}() reply`,h),l.sendMessage(h,c)}catch(m){if(m.name==="DataCloneError")h=Vg(t,g,m),r?.(`Sending ${oi(b)}() reply`,h),l.sendMessage(h);throw m}};return l.addMessageHandler(o),()=>{n=!0,l.removeMessageHandler(o)}},Mc=yc,Ug=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),Uc=Symbol("CallOptions"),Ac=class{transferables;timeout;#l=Uc;constructor(l){this.transferables=l?.transferables,this.timeout=l?.timeout}},kc=Ac,Sc=new Set(["apply","call","bind"]),Ag=(l,i,t=[])=>{return new Proxy(t.length?()=>{}:Object.create(null),{get(r,n){if(n==="then")return;if(t.length&&Sc.has(n))return Reflect.get(r,n);return Ag(l,i,[...t,n])},apply(r,n,o){return l(t,o)}})},Eg=(l)=>{return new vl("CONNECTION_DESTROYED",`Method call ${oi(l)}() failed due to destroyed connection`)},Nc=(l,i,t)=>{let r=!1,n=new Map,o=(e)=>{if(!yg(e))return;let{callId:g,value:h,isError:c,isSerializedErrorInstance:m}=e,u=n.get(g);if(!u)return;if(n.delete(g),t?.(`Received ${oi(u.methodPath)}() call`,e),c)u.reject(m?Fc(h):h);else u.resolve(h)};return l.addMessageHandler(o),{remoteProxy:Ag((e,g)=>{if(r)throw Eg(e);let h=Ug(),c=g[g.length-1],m=c instanceof kc,{timeout:u,transferables:s}=m?c:{},Z=m?g.slice(0,-1):g;return new Promise((L,D)=>{let H=u!==void 0?window.setTimeout(()=>{n.delete(h),D(new vl("METHOD_CALL_TIMEOUT",`Method call ${oi(e)}() timed out after ${u}ms`))},u):void 0;n.set(h,{methodPath:e,resolve:L,reject:D,timeoutId:H});try{let gl={namespace:Dl,channel:i,type:"CALL",id:h,methodPath:e,args:Z};t?.(`Sending ${oi(e)}() call`,gl),l.sendMessage(gl,s)}catch(gl){D(new vl("TRANSMISSION_FAILED",gl.message))}})},t),destroy:()=>{r=!0,l.removeMessageHandler(o);for(let{methodPath:e,reject:g,timeoutId:h}of n.values())clearTimeout(h),g(Eg(e));n.clear()}}},Pc=Nc,Cc=()=>{let l,i;return{promise:new Promise((r,n)=>{l=r,i=n}),resolve:l,reject:i}},Ic=Cc,Zc=class extends Error{constructor(l){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${l}`)}},Yi=Zc,Mr="deprecated-penpal",Tc=(l)=>{return At(l)&&"penpal"in l},dc=(l)=>l.split("."),Lg=(l)=>l.join("."),kg=(l)=>{return new Yi(`Unexpected message to translate: ${JSON.stringify(l)}`)},lm=(l)=>{if(l.penpal==="syn")return{namespace:Dl,channel:void 0,type:"SYN",participantId:Mr};if(l.penpal==="ack")return{namespace:Dl,channel:void 0,type:"ACK2"};if(l.penpal==="call")return{namespace:Dl,channel:void 0,type:"CALL",id:l.id,methodPath:dc(l.methodName),args:l.args};if(l.penpal==="reply")if(l.resolution==="fulfilled")return{namespace:Dl,channel:void 0,type:"REPLY",callId:l.id,value:l.returnValue};else return{namespace:Dl,channel:void 0,type:"REPLY",callId:l.id,isError:!0,...l.returnValueIsError?{value:l.returnValue,isSerializedErrorInstance:!0}:{value:l.returnValue}};throw kg(l)},im=(l)=>{if(kt(l))return{penpal:"synAck",methodNames:l.methodPaths.map(Lg)};if(Rg(l))return{penpal:"call",id:l.id,methodName:Lg(l.methodPath),args:l.args};if(yg(l))if(l.isError)return{penpal:"reply",id:l.callId,resolution:"rejected",...l.isSerializedErrorInstance?{returnValue:l.value,returnValueIsError:!0}:{returnValue:l.value}};else return{penpal:"reply",id:l.callId,resolution:"fulfilled",returnValue:l.value};throw kg(l)},tm=({messenger:l,methods:i,timeout:t,channel:r,log:n})=>{let o=Ug(),f,b=[],e=!1,g=Mg(i),{promise:h,resolve:c,reject:m}=Ic(),u=t!==void 0?setTimeout(()=>{m(new vl("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,s=()=>{for(let B of b)B()},Z=()=>{if(e)return;b.push(Mc(l,i,r,n));let{remoteProxy:B,destroy:F}=Pc(l,r,n);b.push(F),clearTimeout(u),e=!0,c({remoteProxy:B,destroy:s})},L=()=>{let B={namespace:Dl,type:"SYN",channel:r,participantId:o};n?.("Sending handshake SYN",B);try{l.sendMessage(B)}catch(F){m(new vl("TRANSMISSION_FAILED",F.message))}},D=(B)=>{if(n?.("Received handshake SYN",B),B.participantId===f&&f!==Mr)return;if(f=B.participantId,L(),!(o>f||f===Mr))return;let M={namespace:Dl,channel:r,type:"ACK1",methodPaths:g};n?.("Sending handshake ACK1",M);try{l.sendMessage(M)}catch(T){m(new vl("TRANSMISSION_FAILED",T.message));return}},H=(B)=>{n?.("Received handshake ACK1",B);let F={namespace:Dl,channel:r,type:"ACK2"};n?.("Sending handshake ACK2",F);try{l.sendMessage(F)}catch(M){m(new vl("TRANSMISSION_FAILED",M.message));return}Z()},gl=(B)=>{n?.("Received handshake ACK2",B),Z()},K=(B)=>{if(Oi(B))D(B);if(kt(B))H(B);if(ct(B))gl(B)};return l.addMessageHandler(K),b.push(()=>l.removeMessageHandler(K)),L(),h},rm=tm,nm=(l)=>{let i=!1,t;return(...r)=>{if(!i)i=!0,t=l(...r);return t}},om=nm,Hg=new WeakSet,fm=({messenger:l,methods:i={},timeout:t,channel:r,log:n})=>{if(!l)throw new vl("INVALID_ARGUMENT","messenger must be defined");if(Hg.has(l))throw new vl("INVALID_ARGUMENT","A messenger can only be used for a single connection");Hg.add(l);let o=[l.destroy],f=om((g)=>{if(g){let h={namespace:Dl,channel:r,type:"DESTROY"};try{l.sendMessage(h)}catch(c){}}for(let h of o)h();n?.("Connection destroyed")}),b=(g)=>{return Hc(g)&&g.channel===r};return{promise:(async()=>{try{l.initialize({log:n,validateReceivedMessage:b}),l.addMessageHandler((c)=>{if(Kc(c))f(!1)});let{remoteProxy:g,destroy:h}=await rm({messenger:l,methods:i,timeout:t,channel:r,log:n});return o.push(h),g}catch(g){throw f(!0),g}})(),destroy:()=>{f(!0)}}},Sg=fm,gm=class{#l;#n;#t;#i;#f;#r=new Set;#o;#g=!1;constructor({remoteWindow:l,allowedOrigins:i}){if(!l)throw new vl("INVALID_ARGUMENT","remoteWindow must be defined");this.#l=l,this.#n=i?.length?i:[window.origin]}initialize=({log:l,validateReceivedMessage:i})=>{this.#t=l,this.#i=i,window.addEventListener("message",this.#c)};sendMessage=(l,i)=>{if(Oi(l)){let t=this.#b(l);this.#l.postMessage(l,{targetOrigin:t,transfer:i});return}if(kt(l)||this.#g){let t=this.#g?im(l):l,r=this.#b(l);this.#l.postMessage(t,{targetOrigin:r,transfer:i});return}if(ct(l)){let{port1:t,port2:r}=new MessageChannel;this.#o=t,t.addEventListener("message",this.#e),t.start();let n=[r,...i||[]],o=this.#b(l);this.#l.postMessage(l,{targetOrigin:o,transfer:n});return}if(this.#o){this.#o.postMessage(l,{transfer:i});return}throw new Yi("Port is undefined")};addMessageHandler=(l)=>{this.#r.add(l)};removeMessageHandler=(l)=>{this.#r.delete(l)};destroy=()=>{window.removeEventListener("message",this.#c),this.#h(),this.#r.clear()};#m=(l)=>{return this.#n.some((i)=>i instanceof RegExp?i.test(l):i===l||i==="*")};#b=(l)=>{if(Oi(l))return"*";if(!this.#f)throw new Yi("Concrete remote origin not set");return this.#f==="null"&&this.#n.includes("*")?"*":this.#f};#h=()=>{this.#o?.removeEventListener("message",this.#e),this.#o?.close(),this.#o=void 0};#c=({source:l,origin:i,ports:t,data:r})=>{if(l!==this.#l)return;if(Tc(r))this.#t?.("Please upgrade the child window to the latest version of Penpal."),this.#g=!0,r=lm(r);if(!this.#i?.(r))return;if(!this.#m(i)){this.#t?.(`Received a message from origin \`${i}\` which did not match allowed origins \`[${this.#n.join(", ")}]\``);return}if(Oi(r))this.#h(),this.#f=i;if(ct(r)&&!this.#g){if(this.#o=t[0],!this.#o)throw new Yi("No port received on ACK2");this.#o.addEventListener("message",this.#e),this.#o.start()}for(let n of this.#r)n(r)};#e=({data:l})=>{if(!this.#i?.(l))return;for(let i of this.#r)i(l)}},Ng=gm,P5=class{#l;#n;#t=new Set;#i;constructor({worker:l}){if(!l)throw new vl("INVALID_ARGUMENT","worker must be defined");this.#l=l}initialize=({validateReceivedMessage:l})=>{this.#n=l,this.#l.addEventListener("message",this.#r)};sendMessage=(l,i)=>{if(Oi(l)||kt(l)){this.#l.postMessage(l,{transfer:i});return}if(ct(l)){let{port1:t,port2:r}=new MessageChannel;this.#i=t,t.addEventListener("message",this.#r),t.start(),this.#l.postMessage(l,{transfer:[r,...i||[]]});return}if(this.#i){this.#i.postMessage(l,{transfer:i});return}throw new Yi("Port is undefined")};addMessageHandler=(l)=>{this.#t.add(l)};removeMessageHandler=(l)=>{this.#t.delete(l)};destroy=()=>{this.#l.removeEventListener("message",this.#r),this.#f(),this.#t.clear()};#f=()=>{this.#i?.removeEventListener("message",this.#r),this.#i?.close(),this.#i=void 0};#r=({ports:l,data:i})=>{if(!this.#n?.(i))return;if(Oi(i))this.#f();if(ct(i)){if(this.#i=l[0],!this.#i)throw new Yi("No port received on ACK2");this.#i.addEventListener("message",this.#r),this.#i.start()}for(let t of this.#t)t(i)}};var C5=class{#l;#n;#t=new Set;constructor({port:l}){if(!l)throw new vl("INVALID_ARGUMENT","port must be defined");this.#l=l}initialize=({validateReceivedMessage:l})=>{this.#n=l,this.#l.addEventListener("message",this.#i),this.#l.start()};sendMessage=(l,i)=>{this.#l?.postMessage(l,{transfer:i})};addMessageHandler=(l)=>{this.#t.add(l)};removeMessageHandler=(l)=>{this.#t.delete(l)};destroy=()=>{this.#l.removeEventListener("message",this.#i),this.#l.close(),this.#t.clear()};#i=({data:l})=>{if(!this.#n?.(l))return;for(let i of this.#t)i(l)}};var Pg=["SCRIPT","STYLE","LINK","META","NOSCRIPT"],Cg=new Set(["a","abbr","area","audio","b","bdi","bdo","br","button","canvas","cite","code","data","datalist","del","dfn","em","embed","h1","h2","h3","h4","h5","h6","i","iframe","img","input","ins","kbd","label","li","map","mark","meter","noscript","object","output","p","picture","progress","q","ruby","s","samp","script","select","slot","small","span","strong","sub","sup","svg","template","textarea","time","u","var","video","wbr"]);var Ur=".next-prod";var cx={SCALE:0.7,PAN_POSITION:{x:175,y:100},URL:"http://localhost:3000/",FRAME_POSITION:{x:0,y:0},FRAME_DIMENSION:{width:1536,height:960},ASPECT_RATIO_LOCKED:!1,DEVICE:"Custom:Custom",THEME:"system",ORIENTATION:"Portrait",MIN_DIMENSIONS:{width:"280px",height:"360px"},COMMANDS:{run:"bun run dev",build:"bun run build",install:"bun install"},IMAGE_FOLDER:"public",IMAGE_DIMENSION:{width:"100px",height:"100px"},FONT_FOLDER:"fonts",FONT_CONFIG:"app/fonts.ts",TAILWIND_CONFIG:"tailwind.config.ts",CHAT_SETTINGS:{showSuggestions:!0,autoApplyCode:!0,expandCodeBlocks:!1,showMiniChat:!0},EDITOR_SETTINGS:{shouldWarnDelete:!1,enableBunReplace:!0,buildFlags:"--no-lint"}};var Ar=["node_modules","dist","build",".git",".next"],px=[...Ar,"static","out",Ur],ux=[...Ar,Ur],zx=[...Ar,"coverage"],bm=[".jsx",".tsx"],em=[".js",".ts",".mjs",".cjs"],xx=[...bm,...em];var $x={["en"]:"English",["ja"]:"日本語",["zh"]:"中文",["ko"]:"한국어"};var dg=rg(yr(),1);function R(l){return document.querySelector(`[${"data-odid"}="${l}"]`)}function kr(l,i=!1){let t=`[${"data-odid"}="${l}"]`;if(!i)return t;return hm(t)}function hm(l){return CSS.escape(l)}function zi(l){return l&&l instanceof Node&&l.nodeType===Node.ELEMENT_NODE&&!Pg.includes(l.tagName)&&!l.hasAttribute("data-onlook-ignore")&&l.style.display!=="none"}var cm="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ig=(l=21)=>{let i="",t=l|0;while(t--)i+=cm[Math.random()*64|0];return i};function Xl(l){let i=l.getAttribute("data-odid");if(!i)i=`odid-${Ig()}`,l.setAttribute("data-odid",i);return i}function Hl(l){return l.getAttribute("data-oid")}function Kl(l){return l.getAttribute("data-oiid")}function Zg(l,i){if(!$l)return;$l.onDomProcessed({layerMap:Object.fromEntries(l),rootNode:i}).catch((t)=>{console.error("Failed to send DOM processed event:",t)})}function Sr(l){window._onlookFrameId=l}function Qi(){let l=window._onlookFrameId;if(!l)return console.warn("Frame id not found"),$l?.getFrameId().then((i)=>{Sr(i)}),"";return l}function mm(l=document.body){if(!Qi())return console.warn("frameView id not found, skipping dom processing"),null;let t=zl(l);if(!t)return console.warn("Error building layer tree, root element is null"),null;let r=l.getAttribute("data-odid");if(!r)return console.warn("Root dom id not found"),null;let n=t.get(r);if(!n)return console.warn("Root node not found"),null;return Zg(t,n),{rootDomId:r,layerMap:Array.from(t.entries())}}var St=dg.default(mm,500),wm=[(l)=>{let i=l.parentElement;return i&&i.tagName.toLowerCase()==="svg"},(l)=>{return l.tagName.toLowerCase()==="next-route-announcer"},(l)=>{return l.tagName.toLowerCase()==="nextjs-portal"}];function zl(l){if(!zi(l))return null;let i=new Map,t=document.createTreeWalker(l,NodeFilter.SHOW_ELEMENT,{acceptNode:(o)=>{let f=o;if(wm.some((b)=>b(f)))return NodeFilter.FILTER_REJECT;return zi(f)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}}),r=Tg(l);r.children=[],i.set(r.domId,r);let n=t.nextNode();while(n){let o=Tg(n);o.children=[];let f=n.parentElement;if(f){let b=f.getAttribute("data-odid");if(b){o.parent=b;let e=i.get(b);if(e&&e.children)e.children.push(o.domId)}}i.set(o.domId,o),n=t.nextNode()}return i}function Tg(l){let i=Xl(l),t=Hl(l),r=Kl(l),n=Array.from(l.childNodes).map((e)=>e.nodeType===Node.TEXT_NODE?e.textContent:"").join(" ").trim().slice(0,500),o=window.getComputedStyle(l),f=l.getAttribute("data-ocname");return{domId:i,oid:t||null,instanceId:r||null,textContent:n||"",tagName:l.tagName.toLowerCase(),isVisible:o.visibility!=="hidden",component:f||null,frameId:Qi(),children:null,parent:null,dynamicType:null,coreElementType:null}}function Nr(l){throw new Error(`Expected \`never\`, found: ${JSON.stringify(l)}`)}var lb=(l)=>JSON.parse(JSON.stringify(l));function ib(l){let i=rb(l),t=pm(l),r=um(l);return{defined:{width:"auto",height:"auto",...t,...r},computed:i}}function tb(l){let i=R(l);if(!i)return{};return rb(i)}function rb(l){return lb(window.getComputedStyle(l))}function pm(l){let i={},t=nb(l.style.cssText);return Object.entries(t).forEach(([r,n])=>{i[r]=n}),i}function um(l){let i={},t=document.styleSheets;for(let r=0;ri[g]=h)}}catch(b){console.warn("Error",b)}}return i}function nb(l){let i={};return l.split(";").forEach((t)=>{if(t=t.trim(),!t)return;let[r,...n]=t.split(":");i[r?.trim()??""]=n.join(":").trim()}),i}var ob=(l,i)=>{let t=document.elementFromPoint(l,i);if(!t)return;let r=(o)=>{if(o?.shadowRoot){let f=o.shadowRoot.elementFromPoint(l,i);if(f==o)return o;else if(f?.shadowRoot)return r(f);else return f||o}else return o};return r(t)||t},nl=(l,i)=>{let t=l.parentElement,r=t?{domId:t.getAttribute("data-odid"),frameId:Qi(),oid:t.getAttribute("data-oid"),instanceId:t.getAttribute("data-oiid"),rect:t.getBoundingClientRect()}:null,n=l.getBoundingClientRect(),o=i?ib(l):null;return{domId:l.getAttribute("data-odid"),oid:l.getAttribute("data-oid"),frameId:Qi(),instanceId:l.getAttribute("data-oiid"),rect:n,tagName:l.tagName,parent:r,styles:o}};function Nt(l){try{let i=l.getAttribute("data-onlook-drag-saved-style");if(i){let t=JSON.parse(i);for(let r in t)l.style[r]=t[r]}}catch(i){console.warn("Error restoring style",i)}}function fb(l){let i=l.parentElement;if(!i)return;return{type:"index",targetDomId:i.getAttribute("data-odid"),targetOid:Kl(i)||Hl(i)||null,index:Array.from(l.parentElement?.children||[]).indexOf(l),originalIndex:Array.from(l.parentElement?.children||[]).indexOf(l)}}var gb=(l)=>{let i=Array.from(l.childNodes).filter((t)=>t.nodeType===Node.TEXT_NODE).map((t)=>t.textContent);if(i.length===0)return;return i.join("")};var Pt=(l,i)=>{let t=R(l)||document.body;return nl(t,i)},bb=(l,i,t)=>{let r=zm(l,i)||document.body;return nl(r,t)},zm=(l,i)=>{let t=document.elementFromPoint(l,i);if(!t)return;let r=(o)=>{if(o?.shadowRoot){let f=o.shadowRoot.elementFromPoint(l,i);if(f==o)return o;else if(f?.shadowRoot)return r(f);else return f||o}else return o};return r(t)||t},eb=(l,i,t)=>{let r=R(l);if(!r){console.warn("Failed to updateElementInstanceId: Element not found");return}r.setAttribute("data-oiid",i),r.setAttribute("data-ocname",t)},hb=(l)=>{let i=R(l);if(!i?.parentElement)return null;return nl(i.parentElement,!1)},cb=(l)=>{let i=R(l);if(!i)return 0;return i.children.length},mb=(l)=>{let i=R(l);if(!i)return null;return nl(i.offsetParent,!1)};function wb(l,i,t){let r=R(l.domId);if(!r)return console.warn("Failed to find parent element",l.domId),null;let n=xm(i),o=new Set(t.map((g)=>g.domId)),f=Array.from(r.children).map((g,h)=>({element:g,index:h,domId:Xl(g)})).filter(({domId:g})=>o.has(g));if(f.length===0)return console.warn("No valid children found to group"),null;let b=Math.min(...f.map((g)=>g.index));return r.insertBefore(n,r.children[b]??null),f.forEach(({element:g})=>{let h=g.cloneNode(!0);h.setAttribute("data-onlook-inserted","true"),n.appendChild(h),g.style.display="none",ub(g)}),{domEl:nl(n,!0),newMap:zl(n)}}function pb(l,i){let t=R(l.domId);if(!t)return console.warn(`Parent element not found: ${l.domId}`),null;let r;if(i.domId)r=R(i.domId);else return console.warn("Container domId is required for ungrouping"),null;if(!r)return console.warn("Container element not found for ungrouping"),null;return Array.from(r.children).forEach((f)=>{t.appendChild(f)}),r.remove(),{domEl:nl(t,!0),newMap:zl(t)}}function xm(l){let i=document.createElement(l.tagName);return Object.entries(l.attributes).forEach(([t,r])=>{i.setAttribute(t,r)}),i.setAttribute("data-onlook-inserted","true"),i.setAttribute("data-odid",l.domId),i.setAttribute("data-oid",l.oid),i}function ub(l){l.removeAttribute("data-odid"),l.removeAttribute("data-oid"),l.removeAttribute("data-onlook-inserted");let i=Array.from(l.children);if(i.length===0)return;i.forEach((t)=>{ub(t)})}function Ct(l){let i=R(l);if(!i)return console.warn("Element not found for domId:",l),null;return zb(i)}function zb(l){let i=Array.from(l.attributes).reduce((r,n)=>{return r[n.name]=n.value,r},{}),t=Kl(l)||Hl(l)||null;if(!t)return console.warn("Element has no oid"),null;return{oid:t,domId:Xl(l),tagName:l.tagName.toLowerCase(),children:Array.from(l.children).map((r)=>zb(r)).filter(Boolean),attributes:i,textContent:gb(l)||null,styles:{}}}function xb(l){let i=R(l);if(!i)throw new Error("Element not found for domId: "+l);let t=i.parentElement;if(!t)throw new Error("Inserted element has no parent");let r=Kl(t)||Hl(t);if(!r)return console.warn("Parent element has no oid"),null;let n=Xl(t),o=Array.from(t.children).indexOf(i);if(o===-1)return{type:"append",targetDomId:n,targetOid:r};return{type:"index",targetDomId:n,targetOid:r,index:o,originalIndex:o}}function ab(l){let i=document.querySelector(`[${"data-odid"}="${l}"]`);if(!i)return console.warn("No element found",{domId:l}),{dynamicType:null,coreType:null};let t=i.getAttribute("data-onlook-dynamic-type")||null,r=i.getAttribute("data-onlook-core-element-type")||null;return{dynamicType:t,coreType:r}}function vb(l,i,t){let r=document.querySelector(`[${"data-odid"}="${l}"]`);if(r){if(i)r.setAttribute("data-onlook-dynamic-type",i);if(t)r.setAttribute("data-onlook-core-element-type",t)}}function $b(){let i=document.body.querySelector(`[${"data-oid"}]`);if(i)return nl(i,!0);return null}var Yl=0,w=1,v=2,S=3,E=4,bl=5,Gi=6,tl=7,wl=8,J=9,$=10,U=11,j=12,Y=13,Cl=14,cl=15,C=16,d=17,ll=18,el=19,pl=20,O=21,a=22,N=23,ml=24,A=25;function ol(l){return l>=48&&l<=57}function ql(l){return ol(l)||l>=65&&l<=70||l>=97&&l<=102}function Tt(l){return l>=65&&l<=90}function am(l){return l>=97&&l<=122}function vm(l){return Tt(l)||am(l)}function $m(l){return l>=128}function Zt(l){return vm(l)||$m(l)||l===95}function mt(l){return Zt(l)||ol(l)||l===45}function _m(l){return l>=0&&l<=8||l===11||l>=14&&l<=31||l===127}function wt(l){return l===10||l===13||l===12}function Rl(l){return wt(l)||l===32||l===9}function _l(l,i){if(l!==92)return!1;if(wt(i)||i===0)return!1;return!0}function Bi(l,i,t){if(l===45)return Zt(i)||i===45||_l(i,t);if(Zt(l))return!0;if(l===92)return _l(l,i);return!1}function dt(l,i,t){if(l===43||l===45){if(ol(i))return 2;return i===46&&ol(t)?3:0}if(l===46)return ol(i)?2:0;if(ol(l))return 1;return 0}function lr(l){if(l===65279)return 1;if(l===65534)return 1;return 0}var Pr=new Array(128),qm=128,pt=130,Cr=131,ir=132,Ir=133;for(let l=0;ll.length)return!1;for(let n=i;n=0;i--)if(!Rl(l.charCodeAt(i)))break;return i+1}function ut(l,i){for(;i=55296&&i<=57343||i>1114111)i=65533;return String.fromCodePoint(i)}var Vi=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"];function Ei(l=null,i){if(l===null||l.length0?lr(i.charCodeAt(0)):0,n=Ei(l.lines,t),o=Ei(l.columns,t),f=l.startLine,b=l.startColumn;for(let e=r;e{}){l=String(l||"");let t=l.length,r=Ei(this.offsetAndType,l.length+1),n=Ei(this.balance,l.length+1),o=0,f=-1,b=0,e=l.length;this.offsetAndType=null,this.balance=null,n.fill(0),i(l,(g,h,c)=>{let m=o++;if(r[m]=g<>Ul]}else if(Xb(g))e=m,b=ai[g]}),r[o]=Yl<o)n[g]=o}this.source=l,this.firstCharOffset=f===-1?0:f,this.tokenCount=o,this.offsetAndType=r,this.balance=n,this.reset(),this.next()}lookupType(l){if(l+=this.tokenIndex,l>Ul;return Yl}lookupTypeNonSC(l){for(let i=this.tokenIndex;i>Ul;if(t!==Y&&t!==A){if(l--===0)return t}}return Yl}lookupOffset(l){if(l+=this.tokenIndex,l>Ul;if(t!==Y&&t!==A){if(l--===0)return i-this.tokenIndex}}return Yl}lookupValue(l,i){if(l+=this.tokenIndex,l0)return l>Ul,this.tokenEnd=i&Ml;else this.tokenIndex=this.tokenCount,this.next()}next(){let l=this.tokenIndex+1;if(l>Ul,this.tokenEnd=l&Ml;else this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=Yl,this.tokenStart=this.tokenEnd=this.source.length}skipSC(){while(this.tokenType===Y||this.tokenType===A)this.next()}skipUntilBalanced(l,i){let t=l,r=0,n=0;l:for(;t0?this.offsetAndType[t-1]&Ml:this.firstCharOffset,i(this.source.charCodeAt(n))){case 1:break l;case 2:t++;break l;default:if(Xb(this.offsetAndType[t]>>Ul))t=r}}this.skip(t-this.tokenIndex)}forEachToken(l){for(let i=0,t=this.firstCharOffset;i>Ul;t=o,l(f,r,o,i)}}dump(){let l=new Array(this.tokenCount);return this.forEachToken((i,t,r,n)=>{l[n]={idx:n,type:Vi[i],chunk:this.source.substring(t,r),balance:this.balance[n]}}),l}}function fi(l,i){function t(c){return c=l.length){if(gString(s+D+1).padStart(m)+" |"+L).join(` `)}let b=` -`.repeat(Math.max(r-1,0)),e=" ".repeat(Math.max(n-1,0)),g=(b+e+l).split(/\r\n?|\n|\f/),h=Math.max(1,i-o)-1,c=Math.min(i+o,g.length+1),m=Math.max(4,String(c).length)+1,u=0;if(t+=(sb.length-1)*(g[i-1].substr(0,t-1).match(/\t/g)||[]).length,t>Tr)u=t-Wb+3,t=Wb-2;for(let W=h;W<=c;W++)if(W>=0&&W0&&g[W].length>u?"…":"")+g[W].substr(u,Tr-2)+(g[W].length>u+Tr-1?"…":"");return[f(h,i),new Array(t+m+2).join("-")+"^",f(i,c)].filter(Boolean).join(` -`).replace(/^(\s+\d+\s+\|\n)+/,"").replace(/\n(\s+\d+\s+\|)+$/,"")}function dr(l,i,t,r,n,o=1,f=1){return Object.assign(vi("SyntaxError",l),{source:i,offset:t,line:r,column:n,sourceFragment(e){return Ob({source:i,line:r,column:n,baseLine:o,baseColumn:f},isNaN(e)?0:e)},get formattedMessage(){return`Parse error: ${l} -`+Ob({source:i,line:r,column:n,baseLine:o,baseColumn:f},2)}})}function jb(l){let i=this.createList(),t=!1,r={recognizer:l};while(!this.eof){switch(this.tokenType){case A:this.next();continue;case Y:t=!0,this.next();continue}let n=l.getNode.call(this,r);if(n===void 0)break;if(t){if(l.onWhiteSpace)l.onWhiteSpace.call(this,n,i,r);t=!1}i.push(n)}if(t&&l.onWhiteSpace)l.onWhiteSpace.call(this,null,i,r);return i}var Yb=()=>{},Dm=33,Xm=35,ln=59,Qb=123,Gb=0;function Wm(l){return function(){return this[l]()}}function tn(l){let i=Object.create(null);for(let t of Object.keys(l)){let r=l[t],n=r.parse||r;if(n)i[t]=n}return i}function sm(l){let i={context:Object.create(null),features:Object.assign(Object.create(null),l.features),scope:Object.assign(Object.create(null),l.scope),atrule:tn(l.atrule),pseudo:tn(l.pseudo),node:tn(l.node)};for(let[t,r]of Object.entries(l.parseContext))switch(typeof r){case"function":i.context[t]=r;break;case"string":i.context[t]=Wm(r);break}return{config:i,...i,...i.node}}function Bb(l){let i="",t="",r=!1,n=Yb,o=!1,f=new or,b=Object.assign(new fr,sm(l||{}),{parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:jb,consumeUntilBalanceEnd:()=>0,consumeUntilLeftCurlyBracket(g){return g===Qb?1:0},consumeUntilLeftCurlyBracketOrSemicolon(g){return g===Qb||g===ln?1:0},consumeUntilExclamationMarkOrSemicolon(g){return g===Dm||g===ln?1:0},consumeUntilSemicolonIncluded(g){return g===ln?2:0},createList(){return new il},createSingleNodeList(g){return new il().appendData(g)},getFirstListNode(g){return g&&g.first},getLastListNode(g){return g&&g.last},parseWithFallback(g,h){let c=this.tokenIndex;try{return g.call(this)}catch(m){if(o)throw m;this.skip(c-this.tokenIndex);let u=h.call(this);return o=!0,n(m,u),o=!1,u}},lookupNonWSType(g){let h;do if(h=this.lookupType(g++),h!==Y&&h!==A)return h;while(h!==Gb);return Gb},charCodeAt(g){return g>=0&&gu.toUpperCase()),c=`${/[[\](){}]/.test(h)?`"${h}"`:h} is expected`,m=this.tokenStart;switch(g){case w:if(this.tokenType===v||this.tokenType===tl)m=this.tokenEnd-1,c="Identifier is expected but function found";else c="Identifier is expected";break;case E:if(this.isDelim(Xm))this.next(),m++,c="Name is expected";break;case U:if(this.tokenType===$)m=this.tokenEnd,c="Percent sign is expected";break}this.error(c,m)}this.next()},eatIdent(g){if(this.tokenType!==w||this.lookupValue(0,g)===!1)this.error(`Identifier "${g}" is expected`);this.next()},eatDelim(g){if(!this.isDelim(g))this.error(`Delim "${String.fromCharCode(g)}" is expected`);this.next()},getLocation(g,h){if(r)return f.getLocationRange(g,h,t);return null},getLocationFromList(g){if(r){let h=this.getFirstListNode(g),c=this.getLastListNode(g);return f.getLocationRange(h!==null?h.loc.start.offset-f.startOffset:this.tokenStart,c!==null?c.loc.end.offset-f.startOffset:this.tokenStart,t)}return null},error(g,h){let c=typeof h!=="undefined"&&h",r=Boolean(h.positions),n=typeof h.onParseError==="function"?h.onParseError:Yb,o=!1,b.parseAtrulePrelude="parseAtrulePrelude"in h?Boolean(h.parseAtrulePrelude):!0,b.parseRulePrelude="parseRulePrelude"in h?Boolean(h.parseRulePrelude):!0,b.parseValue="parseValue"in h?Boolean(h.parseValue):!0,b.parseCustomProperty="parseCustomProperty"in h?Boolean(h.parseCustomProperty):!1;let{context:c="default",onComment:m}=h;if(c in b.context===!1)throw new Error("Unknown context `"+c+"`");if(typeof m==="function")b.forEachToken((W,Z,L)=>{if(W===A){let D=b.getLocation(Z,L),H=Zl(i,L-2,L,"*/")?i.slice(Z+2,L-2):i.slice(Z+2,L);m(H,D)}});let u=b.context[c].call(b,h);if(!b.eof)b.error();return u},{SyntaxError:dr,config:b.config})}var vt=Rb(),fl=gr(),er=Sb().ArraySet,aw=Pb().MappingList;function Ol(l){if(!l)l={};this._file=fl.getArg(l,"file",null),this._sourceRoot=fl.getArg(l,"sourceRoot",null),this._skipValidation=fl.getArg(l,"skipValidation",!1),this._ignoreInvalidMapping=fl.getArg(l,"ignoreInvalidMapping",!1),this._sources=new er,this._names=new er,this._mappings=new aw,this._sourcesContents=null}Ol.prototype._version=3;Ol.fromSourceMap=function l(i,t){var r=i.sourceRoot,n=new Ol(Object.assign(t||{},{file:i.file,sourceRoot:r}));return i.eachMapping(function(o){var f={generated:{line:o.generatedLine,column:o.generatedColumn}};if(o.source!=null){if(f.source=o.source,r!=null)f.source=fl.relative(r,f.source);if(f.original={line:o.originalLine,column:o.originalColumn},o.name!=null)f.name=o.name}n.addMapping(f)}),i.sources.forEach(function(o){var f=o;if(r!==null)f=fl.relative(r,o);if(!n._sources.has(f))n._sources.add(f);var b=i.sourceContentFor(o);if(b!=null)n.setSourceContent(o,b)}),n};Ol.prototype.addMapping=function l(i){var t=fl.getArg(i,"generated"),r=fl.getArg(i,"original",null),n=fl.getArg(i,"source",null),o=fl.getArg(i,"name",null);if(!this._skipValidation){if(this._validateMapping(t,r,n,o)===!1)return}if(n!=null){if(n=String(n),!this._sources.has(n))this._sources.add(n)}if(o!=null){if(o=String(o),!this._names.has(o))this._names.add(o)}this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:n,name:o})};Ol.prototype.setSourceContent=function l(i,t){var r=i;if(this._sourceRoot!=null)r=fl.relative(this._sourceRoot,r);if(t!=null){if(!this._sourcesContents)this._sourcesContents=Object.create(null);this._sourcesContents[fl.toSetString(r)]=t}else if(this._sourcesContents){if(delete this._sourcesContents[fl.toSetString(r)],Object.keys(this._sourcesContents).length===0)this._sourcesContents=null}};Ol.prototype.applySourceMap=function l(i,t,r){var n=t;if(t==null){if(i.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);n=i.file}var o=this._sourceRoot;if(o!=null)n=fl.relative(o,n);var f=new er,b=new er;this._mappings.unsortedForEach(function(e){if(e.source===n&&e.originalLine!=null){var g=i.originalPositionFor({line:e.originalLine,column:e.originalColumn});if(g.source!=null){if(e.source=g.source,r!=null)e.source=fl.join(r,e.source);if(o!=null)e.source=fl.relative(o,e.source);if(e.originalLine=g.line,e.originalColumn=g.column,g.name!=null)e.name=g.name}}var h=e.source;if(h!=null&&!f.has(h))f.add(h);var c=e.name;if(c!=null&&!b.has(c))b.add(c)},this),this._sources=f,this._names=b,i.sources.forEach(function(e){var g=i.sourceContentFor(e);if(g!=null){if(r!=null)e=fl.join(r,e);if(o!=null)e=fl.relative(o,e);this.setSourceContent(e,g)}},this)};Ol.prototype._validateMapping=function l(i,t,r,n){if(t&&typeof t.line!=="number"&&typeof t.column!=="number"){var o="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping){if(typeof console!=="undefined"&&console.warn)console.warn(o);return!1}else throw new Error(o)}if(i&&"line"in i&&"column"in i&&i.line>0&&i.column>=0&&!t&&!r&&!n)return;else if(i&&"line"in i&&"column"in i&&t&&"line"in t&&"column"in t&&i.line>0&&i.column>=0&&t.line>0&&t.column>=0&&r)return;else{var o="Invalid mapping: "+JSON.stringify({generated:i,source:r,original:t,name:n});if(this._ignoreInvalidMapping){if(typeof console!=="undefined"&&console.warn)console.warn(o);return!1}else throw new Error(o)}};Ol.prototype._serializeMappings=function l(){var i=0,t=1,r=0,n=0,o=0,f=0,b="",e,g,h,c,m=this._mappings.toArray();for(var u=0,W=m.length;u0){if(!fl.compareByGeneratedPositionsInflated(g,m[u-1]))continue;e+=","}if(e+=vt.encode(g.generatedColumn-i),i=g.generatedColumn,g.source!=null){if(c=this._sources.indexOf(g.source),e+=vt.encode(c-f),f=c,e+=vt.encode(g.originalLine-1-n),n=g.originalLine-1,e+=vt.encode(g.originalColumn-r),r=g.originalColumn,g.name!=null)h=this._names.indexOf(g.name),e+=vt.encode(h-o),o=h}b+=e}return b};Ol.prototype._generateSourcesContent=function l(i,t){return i.map(function(r){if(!this._sourcesContents)return null;if(t!=null)r=fl.relative(t,r);var n=fl.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)};Ol.prototype.toJSON=function l(){var i={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null)i.file=this._file;if(this._sourceRoot!=null)i.sourceRoot=this._sourceRoot;if(this._sourcesContents)i.sourcesContent=this._generateSourcesContent(i.sources,i.sourceRoot);return i};Ol.prototype.toString=function l(){return JSON.stringify(this.toJSON())};var gn=Ol;var Cb=new Set(["Atrule","Selector","Declaration"]);function Ib(l){let i=new gn,t={line:1,column:0},r={line:0,column:0},n={line:1,column:0},o={generated:n},f=1,b=0,e=!1,g=l.node;l.node=function(m){if(m.loc&&m.loc.start&&Cb.has(m.type)){let u=m.loc.start.line,W=m.loc.start.column-1;if(r.line!==u||r.column!==W){if(r.line=u,r.column=W,t.line=f,t.column=b,e){if(e=!1,t.line!==n.line||t.column!==n.column)i.addMapping(o)}e=!0,i.addMapping({source:m.loc.source,original:r,generated:t})}}if(g.call(this,m),e&&Cb.has(m.type))n.line=f,n.column=b};let h=l.emit;l.emit=function(m,u,W){for(let Z=0;Zqw,safe:()=>en});var vw=43,$w=45,bn=(l,i)=>{if(l===J)l=i;if(typeof l==="string"){let t=l.charCodeAt(0);return t>127?32768:t<<8}return l},Zb=[[w,w],[w,v],[w,tl],[w,wl],[w,"-"],[w,$],[w,U],[w,O],[w,cl],[w,j],[S,w],[S,v],[S,tl],[S,wl],[S,"-"],[S,$],[S,U],[S,O],[S,cl],[E,w],[E,v],[E,tl],[E,wl],[E,"-"],[E,$],[E,U],[E,O],[E,cl],[O,w],[O,v],[O,tl],[O,wl],[O,"-"],[O,$],[O,U],[O,O],[O,cl],["#",w],["#",v],["#",tl],["#",wl],["#","-"],["#",$],["#",U],["#",O],["#",cl],["-",w],["-",v],["-",tl],["-",wl],["-","-"],["-",$],["-",U],["-",O],["-",cl],[$,w],[$,v],[$,tl],[$,wl],[$,$],[$,U],[$,O],[$,"%"],[$,cl],["@",w],["@",v],["@",tl],["@",wl],["@","-"],["@",cl],[".",$],[".",U],[".",O],["+",$],["+",U],["+",O],["/","*"]],_w=Zb.concat([[w,E],[O,E],[E,E],[S,j],[S,bl],[S,C],[U,U],[U,O],[U,v],[U,"-"],[a,w],[a,v],[a,U],[a,O],[a,E],[a,"-"]]);function Tb(l){let i=new Set(l.map(([t,r])=>bn(t)<<16|bn(r)));return function(t,r,n){let o=bn(r,n),f=n.charCodeAt(0);if(f===$w&&r!==w&&r!==v&&r!==cl||f===vw?i.has(t<<16|f<<8):i.has(t<<16|o))this.emit(" ",Y,!0);return o}}var qw=Tb(Zb),en=Tb(_w);var Jw=92;function Dw(l,i){if(typeof i==="function"){let t=null;l.children.forEach((r)=>{if(t!==null)i.call(this,t);this.node(r),t=r});return}l.children.forEach(this.node,this)}function Xw(l){fi(l,(i,t,r)=>{this.token(i,l.slice(t,r))})}function db(l){let i=new Map;for(let[t,r]of Object.entries(l.node))if(typeof(r.generate||r)==="function")i.set(t,r.generate||r);return function(t,r){let n="",o=0,f={node(e){if(i.has(e.type))i.get(e.type).call(b,e);else throw new Error("Unknown node type: "+e.type)},tokenBefore:en,token(e,g){if(o=this.tokenBefore(o,e,g),this.emit(g,e,!1),e===J&&g.charCodeAt(0)===Jw)this.emit(` -`,Y,!0)},emit(e){n+=e},result(){return n}};if(r){if(typeof r.decorator==="function")f=r.decorator(f);if(r.sourceMap)f=Ib(f);if(r.mode in hr)f.tokenBefore=hr[r.mode]}let b={node:(e)=>f.node(e),children:Dw,token:(e,g)=>f.token(e,g),tokenize:Xw};return f.node(t),f.result()}}function l0(l){return{fromPlainObject(i){return l(i,{enter(t){if(t.children&&t.children instanceof il===!1)t.children=new il().fromArray(t.children)}}),i},toPlainObject(i){return l(i,{leave(t){if(t.children&&t.children instanceof il)t.children=t.children.toArray()}}),i}}}var{hasOwnProperty:hn}=Object.prototype,$t=function(){};function i0(l){return typeof l==="function"?l:$t}function t0(l,i){return function(t,r,n){if(t.type===i)l.call(this,t,r,n)}}function Ww(l,i){let t=i.structure,r=[];for(let n in t){if(hn.call(t,n)===!1)continue;let o=t[n],f={name:n,type:!1,nullable:!1};if(!Array.isArray(o))o=[o];for(let b of o)if(b===null)f.nullable=!0;else if(typeof b==="string")f.type="node";else if(Array.isArray(b))f.type="list";if(f.type)r.push(f)}if(r.length)return{context:i.walkContext,fields:r};return null}function sw(l){let i={};for(let t in l.node)if(hn.call(l.node,t)){let r=l.node[t];if(!r.structure)throw new Error("Missed `structure` field in `"+t+"` node type definition");i[t]=Ww(t,r)}return i}function r0(l,i){let t=l.fields.slice(),r=l.context,n=typeof r==="string";if(i)t.reverse();return function(o,f,b,e){let g;if(n)g=f[r],f[r]=o;for(let h of t){let c=o[h.name];if(!h.nullable||c){if(h.type==="list"){if(i?c.reduceRight(e,!1):c.reduce(e,!1))return!0}else if(b(c))return!0}}if(n)f[r]=g}}function n0({StyleSheet:l,Atrule:i,Rule:t,Block:r,DeclarationList:n}){return{Atrule:{StyleSheet:l,Atrule:i,Rule:t,Block:r},Rule:{StyleSheet:l,Atrule:i,Rule:t,Block:r},Declaration:{StyleSheet:l,Atrule:i,Rule:t,Block:r,DeclarationList:n}}}function o0(l){let i=sw(l),t={},r={},n=Symbol("break-walk"),o=Symbol("skip-node");for(let g in i)if(hn.call(i,g)&&i[g]!==null)t[g]=r0(i[g],!1),r[g]=r0(i[g],!0);let f=n0(t),b=n0(r),e=function(g,h){function c(D,H,gl){let K=m.call(L,D,H,gl);if(K===n)return!0;if(K===o)return!1;if(W.hasOwnProperty(D.type)){if(W[D.type](D,L,c,Z))return!0}if(u.call(L,D,H,gl)===n)return!0;return!1}let m=$t,u=$t,W=t,Z=(D,H,gl,K)=>D||c(H,gl,K),L={break:n,skip:o,root:g,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null};if(typeof h==="function")m=h;else if(h){if(m=i0(h.enter),u=i0(h.leave),h.reverse)W=r;if(h.visit){if(f.hasOwnProperty(h.visit))W=h.reverse?b[h.visit]:f[h.visit];else if(!i.hasOwnProperty(h.visit))throw new Error("Bad value `"+h.visit+"` for `visit` option (should be: "+Object.keys(i).sort().join(", ")+")");m=t0(m,h.visit),u=t0(u,h.visit)}}if(m===$t&&u===$t)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");c(g)};return e.break=n,e.skip=o,e.find=function(g,h){let c=null;return e(g,function(m,u,W){if(h.call(this,m,u,W))return c=m,n}),c},e.findLast=function(g,h){let c=null;return e(g,{reverse:!0,enter(m,u,W){if(h.call(this,m,u,W))return c=m,n}}),c},e.findAll=function(g,h){let c=[];return e(g,function(m,u,W){if(h.call(this,m,u,W))c.push(m)}),c},e}function Ow(l){return l}function jw(l){let{min:i,max:t,comma:r}=l;if(i===0&&t===0)return r?"#?":"*";if(i===0&&t===1)return"?";if(i===1&&t===0)return r?"#":"+";if(i===1&&t===1)return"";return(r?"#":"")+(i===t?"{"+i+"}":"{"+i+","+(t!==0?t:"")+"}")}function Yw(l){switch(l.type){case"Range":return" ["+(l.min===null?"-∞":l.min)+","+(l.max===null?"∞":l.max)+"]";default:throw new Error("Unknown node type `"+l.type+"`")}}function Qw(l,i,t,r){let n=l.combinator===" "||r?l.combinator:" "+l.combinator+" ",o=l.terms.map((f)=>cr(f,i,t,r)).join(n);if(l.explicit||t)return(r||o[0]===","?"[":"[ ")+o+(r?"]":" ]");return o}function cr(l,i,t,r){let n;switch(l.type){case"Group":n=Qw(l,i,t,r)+(l.disallowEmpty?"!":"");break;case"Multiplier":return cr(l.term,i,t,r)+i(jw(l),l);case"Boolean":n="";break;case"Type":n="<"+l.name+(l.opts?i(Yw(l.opts),l.opts):"")+">";break;case"Property":n="<'"+l.name+"'>";break;case"Keyword":n=l.name;break;case"AtKeyword":n="@"+l.name;break;case"Function":n=l.name+"(";break;case"String":case"Token":n=l.value;break;case"Comma":n=",";break;default:throw new Error("Unknown node type `"+l.type+"`")}return i(n,l)}function Ki(l,i){let t=Ow,r=!1,n=!1;if(typeof i==="function")t=i;else if(i){if(r=Boolean(i.forceBraces),n=Boolean(i.compact),typeof i.decorate==="function")t=i.decorate}return cr(l,t,r,n)}var f0={offset:0,line:1,column:1};function Gw(l,i){let{tokens:t,longestMatch:r}=l,n=r1)h=mr(o||i,"end")||_t(f0,g),c=_t(h);else h=mr(o,"start")||_t(mr(i,"start")||f0,g.slice(0,f)),c=mr(o,"end")||_t(h,g.substr(f,b));return{css:g,mismatchOffset:f,mismatchLength:b,start:h,end:c}}function mr(l,i){let t=l&&l.loc&&l.loc[i];if(t)return"line"in t?_t(t):t;return null}function _t({offset:l,line:i,column:t},r){let n={offset:l,line:i,column:t};if(r){let o=r.split(/\n|\r\n?|\f/);n.offset+=r.length,n.line+=o.length-1,n.column=o.length===1?n.column+r.length:o.pop().length+1}return n}var Ri=function(l,i){let t=vi("SyntaxReferenceError",l+(i?" `"+i+"`":""));return t.reference=i,t},g0=function(l,i,t,r){let n=vi("SyntaxMatchError",l),{css:o,mismatchOffset:f,mismatchLength:b,start:e,end:g}=Gw(r,t);return n.rawMessage=l,n.syntax=i?Ki(i):"",n.css=o,n.mismatchOffset=f,n.mismatchLength=b,n.message=l+` +`.repeat(Math.max(r-1,0)),e=" ".repeat(Math.max(n-1,0)),g=(b+e+l).split(/\r\n?|\n|\f/),h=Math.max(1,i-o)-1,c=Math.min(i+o,g.length+1),m=Math.max(4,String(c).length)+1,u=0;if(t+=(Wb.length-1)*(g[i-1].substr(0,t-1).match(/\t/g)||[]).length,t>Tr)u=t-sb+3,t=sb-2;for(let s=h;s<=c;s++)if(s>=0&&s0&&g[s].length>u?"…":"")+g[s].substr(u,Tr-2)+(g[s].length>u+Tr-1?"…":"");return[f(h,i),new Array(t+m+2).join("-")+"^",f(i,c)].filter(Boolean).join(` +`).replace(/^(\s+\d+\s+\|\n)+/,"").replace(/\n(\s+\d+\s+\|)+$/,"")}function dr(l,i,t,r,n,o=1,f=1){return Object.assign(vi("SyntaxError",l),{source:i,offset:t,line:r,column:n,sourceFragment(e){return jb({source:i,line:r,column:n,baseLine:o,baseColumn:f},isNaN(e)?0:e)},get formattedMessage(){return`Parse error: ${l} +`+jb({source:i,line:r,column:n,baseLine:o,baseColumn:f},2)}})}function Ob(l){let i=this.createList(),t=!1,r={recognizer:l};while(!this.eof){switch(this.tokenType){case A:this.next();continue;case Y:t=!0,this.next();continue}let n=l.getNode.call(this,r);if(n===void 0)break;if(t){if(l.onWhiteSpace)l.onWhiteSpace.call(this,n,i,r);t=!1}i.push(n)}if(t&&l.onWhiteSpace)l.onWhiteSpace.call(this,null,i,r);return i}var Yb=()=>{},Dm=33,Xm=35,ln=59,Qb=123,Gb=0;function sm(l){return function(){return this[l]()}}function tn(l){let i=Object.create(null);for(let t of Object.keys(l)){let r=l[t],n=r.parse||r;if(n)i[t]=n}return i}function Wm(l){let i={context:Object.create(null),features:Object.assign(Object.create(null),l.features),scope:Object.assign(Object.create(null),l.scope),atrule:tn(l.atrule),pseudo:tn(l.pseudo),node:tn(l.node)};for(let[t,r]of Object.entries(l.parseContext))switch(typeof r){case"function":i.context[t]=r;break;case"string":i.context[t]=sm(r);break}return{config:i,...i,...i.node}}function Bb(l){let i="",t="",r=!1,n=Yb,o=!1,f=new or,b=Object.assign(new fr,Wm(l||{}),{parseAtrulePrelude:!0,parseRulePrelude:!0,parseValue:!0,parseCustomProperty:!1,readSequence:Ob,consumeUntilBalanceEnd:()=>0,consumeUntilLeftCurlyBracket(g){return g===Qb?1:0},consumeUntilLeftCurlyBracketOrSemicolon(g){return g===Qb||g===ln?1:0},consumeUntilExclamationMarkOrSemicolon(g){return g===Dm||g===ln?1:0},consumeUntilSemicolonIncluded(g){return g===ln?2:0},createList(){return new il},createSingleNodeList(g){return new il().appendData(g)},getFirstListNode(g){return g&&g.first},getLastListNode(g){return g&&g.last},parseWithFallback(g,h){let c=this.tokenIndex;try{return g.call(this)}catch(m){if(o)throw m;this.skip(c-this.tokenIndex);let u=h.call(this);return o=!0,n(m,u),o=!1,u}},lookupNonWSType(g){let h;do if(h=this.lookupType(g++),h!==Y&&h!==A)return h;while(h!==Gb);return Gb},charCodeAt(g){return g>=0&&gu.toUpperCase()),c=`${/[[\](){}]/.test(h)?`"${h}"`:h} is expected`,m=this.tokenStart;switch(g){case w:if(this.tokenType===v||this.tokenType===tl)m=this.tokenEnd-1,c="Identifier is expected but function found";else c="Identifier is expected";break;case E:if(this.isDelim(Xm))this.next(),m++,c="Name is expected";break;case U:if(this.tokenType===$)m=this.tokenEnd,c="Percent sign is expected";break}this.error(c,m)}this.next()},eatIdent(g){if(this.tokenType!==w||this.lookupValue(0,g)===!1)this.error(`Identifier "${g}" is expected`);this.next()},eatDelim(g){if(!this.isDelim(g))this.error(`Delim "${String.fromCharCode(g)}" is expected`);this.next()},getLocation(g,h){if(r)return f.getLocationRange(g,h,t);return null},getLocationFromList(g){if(r){let h=this.getFirstListNode(g),c=this.getLastListNode(g);return f.getLocationRange(h!==null?h.loc.start.offset-f.startOffset:this.tokenStart,c!==null?c.loc.end.offset-f.startOffset:this.tokenStart,t)}return null},error(g,h){let c=typeof h!=="undefined"&&h",r=Boolean(h.positions),n=typeof h.onParseError==="function"?h.onParseError:Yb,o=!1,b.parseAtrulePrelude="parseAtrulePrelude"in h?Boolean(h.parseAtrulePrelude):!0,b.parseRulePrelude="parseRulePrelude"in h?Boolean(h.parseRulePrelude):!0,b.parseValue="parseValue"in h?Boolean(h.parseValue):!0,b.parseCustomProperty="parseCustomProperty"in h?Boolean(h.parseCustomProperty):!1;let{context:c="default",onComment:m}=h;if(c in b.context===!1)throw new Error("Unknown context `"+c+"`");if(typeof m==="function")b.forEachToken((s,Z,L)=>{if(s===A){let D=b.getLocation(Z,L),H=Zl(i,L-2,L,"*/")?i.slice(Z+2,L-2):i.slice(Z+2,L);m(H,D)}});let u=b.context[c].call(b,h);if(!b.eof)b.error();return u},{SyntaxError:dr,config:b.config})}var vt=Rb(),fl=gr(),er=Sb().ArraySet,aw=Pb().MappingList;function jl(l){if(!l)l={};this._file=fl.getArg(l,"file",null),this._sourceRoot=fl.getArg(l,"sourceRoot",null),this._skipValidation=fl.getArg(l,"skipValidation",!1),this._ignoreInvalidMapping=fl.getArg(l,"ignoreInvalidMapping",!1),this._sources=new er,this._names=new er,this._mappings=new aw,this._sourcesContents=null}jl.prototype._version=3;jl.fromSourceMap=function l(i,t){var r=i.sourceRoot,n=new jl(Object.assign(t||{},{file:i.file,sourceRoot:r}));return i.eachMapping(function(o){var f={generated:{line:o.generatedLine,column:o.generatedColumn}};if(o.source!=null){if(f.source=o.source,r!=null)f.source=fl.relative(r,f.source);if(f.original={line:o.originalLine,column:o.originalColumn},o.name!=null)f.name=o.name}n.addMapping(f)}),i.sources.forEach(function(o){var f=o;if(r!==null)f=fl.relative(r,o);if(!n._sources.has(f))n._sources.add(f);var b=i.sourceContentFor(o);if(b!=null)n.setSourceContent(o,b)}),n};jl.prototype.addMapping=function l(i){var t=fl.getArg(i,"generated"),r=fl.getArg(i,"original",null),n=fl.getArg(i,"source",null),o=fl.getArg(i,"name",null);if(!this._skipValidation){if(this._validateMapping(t,r,n,o)===!1)return}if(n!=null){if(n=String(n),!this._sources.has(n))this._sources.add(n)}if(o!=null){if(o=String(o),!this._names.has(o))this._names.add(o)}this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:n,name:o})};jl.prototype.setSourceContent=function l(i,t){var r=i;if(this._sourceRoot!=null)r=fl.relative(this._sourceRoot,r);if(t!=null){if(!this._sourcesContents)this._sourcesContents=Object.create(null);this._sourcesContents[fl.toSetString(r)]=t}else if(this._sourcesContents){if(delete this._sourcesContents[fl.toSetString(r)],Object.keys(this._sourcesContents).length===0)this._sourcesContents=null}};jl.prototype.applySourceMap=function l(i,t,r){var n=t;if(t==null){if(i.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);n=i.file}var o=this._sourceRoot;if(o!=null)n=fl.relative(o,n);var f=new er,b=new er;this._mappings.unsortedForEach(function(e){if(e.source===n&&e.originalLine!=null){var g=i.originalPositionFor({line:e.originalLine,column:e.originalColumn});if(g.source!=null){if(e.source=g.source,r!=null)e.source=fl.join(r,e.source);if(o!=null)e.source=fl.relative(o,e.source);if(e.originalLine=g.line,e.originalColumn=g.column,g.name!=null)e.name=g.name}}var h=e.source;if(h!=null&&!f.has(h))f.add(h);var c=e.name;if(c!=null&&!b.has(c))b.add(c)},this),this._sources=f,this._names=b,i.sources.forEach(function(e){var g=i.sourceContentFor(e);if(g!=null){if(r!=null)e=fl.join(r,e);if(o!=null)e=fl.relative(o,e);this.setSourceContent(e,g)}},this)};jl.prototype._validateMapping=function l(i,t,r,n){if(t&&typeof t.line!=="number"&&typeof t.column!=="number"){var o="original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.";if(this._ignoreInvalidMapping){if(typeof console!=="undefined"&&console.warn)console.warn(o);return!1}else throw new Error(o)}if(i&&"line"in i&&"column"in i&&i.line>0&&i.column>=0&&!t&&!r&&!n)return;else if(i&&"line"in i&&"column"in i&&t&&"line"in t&&"column"in t&&i.line>0&&i.column>=0&&t.line>0&&t.column>=0&&r)return;else{var o="Invalid mapping: "+JSON.stringify({generated:i,source:r,original:t,name:n});if(this._ignoreInvalidMapping){if(typeof console!=="undefined"&&console.warn)console.warn(o);return!1}else throw new Error(o)}};jl.prototype._serializeMappings=function l(){var i=0,t=1,r=0,n=0,o=0,f=0,b="",e,g,h,c,m=this._mappings.toArray();for(var u=0,s=m.length;u0){if(!fl.compareByGeneratedPositionsInflated(g,m[u-1]))continue;e+=","}if(e+=vt.encode(g.generatedColumn-i),i=g.generatedColumn,g.source!=null){if(c=this._sources.indexOf(g.source),e+=vt.encode(c-f),f=c,e+=vt.encode(g.originalLine-1-n),n=g.originalLine-1,e+=vt.encode(g.originalColumn-r),r=g.originalColumn,g.name!=null)h=this._names.indexOf(g.name),e+=vt.encode(h-o),o=h}b+=e}return b};jl.prototype._generateSourcesContent=function l(i,t){return i.map(function(r){if(!this._sourcesContents)return null;if(t!=null)r=fl.relative(t,r);var n=fl.toSetString(r);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)};jl.prototype.toJSON=function l(){var i={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null)i.file=this._file;if(this._sourceRoot!=null)i.sourceRoot=this._sourceRoot;if(this._sourcesContents)i.sourcesContent=this._generateSourcesContent(i.sources,i.sourceRoot);return i};jl.prototype.toString=function l(){return JSON.stringify(this.toJSON())};var gn=jl;var Cb=new Set(["Atrule","Selector","Declaration"]);function Ib(l){let i=new gn,t={line:1,column:0},r={line:0,column:0},n={line:1,column:0},o={generated:n},f=1,b=0,e=!1,g=l.node;l.node=function(m){if(m.loc&&m.loc.start&&Cb.has(m.type)){let u=m.loc.start.line,s=m.loc.start.column-1;if(r.line!==u||r.column!==s){if(r.line=u,r.column=s,t.line=f,t.column=b,e){if(e=!1,t.line!==n.line||t.column!==n.column)i.addMapping(o)}e=!0,i.addMapping({source:m.loc.source,original:r,generated:t})}}if(g.call(this,m),e&&Cb.has(m.type))n.line=f,n.column=b};let h=l.emit;l.emit=function(m,u,s){for(let Z=0;Zqw,safe:()=>en});var vw=43,$w=45,bn=(l,i)=>{if(l===J)l=i;if(typeof l==="string"){let t=l.charCodeAt(0);return t>127?32768:t<<8}return l},Zb=[[w,w],[w,v],[w,tl],[w,wl],[w,"-"],[w,$],[w,U],[w,j],[w,cl],[w,O],[S,w],[S,v],[S,tl],[S,wl],[S,"-"],[S,$],[S,U],[S,j],[S,cl],[E,w],[E,v],[E,tl],[E,wl],[E,"-"],[E,$],[E,U],[E,j],[E,cl],[j,w],[j,v],[j,tl],[j,wl],[j,"-"],[j,$],[j,U],[j,j],[j,cl],["#",w],["#",v],["#",tl],["#",wl],["#","-"],["#",$],["#",U],["#",j],["#",cl],["-",w],["-",v],["-",tl],["-",wl],["-","-"],["-",$],["-",U],["-",j],["-",cl],[$,w],[$,v],[$,tl],[$,wl],[$,$],[$,U],[$,j],[$,"%"],[$,cl],["@",w],["@",v],["@",tl],["@",wl],["@","-"],["@",cl],[".",$],[".",U],[".",j],["+",$],["+",U],["+",j],["/","*"]],_w=Zb.concat([[w,E],[j,E],[E,E],[S,O],[S,bl],[S,C],[U,U],[U,j],[U,v],[U,"-"],[a,w],[a,v],[a,U],[a,j],[a,E],[a,"-"]]);function Tb(l){let i=new Set(l.map(([t,r])=>bn(t)<<16|bn(r)));return function(t,r,n){let o=bn(r,n),f=n.charCodeAt(0);if(f===$w&&r!==w&&r!==v&&r!==cl||f===vw?i.has(t<<16|f<<8):i.has(t<<16|o))this.emit(" ",Y,!0);return o}}var qw=Tb(Zb),en=Tb(_w);var Jw=92;function Dw(l,i){if(typeof i==="function"){let t=null;l.children.forEach((r)=>{if(t!==null)i.call(this,t);this.node(r),t=r});return}l.children.forEach(this.node,this)}function Xw(l){fi(l,(i,t,r)=>{this.token(i,l.slice(t,r))})}function db(l){let i=new Map;for(let[t,r]of Object.entries(l.node))if(typeof(r.generate||r)==="function")i.set(t,r.generate||r);return function(t,r){let n="",o=0,f={node(e){if(i.has(e.type))i.get(e.type).call(b,e);else throw new Error("Unknown node type: "+e.type)},tokenBefore:en,token(e,g){if(o=this.tokenBefore(o,e,g),this.emit(g,e,!1),e===J&&g.charCodeAt(0)===Jw)this.emit(` +`,Y,!0)},emit(e){n+=e},result(){return n}};if(r){if(typeof r.decorator==="function")f=r.decorator(f);if(r.sourceMap)f=Ib(f);if(r.mode in hr)f.tokenBefore=hr[r.mode]}let b={node:(e)=>f.node(e),children:Dw,token:(e,g)=>f.token(e,g),tokenize:Xw};return f.node(t),f.result()}}function l0(l){return{fromPlainObject(i){return l(i,{enter(t){if(t.children&&t.children instanceof il===!1)t.children=new il().fromArray(t.children)}}),i},toPlainObject(i){return l(i,{leave(t){if(t.children&&t.children instanceof il)t.children=t.children.toArray()}}),i}}}var{hasOwnProperty:hn}=Object.prototype,$t=function(){};function i0(l){return typeof l==="function"?l:$t}function t0(l,i){return function(t,r,n){if(t.type===i)l.call(this,t,r,n)}}function sw(l,i){let t=i.structure,r=[];for(let n in t){if(hn.call(t,n)===!1)continue;let o=t[n],f={name:n,type:!1,nullable:!1};if(!Array.isArray(o))o=[o];for(let b of o)if(b===null)f.nullable=!0;else if(typeof b==="string")f.type="node";else if(Array.isArray(b))f.type="list";if(f.type)r.push(f)}if(r.length)return{context:i.walkContext,fields:r};return null}function Ww(l){let i={};for(let t in l.node)if(hn.call(l.node,t)){let r=l.node[t];if(!r.structure)throw new Error("Missed `structure` field in `"+t+"` node type definition");i[t]=sw(t,r)}return i}function r0(l,i){let t=l.fields.slice(),r=l.context,n=typeof r==="string";if(i)t.reverse();return function(o,f,b,e){let g;if(n)g=f[r],f[r]=o;for(let h of t){let c=o[h.name];if(!h.nullable||c){if(h.type==="list"){if(i?c.reduceRight(e,!1):c.reduce(e,!1))return!0}else if(b(c))return!0}}if(n)f[r]=g}}function n0({StyleSheet:l,Atrule:i,Rule:t,Block:r,DeclarationList:n}){return{Atrule:{StyleSheet:l,Atrule:i,Rule:t,Block:r},Rule:{StyleSheet:l,Atrule:i,Rule:t,Block:r},Declaration:{StyleSheet:l,Atrule:i,Rule:t,Block:r,DeclarationList:n}}}function o0(l){let i=Ww(l),t={},r={},n=Symbol("break-walk"),o=Symbol("skip-node");for(let g in i)if(hn.call(i,g)&&i[g]!==null)t[g]=r0(i[g],!1),r[g]=r0(i[g],!0);let f=n0(t),b=n0(r),e=function(g,h){function c(D,H,gl){let K=m.call(L,D,H,gl);if(K===n)return!0;if(K===o)return!1;if(s.hasOwnProperty(D.type)){if(s[D.type](D,L,c,Z))return!0}if(u.call(L,D,H,gl)===n)return!0;return!1}let m=$t,u=$t,s=t,Z=(D,H,gl,K)=>D||c(H,gl,K),L={break:n,skip:o,root:g,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null};if(typeof h==="function")m=h;else if(h){if(m=i0(h.enter),u=i0(h.leave),h.reverse)s=r;if(h.visit){if(f.hasOwnProperty(h.visit))s=h.reverse?b[h.visit]:f[h.visit];else if(!i.hasOwnProperty(h.visit))throw new Error("Bad value `"+h.visit+"` for `visit` option (should be: "+Object.keys(i).sort().join(", ")+")");m=t0(m,h.visit),u=t0(u,h.visit)}}if(m===$t&&u===$t)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");c(g)};return e.break=n,e.skip=o,e.find=function(g,h){let c=null;return e(g,function(m,u,s){if(h.call(this,m,u,s))return c=m,n}),c},e.findLast=function(g,h){let c=null;return e(g,{reverse:!0,enter(m,u,s){if(h.call(this,m,u,s))return c=m,n}}),c},e.findAll=function(g,h){let c=[];return e(g,function(m,u,s){if(h.call(this,m,u,s))c.push(m)}),c},e}function jw(l){return l}function Ow(l){let{min:i,max:t,comma:r}=l;if(i===0&&t===0)return r?"#?":"*";if(i===0&&t===1)return"?";if(i===1&&t===0)return r?"#":"+";if(i===1&&t===1)return"";return(r?"#":"")+(i===t?"{"+i+"}":"{"+i+","+(t!==0?t:"")+"}")}function Yw(l){switch(l.type){case"Range":return" ["+(l.min===null?"-∞":l.min)+","+(l.max===null?"∞":l.max)+"]";default:throw new Error("Unknown node type `"+l.type+"`")}}function Qw(l,i,t,r){let n=l.combinator===" "||r?l.combinator:" "+l.combinator+" ",o=l.terms.map((f)=>cr(f,i,t,r)).join(n);if(l.explicit||t)return(r||o[0]===","?"[":"[ ")+o+(r?"]":" ]");return o}function cr(l,i,t,r){let n;switch(l.type){case"Group":n=Qw(l,i,t,r)+(l.disallowEmpty?"!":"");break;case"Multiplier":return cr(l.term,i,t,r)+i(Ow(l),l);case"Boolean":n="";break;case"Type":n="<"+l.name+(l.opts?i(Yw(l.opts),l.opts):"")+">";break;case"Property":n="<'"+l.name+"'>";break;case"Keyword":n=l.name;break;case"AtKeyword":n="@"+l.name;break;case"Function":n=l.name+"(";break;case"String":case"Token":n=l.value;break;case"Comma":n=",";break;default:throw new Error("Unknown node type `"+l.type+"`")}return i(n,l)}function Ki(l,i){let t=jw,r=!1,n=!1;if(typeof i==="function")t=i;else if(i){if(r=Boolean(i.forceBraces),n=Boolean(i.compact),typeof i.decorate==="function")t=i.decorate}return cr(l,t,r,n)}var f0={offset:0,line:1,column:1};function Gw(l,i){let{tokens:t,longestMatch:r}=l,n=r1)h=mr(o||i,"end")||_t(f0,g),c=_t(h);else h=mr(o,"start")||_t(mr(i,"start")||f0,g.slice(0,f)),c=mr(o,"end")||_t(h,g.substr(f,b));return{css:g,mismatchOffset:f,mismatchLength:b,start:h,end:c}}function mr(l,i){let t=l&&l.loc&&l.loc[i];if(t)return"line"in t?_t(t):t;return null}function _t({offset:l,line:i,column:t},r){let n={offset:l,line:i,column:t};if(r){let o=r.split(/\n|\r\n?|\f/);n.offset+=r.length,n.line+=o.length-1,n.column=o.length===1?n.column+r.length:o.pop().length+1}return n}var Ri=function(l,i){let t=vi("SyntaxReferenceError",l+(i?" `"+i+"`":""));return t.reference=i,t},g0=function(l,i,t,r){let n=vi("SyntaxMatchError",l),{css:o,mismatchOffset:f,mismatchLength:b,start:e,end:g}=Gw(r,t);return n.rawMessage=l,n.syntax=i?Ki(i):"",n.css=o,n.mismatchOffset=f,n.mismatchLength=b,n.message=l+` syntax: `+n.syntax+` value: `+(o||"")+` - --------`+new Array(n.mismatchOffset+1).join("-")+"^",Object.assign(n,e),n.loc={source:t&&t.loc&&t.loc.source||"",start:e,end:g},n};var wr=new Map,yi=new Map;var pr=Bw,cn=Fw;function ur(l,i){return i=i||0,l.length-i>=2&&l.charCodeAt(i)===45&&l.charCodeAt(i+1)===45}function b0(l,i){if(i=i||0,l.length-i>=3){if(l.charCodeAt(i)===45&&l.charCodeAt(i+1)!==45){let t=l.indexOf("-",i+2);if(t!==-1)return l.substring(i,t+1)}}return""}function Bw(l){if(wr.has(l))return wr.get(l);let i=l.toLowerCase(),t=wr.get(i);if(t===void 0){let r=ur(i,0),n=!r?b0(i,0):"";t=Object.freeze({basename:i.substr(n.length),name:i,prefix:n,vendor:n,custom:r})}return wr.set(l,t),t}function Fw(l){if(yi.has(l))return yi.get(l);let i=l,t=l[0];if(t==="/")t=l[1]==="/"?"//":"/";else if(t!=="_"&&t!=="*"&&t!=="$"&&t!=="#"&&t!=="+"&&t!=="&")t="";let r=ur(i,t.length);if(!r){if(i=i.toLowerCase(),yi.has(i)){let b=yi.get(i);return yi.set(l,b),b}}let n=!r?b0(i,t.length):"",o=i.substr(0,t.length+n.length),f=Object.freeze({basename:i.substr(o.length),name:i.substr(t.length),hack:t,vendor:n,prefix:o,custom:r});return yi.set(l,f),f}var Mi=["initial","inherit","unset","revert","revert-layer"];var Jt=43,Al=45,mn=110,Ui=!0,Ew=!1;function pn(l,i){return l!==null&&l.type===J&&l.value.charCodeAt(0)===i}function qt(l,i,t){while(l!==null&&(l.type===Y||l.type===A))l=t(++i);return i}function gi(l,i,t,r){if(!l)return 0;let n=l.value.charCodeAt(i);if(n===Jt||n===Al){if(t)return 0;i++}for(;i6)return 0}return r}function zr(l,i,t){if(!l)return 0;while(zn(t(i),h0)){if(++l>6)return 0;i++}return i}function xn(l,i){let t=0;if(l===null||l.type!==w||!Il(l.value,0,Hw))return 0;if(l=i(++t),l===null)return 0;if(zn(l,Lw)){if(l=i(++t),l===null)return 0;if(l.type===w)return zr(Dt(l,0,!0),++t,i);if(zn(l,h0))return zr(1,++t,i);return 0}if(l.type===$){let r=Dt(l,1,!0);if(r===0)return 0;if(l=i(++t),l===null)return t;if(l.type===O||l.type===$){if(!Kw(l,e0)||!Dt(l,1,!1))return 0;return t+1}return zr(r,t,i)}if(l.type===O)return zr(Dt(l,1,!0),++t,i);return 0}var Rw=["calc(","-moz-calc(","-webkit-calc("],an=new Map([[v,a],[j,a],[el,pl],[N,ml]]);function Ql(l,i){return il.max&&typeof l.max!=="string")return!0}return!1}function yw(l,i){let t=0,r=[],n=0;l:do{switch(l.type){case ml:case a:case pl:if(l.type!==t)break l;if(t=r.pop(),r.length===0){n++;break l}break;case v:case j:case el:case N:r.push(t),t=an.get(l.type);break}n++}while(l=i(n));return n}function jl(l){return function(i,t,r){if(i===null)return 0;if(i.type===v&&m0(i.value,Rw))return yw(i,t);return l(i,t,r)}}function P(l){return function(i){if(i===null||i.type!==l)return 0;return 1}}function Mw(l){if(l===null||l.type!==w)return 0;let i=l.value.toLowerCase();if(m0(i,Mi))return 0;if(c0(i,"default"))return 0;return 1}function p0(l){if(l===null||l.type!==w)return 0;if(Ql(l.value,0)!==45||Ql(l.value,1)!==45)return 0;return 1}function Uw(l){if(!p0(l))return 0;if(l.value==="--")return 0;return 1}function Aw(l){if(l===null||l.type!==E)return 0;let i=l.value.length;if(i!==4&&i!==5&&i!==7&&i!==9)return 0;for(let t=1;ttp,semitones:()=>gp,resolution:()=>np,length:()=>lp,frequency:()=>rp,flex:()=>op,decibel:()=>fp,angle:()=>ip});var lp=["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],ip=["deg","grad","rad","turn"],tp=["s","ms"],rp=["hz","khz"],np=["dpi","dpcm","dppx","x"],op=["fr"],fp=["db"],gp=["st"];function vn(l,i,t){return Object.assign(vi("SyntaxError",l),{input:i,offset:t,rawMessage:l,message:l+` + --------`+new Array(n.mismatchOffset+1).join("-")+"^",Object.assign(n,e),n.loc={source:t&&t.loc&&t.loc.source||"",start:e,end:g},n};var wr=new Map,yi=new Map;var pr=Bw,cn=Fw;function ur(l,i){return i=i||0,l.length-i>=2&&l.charCodeAt(i)===45&&l.charCodeAt(i+1)===45}function b0(l,i){if(i=i||0,l.length-i>=3){if(l.charCodeAt(i)===45&&l.charCodeAt(i+1)!==45){let t=l.indexOf("-",i+2);if(t!==-1)return l.substring(i,t+1)}}return""}function Bw(l){if(wr.has(l))return wr.get(l);let i=l.toLowerCase(),t=wr.get(i);if(t===void 0){let r=ur(i,0),n=!r?b0(i,0):"";t=Object.freeze({basename:i.substr(n.length),name:i,prefix:n,vendor:n,custom:r})}return wr.set(l,t),t}function Fw(l){if(yi.has(l))return yi.get(l);let i=l,t=l[0];if(t==="/")t=l[1]==="/"?"//":"/";else if(t!=="_"&&t!=="*"&&t!=="$"&&t!=="#"&&t!=="+"&&t!=="&")t="";let r=ur(i,t.length);if(!r){if(i=i.toLowerCase(),yi.has(i)){let b=yi.get(i);return yi.set(l,b),b}}let n=!r?b0(i,t.length):"",o=i.substr(0,t.length+n.length),f=Object.freeze({basename:i.substr(o.length),name:i.substr(t.length),hack:t,vendor:n,prefix:o,custom:r});return yi.set(l,f),f}var Mi=["initial","inherit","unset","revert","revert-layer"];var Jt=43,Al=45,mn=110,Ui=!0,Ew=!1;function pn(l,i){return l!==null&&l.type===J&&l.value.charCodeAt(0)===i}function qt(l,i,t){while(l!==null&&(l.type===Y||l.type===A))l=t(++i);return i}function gi(l,i,t,r){if(!l)return 0;let n=l.value.charCodeAt(i);if(n===Jt||n===Al){if(t)return 0;i++}for(;i6)return 0}return r}function zr(l,i,t){if(!l)return 0;while(zn(t(i),h0)){if(++l>6)return 0;i++}return i}function xn(l,i){let t=0;if(l===null||l.type!==w||!Il(l.value,0,Hw))return 0;if(l=i(++t),l===null)return 0;if(zn(l,Lw)){if(l=i(++t),l===null)return 0;if(l.type===w)return zr(Dt(l,0,!0),++t,i);if(zn(l,h0))return zr(1,++t,i);return 0}if(l.type===$){let r=Dt(l,1,!0);if(r===0)return 0;if(l=i(++t),l===null)return t;if(l.type===j||l.type===$){if(!Kw(l,e0)||!Dt(l,1,!1))return 0;return t+1}return zr(r,t,i)}if(l.type===j)return zr(Dt(l,1,!0),++t,i);return 0}var Rw=["calc(","-moz-calc(","-webkit-calc("],an=new Map([[v,a],[O,a],[el,pl],[N,ml]]);function Ql(l,i){return il.max&&typeof l.max!=="string")return!0}return!1}function yw(l,i){let t=0,r=[],n=0;l:do{switch(l.type){case ml:case a:case pl:if(l.type!==t)break l;if(t=r.pop(),r.length===0){n++;break l}break;case v:case O:case el:case N:r.push(t),t=an.get(l.type);break}n++}while(l=i(n));return n}function Ol(l){return function(i,t,r){if(i===null)return 0;if(i.type===v&&m0(i.value,Rw))return yw(i,t);return l(i,t,r)}}function P(l){return function(i){if(i===null||i.type!==l)return 0;return 1}}function Mw(l){if(l===null||l.type!==w)return 0;let i=l.value.toLowerCase();if(m0(i,Mi))return 0;if(c0(i,"default"))return 0;return 1}function p0(l){if(l===null||l.type!==w)return 0;if(Ql(l.value,0)!==45||Ql(l.value,1)!==45)return 0;return 1}function Uw(l){if(!p0(l))return 0;if(l.value==="--")return 0;return 1}function Aw(l){if(l===null||l.type!==E)return 0;let i=l.value.length;if(i!==4&&i!==5&&i!==7&&i!==9)return 0;for(let t=1;ttp,semitones:()=>gp,resolution:()=>np,length:()=>lp,frequency:()=>rp,flex:()=>op,decibel:()=>fp,angle:()=>ip});var lp=["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],ip=["deg","grad","rad","turn"],tp=["s","ms"],rp=["hz","khz"],np=["dpi","dpcm","dppx","x"],op=["fr"],fp=["db"],gp=["st"];function vn(l,i,t){return Object.assign(vi("SyntaxError",l),{input:i,offset:t,rawMessage:l,message:l+` `+i+` ---`+new Array((t||i.length)+1).join("-")+"^"})}var bp=9,ep=10,hp=12,cp=13,mp=32,x0=new Uint8Array(128).map((l,i)=>/[a-zA-Z0-9\-]/.test(String.fromCharCode(i))?1:0);class $n{constructor(l){this.str=l,this.pos=0}charCodeAt(l){return l=128||x0[i]===0)break}if(this.pos===l)this.error("Expect a keyword");return this.substringToPos(l)}scanNumber(){let l=this.pos;for(;l57)break}if(this.pos===l)this.error("Expect a number");return this.substringToPos(l)}scanString(){let l=this.str.indexOf("'",this.pos+1);if(l===-1)this.pos=this.str.length,this.error("Expect an apostrophe");return this.substringToPos(l+1)}}var wp=9,pp=10,up=12,zp=13,xp=32,X0=33,Dn=35,a0=38,vr=39,W0=40,ap=41,s0=42,Xn=43,Wn=44,v0=45,sn=60,qn=62,Jn=63,vp=64,Xt=91,Wt=93,$r=123,$0=124,_0=125,q0=8734,J0={" ":1,"&&":2,"||":3,"|":4};function D0(l){let i=null,t=null;if(l.eat($r),l.skipWs(),i=l.scanNumber(l),l.skipWs(),l.charCode()===Wn){if(l.pos++,l.skipWs(),l.charCode()!==_0)t=l.scanNumber(l),l.skipWs()}else t=i;return l.eat(_0),{min:Number(i),max:t?Number(t):0}}function $p(l){let i=null,t=!1;switch(l.charCode()){case s0:l.pos++,i={min:0,max:0};break;case Xn:l.pos++,i={min:1,max:0};break;case Jn:l.pos++,i={min:0,max:1};break;case Dn:if(l.pos++,t=!0,l.charCode()===$r)i=D0(l);else if(l.charCode()===Jn)l.pos++,i={min:0,max:0};else i={min:1,max:0};break;case $r:i=D0(l);break;default:return null}return{type:"Multiplier",comma:t,min:i.min,max:i.max,term:null}}function bi(l,i){let t=$p(l);if(t!==null){if(t.term=i,l.charCode()===Dn&&l.charCodeAt(l.pos-1)===Xn)return bi(l,t);return t}return i}function _n(l){let i=l.peek();if(i==="")return null;return bi(l,{type:"Token",value:i})}function _p(l){let i;return l.eat(sn),l.eat(vr),i=l.scanWord(),l.eat(vr),l.eat(qn),bi(l,{type:"Property",name:i})}function qp(l){let i=null,t=null,r=1;if(l.eat(Xt),l.charCode()===v0)l.peek(),r=-1;if(r==-1&&l.charCode()===q0)l.peek();else if(i=r*Number(l.scanNumber(l)),l.isNameCharCode())i+=l.scanWord();if(l.skipWs(),l.eat(Wn),l.skipWs(),l.charCode()===q0)l.peek();else{if(r=1,l.charCode()===v0)l.peek(),r=-1;if(t=r*Number(l.scanNumber(l)),l.isNameCharCode())t+=l.scanWord()}return l.eat(Wt),{type:"Range",min:i,max:t}}function Jp(l){let i,t=null;if(l.eat(sn),i=l.scanWord(),i==="boolean-expr"){l.eat(Xt);let r=On(l,Wt);return l.eat(Wt),l.eat(qn),bi(l,{type:"Boolean",term:r.terms.length===1?r.terms[0]:r})}if(l.charCode()===W0&&l.nextCharCode()===ap)l.pos+=2,i+="()";if(l.charCodeAt(l.findWsEnd(l.pos))===Xt)l.skipWs(),t=qp(l);return l.eat(qn),bi(l,{type:"Type",name:i,opts:t})}function Dp(l){let i=l.scanWord();if(l.charCode()===W0)return l.pos++,{type:"Function",name:i};return bi(l,{type:"Keyword",name:i})}function Xp(l,i){function t(n,o){return{type:"Group",terms:n,combinator:o,disallowEmpty:!1,explicit:!1}}let r;i=Object.keys(i).sort((n,o)=>J0[n]-J0[o]);while(i.length>0){r=i.shift();let n=0,o=0;for(;n1)l.splice(o,n-o,t(l.slice(o,n),r)),n=o+1;o=-1}}if(o!==-1&&i.length)l.splice(o,n-o,t(l.slice(o,n),r))}return r}function On(l,i){let t=Object.create(null),r=[],n,o=null,f=l.pos;while(l.charCode()!==i&&(n=sp(l,i)))if(n.type!=="Spaces"){if(n.type==="Combinator"){if(o===null||o.type==="Combinator")l.pos=f,l.error("Unexpected combinator");t[n.value]=!0}else if(o!==null&&o.type!=="Combinator")t[" "]=!0,r.push({type:"Combinator",value:" "});r.push(n),o=n,f=l.pos}if(o!==null&&o.type==="Combinator")l.pos-=f,l.error("Unexpected combinator");return{type:"Group",terms:r,combinator:Xp(r,t)||" ",disallowEmpty:!1,explicit:!1}}function Wp(l,i){let t;if(l.eat(Xt),t=On(l,i),l.eat(Wt),t.explicit=!0,l.charCode()===X0)l.pos++,t.disallowEmpty=!0;return t}function sp(l,i){let t=l.charCode();switch(t){case Wt:break;case Xt:return bi(l,Wp(l,i));case sn:return l.nextCharCode()===vr?_p(l):Jp(l);case $0:return{type:"Combinator",value:l.substringToPos(l.pos+(l.nextCharCode()===$0?2:1))};case a0:return l.pos++,l.eat(a0),{type:"Combinator",value:"&&"};case Wn:return l.pos++,{type:"Comma"};case vr:return bi(l,{type:"String",value:l.scanString()});case xp:case wp:case pp:case zp:case up:return{type:"Spaces",value:l.scanSpaces()};case vp:if(t=l.nextCharCode(),l.isNameCharCode(t))return l.pos++,{type:"AtKeyword",name:l.scanWord()};return _n(l);case s0:case Xn:case Jn:case Dn:case X0:break;case $r:if(t=l.nextCharCode(),t<48||t>57)return _n(l);break;default:if(l.isNameCharCode(t))return Dp(l);return _n(l)}}function st(l){let i=new $n(l),t=On(i);if(i.pos!==l.length)i.error("Unexpected input");if(t.terms.length===1&&t.terms[0].type==="Group")return t.terms[0];return t}var Ot=function(){};function O0(l){return typeof l==="function"?l:Ot}function jn(l,i,t){function r(f){switch(n.call(t,f),f.type){case"Group":f.terms.forEach(r);break;case"Multiplier":case"Boolean":r(f.term);break;case"Type":case"Property":case"Keyword":case"AtKeyword":case"Function":case"String":case"Token":case"Comma":break;default:throw new Error("Unknown type: "+f.type)}o.call(t,f)}let n=Ot,o=Ot;if(typeof i==="function")n=i;else if(i)n=O0(i.enter),o=O0(i.leave);if(n===Ot&&o===Ot)throw new Error("Neither `enter` nor `leave` walker handler is set or both aren't a function");r(l,t)}var jp={decorator(l){let i=[],t=null;return{...l,node(r){let n=t;t=r,l.node.call(this,r),t=n},emit(r,n,o){i.push({type:n,value:r,node:o?null:t})},result(){return i}}}};function Yp(l){let i=[];return fi(l,(t,r,n)=>i.push({type:t,value:l.slice(r,n),node:null})),i}function Yn(l,i){if(typeof l==="string")return Yp(l);return i.generate(l,jp)}var y={type:"Match"},k={type:"Mismatch"},_r={type:"DisallowEmpty"},Qp=40,Gp=41;function xl(l,i,t){if(i===y&&t===k)return l;if(l===y&&i===y&&t===y)return l;if(l.type==="If"&&l.else===k&&i===y)i=l.then,l=l.match;return{type:"If",match:l,then:i,else:t}}function Y0(l){return l.length>2&&l.charCodeAt(l.length-2)===Qp&&l.charCodeAt(l.length-1)===Gp}function j0(l){return l.type==="Keyword"||l.type==="AtKeyword"||l.type==="Function"||l.type==="Type"&&Y0(l.name)}function ei(l,i=" ",t=!1){return{type:"Group",terms:l,combinator:i,disallowEmpty:!1,explicit:t}}function jt(l,i,t=new Set){if(!t.has(l))switch(t.add(l),l.type){case"If":l.match=jt(l.match,i,t),l.then=jt(l.then,i,t),l.else=jt(l.else,i,t);break;case"Type":return i[l.name]||l}return l}function Qn(l,i,t){switch(l){case" ":{let r=y;for(let n=i.length-1;n>=0;n--){let o=i[n];r=xl(o,r,k)}return r}case"|":{let r=k,n=null;for(let o=i.length-1;o>=0;o--){let f=i[o];if(j0(f)){if(n===null&&o>0&&j0(i[o-1]))n=Object.create(null),r=xl({type:"Enum",map:n},y,r);if(n!==null){let b=(Y0(f.name)?f.name.slice(0,-1):f.name).toLowerCase();if(b in n===!1){n[b]=f;continue}}}n=null,r=xl(f,y,r)}return r}case"&&":{if(i.length>5)return{type:"MatchOnce",terms:i,all:!0};let r=k;for(let n=i.length-1;n>=0;n--){let o=i[n],f;if(i.length>1)f=Qn(l,i.filter(function(b){return b!==o}),!1);else f=y;r=xl(o,f,r)}return r}case"||":{if(i.length>5)return{type:"MatchOnce",terms:i,all:!1};let r=t?y:k;for(let n=i.length-1;n>=0;n--){let o=i[n],f;if(i.length>1)f=Qn(l,i.filter(function(b){return b!==o}),!0);else f=y;r=xl(o,f,r)}return r}}}function Bp(l){let i=y,t=Ai(l.term);if(l.max===0){if(t=xl(t,_r,k),i=xl(t,null,k),i.then=xl(y,y,i),l.comma)i.then.else=xl({type:"Comma",syntax:l},i,k)}else for(let r=l.min||1;r<=l.max;r++){if(l.comma&&i!==y)i=xl({type:"Comma",syntax:l},i,k);i=xl(t,xl(y,y,i),k)}if(l.min===0)i=xl(y,y,i);else for(let r=0;r=65&&n<=90)n=n|32;if(n!==r)return!1}return!0}function Rp(l){if(l.type!==J)return!1;return l.value!=="?"}function F0(l){if(l===null)return!0;return l.type===ll||l.type===v||l.type===j||l.type===el||l.type===N||Rp(l)}function V0(l){if(l===null)return!0;return l.type===a||l.type===pl||l.type===ml||l.type===J&&l.value==="/"}function yp(l,i,t){function r(){do H++,D=Hgl)gl=H}function g(){c={syntax:i.syntax,opts:i.syntax.opts||c!==null&&c.opts||null,prev:c},K={type:Bn,syntax:i.syntax,token:K.token,prev:K}}function h(){if(K.type===Bn)K=K.prev;else K={type:E0,syntax:c.syntax,token:K.token,prev:K};c=c.prev}let c=null,m=null,u=null,W=null,Z=0,L=null,D=null,H=-1,gl=0,K={type:Fp,syntax:null,token:null,prev:null};r();while(L===null&&++Zu.tokenIndex)u=W,W=!1}else if(u===null){L=Ep;break}i=u.nextState,m=u.thenStack,c=u.syntaxStack,K=u.matchStack,H=u.tokenIndex,D=HH){while(H":"<'"+i.name+"'>"));if(W!==!1&&D!==null&&i.type==="Type"){if(i.name==="custom-ident"&&D.type===w||i.name==="length"&&D.value==="0"){if(W===null)W=o(i,u);i=k;break}}g(),i=T.matchRef||T.match;break}case"Keyword":{let M=i.name;if(D!==null){let T=D.value;if(T.indexOf("\\")!==-1)T=T.replace(/\\[09].*$/,"");if(Gn(T,M)){e(),i=y;break}}i=k;break}case"AtKeyword":case"Function":if(D!==null&&Gn(D.value,i.name)){e(),i=y;break}i=k;break;case"Token":if(D!==null&&D.value===i.value){e(),i=y;break}i=k;break;case"Comma":if(D!==null&&D.type===ll)if(F0(K.token))i=k;else e(),i=V0(D)?k:y;else i=F0(K.token)||V0(D)?y:k;break;case"String":let B="",F=H;for(;FMp,isProperty:()=>Up,isKeyword:()=>Ap,getTrace:()=>L0});function L0(l){function i(n){if(n===null)return!1;return n.type==="Type"||n.type==="Property"||n.type==="Keyword"}function t(n){if(Array.isArray(n.match)){for(let o=0;ot.type==="Type"&&t.name===i)}function Up(l,i){return Vn(this,l,(t)=>t.type==="Property"&&t.name===i)}function Ap(l){return Vn(this,l,(i)=>i.type==="Keyword")}function Vn(l,i,t){let r=L0.call(l,i);if(r===null)return!1;return r.some(t)}function H0(l){if("node"in l)return l.node;return H0(l.match[0])}function K0(l){if("node"in l)return l.node;return K0(l.match[l.match.length-1])}function Ln(l,i,t,r,n){function o(b){if(b.syntax!==null&&b.syntax.type===r&&b.syntax.name===n){let e=H0(b),g=K0(b);l.syntax.walk(i,function(h,c,m){if(h===e){let u=new il;do{if(u.appendData(c.data),c.data===g)break;c=c.next}while(c!==null);f.push({parent:m,nodes:u})}})}if(Array.isArray(b.match))b.match.forEach(o)}let f=[];if(t.matched!==null)o(t.matched);return f}var{hasOwnProperty:Qt}=Object.prototype;function Hn(l){return typeof l==="number"&&isFinite(l)&&Math.floor(l)===l&&l>=0}function R0(l){return Boolean(l)&&Hn(l.offset)&&Hn(l.line)&&Hn(l.column)}function kp(l,i){return function t(r,n){if(!r||r.constructor!==Object)return n(r,"Type of node should be an Object");for(let o in r){let f=!0;if(Qt.call(r,o)===!1)continue;if(o==="type"){if(r.type!==l)n(r,"Wrong node type `"+r.type+"`, expected `"+l+"`")}else if(o==="loc"){if(r.loc===null)continue;else if(r.loc&&r.loc.constructor===Object)if(typeof r.loc.source!=="string")o+=".source";else if(!R0(r.loc.start))o+=".start";else if(!R0(r.loc.end))o+=".end";else continue;f=!1}else if(i.hasOwnProperty(o)){f=!1;for(let b=0;!f&&b");else throw new Error("Wrong value `"+n+"` in `"+i+"` structure definition")}return t.join(" | ")}function Sp(l,i){let t=i.structure,r={type:String,loc:!0},n={type:'"'+l+'"'};for(let o in t){if(Qt.call(t,o)===!1)continue;let f=r[o]=Array.isArray(t[o])?t[o].slice():[t[o]];n[o]=y0(f,l+"."+o)}return{docs:n,check:kp(l,r)}}function M0(l){let i={};if(l.node){for(let t in l.node)if(Qt.call(l.node,t)){let r=l.node[t];if(r.structure)i[t]=Sp(t,r);else throw new Error("Missed `structure` field in `"+t+"` node type definition")}}return i}function Kn(l,i,t){let r={};for(let n in l)if(l[n].syntax)r[n]=t?l[n].syntax:Ki(l[n].syntax,{compact:i});return r}function Np(l,i,t){let r={};for(let[n,o]of Object.entries(l))r[n]={prelude:o.prelude&&(t?o.prelude.syntax:Ki(o.prelude.syntax,{compact:i})),descriptors:o.descriptors&&Kn(o.descriptors,i,t)};return r}function Pp(l){for(let i=0;i{return t[r]=this.createDescriptor(i.descriptors[r],"AtruleDescriptor",r,l),t},Object.create(null)):null}}addProperty_(l,i){if(!i)return;this.properties[l]=this.createDescriptor(i,"Property",l)}addType_(l,i){if(!i)return;this.types[l]=this.createDescriptor(i,"Type",l)}checkAtruleName(l){if(!this.getAtrule(l))return new Ri("Unknown at-rule","@"+l)}checkAtrulePrelude(l,i){let t=this.checkAtruleName(l);if(t)return t;let r=this.getAtrule(l);if(!r.prelude&&i)return new SyntaxError("At-rule `@"+l+"` should not contain a prelude");if(r.prelude&&!i){if(!ki(this,r.prelude,"",!1).matched)return new SyntaxError("At-rule `@"+l+"` should contain a prelude")}}checkAtruleDescriptorName(l,i){let t=this.checkAtruleName(l);if(t)return t;let r=this.getAtrule(l),n=pr(i);if(!r.descriptors)return new SyntaxError("At-rule `@"+l+"` has no known descriptors");if(!r.descriptors[n.name]&&!r.descriptors[n.basename])return new Ri("Unknown at-rule descriptor",i)}checkPropertyName(l){if(!this.getProperty(l))return new Ri("Unknown property",l)}matchAtrulePrelude(l,i){let t=this.checkAtrulePrelude(l,i);if(t)return Gl(null,t);let r=this.getAtrule(l);if(!r.prelude)return Gl(null,null);return ki(this,r.prelude,i||"",!1)}matchAtruleDescriptor(l,i,t){let r=this.checkAtruleDescriptorName(l,i);if(r)return Gl(null,r);let n=this.getAtrule(l),o=pr(i);return ki(this,n.descriptors[o.name]||n.descriptors[o.basename],t,!1)}matchDeclaration(l){if(l.type!=="Declaration")return Gl(null,new Error("Not a Declaration node"));return this.matchProperty(l.property,l.value)}matchProperty(l,i){if(cn(l).custom)return Gl(null,new Error("Lexer matching doesn't applicable for custom properties"));let t=this.checkPropertyName(l);if(t)return Gl(null,t);return ki(this,this.getProperty(l),i,!0)}matchType(l,i){let t=this.getType(l);if(!t)return Gl(null,new Ri("Unknown type",l));return ki(this,t,i,!1)}match(l,i){if(typeof l!=="string"&&(!l||!l.type))return Gl(null,new Ri("Bad syntax"));if(typeof l==="string"||!l.match)l=this.createDescriptor(l,"Type","anonymous");return ki(this,l,i,!1)}findValueFragments(l,i,t,r){return Ln(this,i,this.matchProperty(l,i),t,r)}findDeclarationValueFragments(l,i,t){return Ln(this,l.value,this.matchDeclaration(l),i,t)}findAllFragments(l,i,t){let r=[];return this.syntax.walk(l,{visit:"Declaration",enter:(n)=>{r.push.apply(r,this.findDeclarationValueFragments(n,i,t))}}),r}getAtrule(l,i=!0){let t=pr(l);return(t.vendor&&i?this.atrules[t.name]||this.atrules[t.basename]:this.atrules[t.name])||null}getAtrulePrelude(l,i=!0){let t=this.getAtrule(l,i);return t&&t.prelude||null}getAtruleDescriptor(l,i){return this.atrules.hasOwnProperty(l)&&this.atrules.declarators?this.atrules[l].declarators[i]||null:null}getProperty(l,i=!0){let t=cn(l);return(t.vendor&&i?this.properties[t.name]||this.properties[t.basename]:this.properties[t.name])||null}getType(l){return hasOwnProperty.call(this.types,l)?this.types[l]:null}validate(){function l(b,e){return e?`<${b}>`:`<'${b}'>`}function i(b,e,g,h){if(g.has(e))return g.get(e);if(g.set(e,!1),h.syntax!==null)jn(h.syntax,function(c){if(c.type!=="Type"&&c.type!=="Property")return;let m=c.type==="Type"?b.types:b.properties,u=c.type==="Type"?r:n;if(!hasOwnProperty.call(m,c.name))t.push(`${l(e,g===r)} used missed syntax definition ${l(c.name,c.type==="Type")}`),g.set(e,!0);else if(i(b,c.name,u,m[c.name]))t.push(`${l(e,g===r)} used broken syntax definition ${l(c.name,c.type==="Type")}`),g.set(e,!0)},this)}let t=[],r=new Map,n=new Map;for(let b in this.types)i(this,b,r,this.types[b]);for(let b in this.properties)i(this,b,n,this.properties[b]);let o=[...r.keys()].filter((b)=>r.get(b)),f=[...n.keys()].filter((b)=>n.get(b));if(o.length||f.length)return{errors:t,types:o,properties:f};return null}dump(l,i){return{generic:this.generic,cssWideKeywords:this.cssWideKeywords,units:this.units,types:Kn(this.types,!i,l),properties:Kn(this.properties,!i,l),atrules:Np(this.atrules,!i,l)}}toString(){return JSON.stringify(this.dump())}}function Rn(l,i){if(typeof i==="string"&&/^\s*\|/.test(i))return typeof l==="string"?l+i:i.replace(/^\s*\|\s*/,"");return i||null}function U0(l,i){let t=Object.create(null);for(let[r,n]of Object.entries(l))if(n){t[r]={};for(let o of Object.keys(n))if(i.includes(o))t[r][o]=n[o]}return t}function Bt(l,i){let t={...l};for(let[r,n]of Object.entries(i))switch(r){case"generic":t[r]=Boolean(n);break;case"cssWideKeywords":t[r]=l[r]?[...l[r],...n]:n||[];break;case"units":t[r]={...l[r]};for(let[o,f]of Object.entries(n))t[r][o]=Array.isArray(f)?f:[];break;case"atrules":t[r]={...l[r]};for(let[o,f]of Object.entries(n)){let b=t[r][o]||{},e=t[r][o]={prelude:b.prelude||null,descriptors:{...b.descriptors}};if(!f)continue;e.prelude=f.prelude?Rn(e.prelude,f.prelude):e.prelude||null;for(let[g,h]of Object.entries(f.descriptors||{}))e.descriptors[g]=h?Rn(e.descriptors[g],h):null;if(!Object.keys(e.descriptors).length)e.descriptors=null}break;case"types":case"properties":t[r]={...l[r]};for(let[o,f]of Object.entries(n))t[r][o]=Rn(t[r][o],f);break;case"scope":case"features":t[r]={...l[r]};for(let[o,f]of Object.entries(n))t[r][o]={...t[r][o],...f};break;case"parseContext":t[r]={...l[r],...n};break;case"atrule":case"pseudo":t[r]={...l[r],...U0(n,["parse"])};break;case"node":t[r]={...l[r],...U0(n,["name","structure","parse","generate","walkContext"])};break}return t}function A0(l){let i=Bb(l),t=o0(l),r=db(l),{fromPlainObject:n,toPlainObject:o}=l0(t),f={lexer:null,createLexer:(b)=>new Gt(b,f,f.lexer.structure),tokenize:fi,parse:i,generate:r,walk:t,find:t.find,findLast:t.findLast,findAll:t.findAll,fromPlainObject:n,toPlainObject:o,fork(b){let e=Bt({},l);return A0(typeof b==="function"?b(e):Bt(e,b))}};return f.lexer=new Gt({generic:l.generic,cssWideKeywords:l.cssWideKeywords,units:l.units,types:l.types,atrules:l.atrules,properties:l.properties,node:l.node},f),f}var yn=(l)=>A0(Bt({},l));var k0={generic:!0,cssWideKeywords:["initial","inherit","unset","revert","revert-layer"],units:{angle:["deg","grad","rad","turn"],decibel:["db"],flex:["fr"],frequency:["hz","khz"],length:["cm","mm","q","in","pt","pc","px","em","rem","ex","rex","cap","rcap","ch","rch","ic","ric","lh","rlh","vw","svw","lvw","dvw","vh","svh","lvh","dvh","vi","svi","lvi","dvi","vb","svb","lvb","dvb","vmin","svmin","lvmin","dvmin","vmax","svmax","lvmax","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],resolution:["dpi","dpcm","dppx","x"],semitones:["st"],time:["s","ms"]},types:{"abs()":"abs( )","absolute-size":"xx-small|x-small|small|medium|large|x-large|xx-large|xxx-large","acos()":"acos( )","alpha-value":"|","angle-percentage":"|","angular-color-hint":"","angular-color-stop":"&&?","angular-color-stop-list":"[ [, ]?]# , ","animateable-feature":"scroll-position|contents|","asin()":"asin( )","atan()":"atan( )","atan2()":"atan2( , )",attachment:"scroll|fixed|local","attr()":"attr( ? [, ]? )","attr-matcher":"['~'|'|'|'^'|'$'|'*']? '='","attr-modifier":"i|s","attribute-selector":"'[' ']'|'[' [|] ? ']'","auto-repeat":"repeat( [auto-fill|auto-fit] , [? ]+ ? )","auto-track-list":"[? [|]]* ? [? [|]]* ?",axis:"block|inline|x|y","baseline-position":"[first|last]? baseline","basic-shape":"||||||","bg-image":"none|","bg-layer":"|| [/ ]?||||||||","bg-position":"[[left|center|right|top|bottom|]|[left|center|right|] [top|center|bottom|]|[center|[left|right] ?]&&[center|[top|bottom] ?]]","bg-size":"[|auto]{1,2}|cover|contain","blur()":"blur( )","blend-mode":"normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity",box:"border-box|padding-box|content-box","brightness()":"brightness( )","calc()":"calc( )","calc-sum":" [['+'|'-'] ]*","calc-product":" ['*' |'/' ]*","calc-value":"||||( )","calc-constant":"e|pi|infinity|-infinity|NaN","cf-final-image":"|","cf-mixing-image":"?&&","circle()":"circle( []? [at ]? )","clamp()":"clamp( #{3} )","class-selector":"'.' ","clip-source":"",color:"|currentColor||||<-non-standard-color>","color-stop":"|","color-stop-angle":"{1,2}","color-stop-length":"{1,2}","color-stop-list":"[ [, ]?]# , ","color-interpolation-method":"in [| ?|]",combinator:"'>'|'+'|'~'|['|' '|']","common-lig-values":"[common-ligatures|no-common-ligatures]","compat-auto":"searchfield|textarea|push-button|slider-horizontal|checkbox|radio|square-button|menulist|listbox|meter|progress-bar|button","composite-style":"clear|copy|source-over|source-in|source-out|source-atop|destination-over|destination-in|destination-out|destination-atop|xor","compositing-operator":"add|subtract|intersect|exclude","compound-selector":"[? *]!","compound-selector-list":"#","complex-selector":" [? ]*","complex-selector-list":"#","conic-gradient()":"conic-gradient( [from ]? [at ]? , )","contextual-alt-values":"[contextual|no-contextual]","content-distribution":"space-between|space-around|space-evenly|stretch","content-list":"[|contents||||||]+","content-position":"center|start|end|flex-start|flex-end","content-replacement":"","contrast()":"contrast( [] )","cos()":"cos( )",counter:"|","counter()":"counter( , ? )","counter-name":"","counter-style":"|symbols( )","counter-style-name":"","counters()":"counters( , , ? )","cross-fade()":"cross-fade( , ? )","cubic-bezier-timing-function":"ease|ease-in|ease-out|ease-in-out|cubic-bezier( , , , )","deprecated-system-color":"ActiveBorder|ActiveCaption|AppWorkspace|Background|ButtonFace|ButtonHighlight|ButtonShadow|ButtonText|CaptionText|GrayText|Highlight|HighlightText|InactiveBorder|InactiveCaption|InactiveCaptionText|InfoBackground|InfoText|Menu|MenuText|Scrollbar|ThreeDDarkShadow|ThreeDFace|ThreeDHighlight|ThreeDLightShadow|ThreeDShadow|Window|WindowFrame|WindowText","discretionary-lig-values":"[discretionary-ligatures|no-discretionary-ligatures]","display-box":"contents|none","display-inside":"flow|flow-root|table|flex|grid|ruby","display-internal":"table-row-group|table-header-group|table-footer-group|table-row|table-cell|table-column-group|table-column|table-caption|ruby-base|ruby-text|ruby-base-container|ruby-text-container","display-legacy":"inline-block|inline-list-item|inline-table|inline-flex|inline-grid","display-listitem":"?&&[flow|flow-root]?&&list-item","display-outside":"block|inline|run-in","drop-shadow()":"drop-shadow( {2,3} ? )","east-asian-variant-values":"[jis78|jis83|jis90|jis04|simplified|traditional]","east-asian-width-values":"[full-width|proportional-width]","element()":"element( , [first|start|last|first-except]? )|element( )","ellipse()":"ellipse( [{2}]? [at ]? )","ending-shape":"circle|ellipse","env()":"env( , ? )","exp()":"exp( )","explicit-track-list":"[? ]+ ?","family-name":"|+","feature-tag-value":" [|on|off]?","feature-type":"@stylistic|@historical-forms|@styleset|@character-variant|@swash|@ornaments|@annotation","feature-value-block":" '{' '}'","feature-value-block-list":"+","feature-value-declaration":" : + ;","feature-value-declaration-list":"","feature-value-name":"","fill-rule":"nonzero|evenodd","filter-function":"|||||||||","filter-function-list":"[|]+","final-bg-layer":"<'background-color'>|||| [/ ]?||||||||","fixed-breadth":"","fixed-repeat":"repeat( [] , [? ]+ ? )","fixed-size":"|minmax( , )|minmax( , )","font-stretch-absolute":"normal|ultra-condensed|extra-condensed|condensed|semi-condensed|semi-expanded|expanded|extra-expanded|ultra-expanded|","font-variant-css21":"[normal|small-caps]","font-weight-absolute":"normal|bold|","frequency-percentage":"|","general-enclosed":"[ ? )]|[( ? )]","generic-family":"|||<-non-standard-generic-family>","generic-name":"serif|sans-serif|cursive|fantasy|monospace","geometry-box":"|fill-box|stroke-box|view-box",gradient:"||||||<-legacy-gradient>","grayscale()":"grayscale( )","grid-line":"auto||[&&?]|[span&&[||]]","historical-lig-values":"[historical-ligatures|no-historical-ligatures]","hsl()":"hsl( [/ ]? )|hsl( , , , ? )","hsla()":"hsla( [/ ]? )|hsla( , , , ? )",hue:"|","hue-rotate()":"hue-rotate( )","hue-interpolation-method":"[shorter|longer|increasing|decreasing] hue","hwb()":"hwb( [|none] [|none] [|none] [/ [|none]]? )","hypot()":"hypot( # )",image:"||||||","image()":"image( ? [? , ?]! )","image-set()":"image-set( # )","image-set-option":"[|] [||type( )]","image-src":"|","image-tags":"ltr|rtl","inflexible-breadth":"|min-content|max-content|auto","inset()":"inset( {1,4} [round <'border-radius'>]? )","invert()":"invert( )","keyframes-name":"|","keyframe-block":"# { }","keyframe-block-list":"+","keyframe-selector":"from|to|| ","lab()":"lab( [||none] [||none] [||none] [/ [|none]]? )","layer()":"layer( )","layer-name":" ['.' ]*","lch()":"lch( [||none] [||none] [|none] [/ [|none]]? )","leader()":"leader( )","leader-type":"dotted|solid|space|","length-percentage":"|","light-dark()":"light-dark( , )","line-names":"'[' * ']'","line-name-list":"[|]+","line-style":"none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset","line-width":"|thin|medium|thick","linear-color-hint":"","linear-color-stop":" ?","linear-gradient()":"linear-gradient( [[|to ]||]? , )","log()":"log( , ? )","mask-layer":"|| [/ ]?||||||[|no-clip]||||","mask-position":"[|left|center|right] [|top|center|bottom]?","mask-reference":"none||","mask-source":"","masking-mode":"alpha|luminance|match-source","matrix()":"matrix( #{6} )","matrix3d()":"matrix3d( #{16} )","max()":"max( # )","media-and":" [and ]+","media-condition":"|||","media-condition-without-or":"||","media-feature":"( [||] )","media-in-parens":"( )||","media-not":"not ","media-or":" [or ]+","media-query":"|[not|only]? [and ]?","media-query-list":"#","media-type":"","mf-boolean":"","mf-name":"","mf-plain":" : ","mf-range":" ['<'|'>']? '='? | ['<'|'>']? '='? | '<' '='? '<' '='? | '>' '='? '>' '='? ","mf-value":"|||","min()":"min( # )","minmax()":"minmax( [|min-content|max-content|auto] , [||min-content|max-content|auto] )","mod()":"mod( , )","name-repeat":"repeat( [|auto-fill] , + )","named-color":"transparent|aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen","namespace-prefix":"","ns-prefix":"[|'*']? '|'","number-percentage":"|","numeric-figure-values":"[lining-nums|oldstyle-nums]","numeric-fraction-values":"[diagonal-fractions|stacked-fractions]","numeric-spacing-values":"[proportional-nums|tabular-nums]",nth:"|even|odd","opacity()":"opacity( [] )","overflow-position":"unsafe|safe","outline-radius":"|","page-body":"? [; ]?| ","page-margin-box":" '{' '}'","page-margin-box-type":"@top-left-corner|@top-left|@top-center|@top-right|@top-right-corner|@bottom-left-corner|@bottom-left|@bottom-center|@bottom-right|@bottom-right-corner|@left-top|@left-middle|@left-bottom|@right-top|@right-middle|@right-bottom","page-selector-list":"[#]?","page-selector":"+| *","page-size":"A5|A4|A3|B5|B4|JIS-B5|JIS-B4|letter|legal|ledger","path()":"path( [ ,]? )","paint()":"paint( , ? )","perspective()":"perspective( [|none] )","polygon()":"polygon( ? , [ ]# )","polar-color-space":"hsl|hwb|lch|oklch",position:"[[left|center|right]||[top|center|bottom]|[left|center|right|] [top|center|bottom|]?|[[left|right] ]&&[[top|bottom] ]]","pow()":"pow( , )","pseudo-class-selector":"':' |':' ')'","pseudo-element-selector":"':' |","pseudo-page":": [left|right|first|blank]",quote:"open-quote|close-quote|no-open-quote|no-close-quote","radial-gradient()":"radial-gradient( [||]? [at ]? , )",ratio:" [/ ]?","ray()":"ray( &&?&&contain?&&[at ]? )","ray-size":"closest-side|closest-corner|farthest-side|farthest-corner|sides","rectangular-color-space":"srgb|srgb-linear|display-p3|a98-rgb|prophoto-rgb|rec2020|lab|oklab|xyz|xyz-d50|xyz-d65","relative-selector":"? ","relative-selector-list":"#","relative-size":"larger|smaller","rem()":"rem( , )","repeat-style":"repeat-x|repeat-y|[repeat|space|round|no-repeat]{1,2}","repeating-conic-gradient()":"repeating-conic-gradient( [from ]? [at ]? , )","repeating-linear-gradient()":"repeating-linear-gradient( [|to ]? , )","repeating-radial-gradient()":"repeating-radial-gradient( [||]? [at ]? , )","reversed-counter-name":"reversed( )","rgb()":"rgb( {3} [/ ]? )|rgb( {3} [/ ]? )|rgb( #{3} , ? )|rgb( #{3} , ? )","rgba()":"rgba( {3} [/ ]? )|rgba( {3} [/ ]? )|rgba( #{3} , ? )|rgba( #{3} , ? )","rotate()":"rotate( [|] )","rotate3d()":"rotate3d( , , , [|] )","rotateX()":"rotateX( [|] )","rotateY()":"rotateY( [|] )","rotateZ()":"rotateZ( [|] )","round()":"round( ? , , )","rounding-strategy":"nearest|up|down|to-zero","saturate()":"saturate( )","scale()":"scale( [|]#{1,2} )","scale3d()":"scale3d( [|]#{3} )","scaleX()":"scaleX( [|] )","scaleY()":"scaleY( [|] )","scaleZ()":"scaleZ( [|] )","scroll()":"scroll( [||]? )",scroller:"root|nearest|self","self-position":"center|start|end|self-start|self-end|flex-start|flex-end","shape-radius":"|closest-side|farthest-side","sign()":"sign( )","skew()":"skew( [|] , [|]? )","skewX()":"skewX( [|] )","skewY()":"skewY( [|] )","sepia()":"sepia( )",shadow:"inset?&&{2,4}&&?","shadow-t":"[{2,3}&&?]",shape:"rect( , , , )|rect( )","shape-box":"|margin-box","side-or-corner":"[left|right]||[top|bottom]","sin()":"sin( )","single-animation":"<'animation-duration'>||||<'animation-delay'>||||||||||[none|]||","single-animation-direction":"normal|reverse|alternate|alternate-reverse","single-animation-fill-mode":"none|forwards|backwards|both","single-animation-iteration-count":"infinite|","single-animation-play-state":"running|paused","single-animation-timeline":"auto|none|||","single-transition":"[none|]||