### Install WebContainer API with npm Source: https://webcontainers.io/guides/quickstart Installs the WebContainer API package using npm. This is the first step to integrate the API into your project. ```bash npm i @webcontainer/api ``` -------------------------------- ### Run npm Install and Dev Server in WebContainer Source: https://webcontainers.io/guides/quickstart Shows how to execute commands within the WebContainer, specifically 'npm install' followed by 'npm run dev'. It includes error handling for the install process. ```javascript async function startDevServer() { const installProcess = await webcontainerInstance.spawn('npm', ['install']); const installExitCode = await installProcess.exit; if (installExitCode !== 0) { throw new Error('Unable to run npm install'); } // `npm run dev` await webcontainerInstance.spawn('npm', ['run', 'dev']); } ``` -------------------------------- ### Create a WebContainer Instance Source: https://webcontainers.io/guides/quickstart Demonstrates how to create a WebContainer instance by importing `WebContainer` and calling the `boot` method. This method should only be called once. ```javascript import { WebContainer } from '@webcontainer/api'; // Call only once const webcontainerInstance = await WebContainer.boot(); ``` -------------------------------- ### Mount Project Files into WebContainer Source: https://webcontainers.io/guides/quickstart Loads project files into the WebContainer's file system using the `mount` method. This is recommended for optimal performance, especially on page load. ```javascript await webcontainerInstance.mount(projectFiles); ``` -------------------------------- ### mkdir - Create Directory Source: https://webcontainers.io/guides/working-with-the-file-system Creates a new directory at the specified path. Supports creating nested directories recursively. ```APIDOC ## POST /fs/mkdir ### Description Creates a directory at the specified path. If the directory already exists, an error will be thrown unless the `recursive` option is used. ### Method POST ### Endpoint `/fs/mkdir` ### Parameters #### Query Parameters - **path** (string) - Required - The path for the new directory. - **options** (object) - Optional - Options for directory creation. - **recursive** (boolean) - Optional - If true, creates parent directories as needed. Defaults to false. ### Request Example ```js // Create a single directory await webcontainerInstance.fs.mkdir('src'); // Create nested directories await webcontainerInstance.fs.mkdir('this/is/my/nested/folder', { recursive: true }); ``` ### Response #### Success Response (200) Indicates the directory was created successfully. No content is typically returned. ``` -------------------------------- ### Spawning a Process in WebContainers Source: https://webcontainers.io/guides/running-processes Demonstrates how to spawn a process using the `spawn` method in WebContainers. This method takes the command and an array of arguments. It's used here to execute `npm install`. ```javascript webcontainerInstance.spawn('npm', ['install']); ``` -------------------------------- ### Handle Server Ready Event for Preview Source: https://webcontainers.io/guides/quickstart Attaches an event listener to the `server-ready` event emitted by the WebContainer. This event provides the URL to preview the application, typically by setting an iframe's source. ```javascript webcontainerInstance.on('server-ready', (port, url) => (iframeEl.src = url)); ``` -------------------------------- ### Running a Development Server in WebContainers Source: https://webcontainers.io/guides/running-processes An asynchronous function that starts a development server within a WebContainer using `npm run start`. It listens for the `server-ready` event to know when the server is available and provides the port and URL. ```javascript async function startDevServer() { // Run `npm run start` to start the Express app await webcontainerInstance.spawn('npm', ['run', 'start']); // Wait for `server-ready` event webcontainerInstance.on('server-ready', (port, url) => { // ... }); } ``` -------------------------------- ### List Directory Contents in WebContainers Source: https://webcontainers.io/guides/working-with-the-file-system Provides an example of how to list the files and directories within a specified directory in the WebContainer's file system using `webcontainerInstance.fs.readdir`. The method returns an array of strings representing the names of the entries in the directory. ```javascript const files = await webcontainerInstance.fs.readdir('/src'); // ^ is an array of strings ``` -------------------------------- ### Spawning a Process with Multiple Arguments in WebContainers Source: https://webcontainers.io/guides/running-processes Illustrates spawning a process with multiple arguments using `webcontainerInstance.spawn`. This example shows how to execute the `ls` command with the `src` directory and the `-l` flag. ```javascript webcontainerInstance.spawn('ls', ['src', '-l']); ``` -------------------------------- ### Configure Cross-Origin Isolation Headers Source: https://webcontainers.io/guides/quickstart Specifies the necessary COOP and COEP headers required for WebContainers, which depend on `SharedArrayBuffer`. These headers ensure the website is cross-origin isolated. ```yaml Cross-Origin-Embedder-Policy: require-corp Cross-Origin-Opener-Policy: same-origin ``` -------------------------------- ### Generating and Mounting Snapshots Source: https://webcontainers.io/guides/working-with-the-file-system Explains how to generate a binary snapshot of a local folder using `@webcontainer/snapshot` and how to serve it. It also details how to fetch this snapshot on the client-side and mount it into a WebContainer. ```APIDOC ## Generating and Mounting Snapshots ### Description Generates a binary snapshot of a folder for efficient mounting in WebContainers. Provides server-side examples (Express, SvelteKit) for serving the snapshot and client-side code for fetching and mounting it. ### Method `snapshot(source: string): Promise` (from `@webcontainer/snapshot`) `webcontainerInstance.mount(snapshot: ArrayBuffer)` ### Parameters #### `snapshot` Function Parameters - **source** (`string`) - Required - The path to the source code folder on the server. #### `mount` Method Parameters - **snapshot** (`ArrayBuffer`) - Required - The binary snapshot data to mount. ### Server-Side Request Example (Express.js) ```javascript import { snapshot } from '@webcontainer/snapshot'; const SOURCE_CODE_FOLDER = './path/to/your/source-code'; const folderSnapshot = await snapshot(SOURCE_CODE_FOLDER); app.get('/snapshot', (req, res) => { res .setHeader('content-type', 'application/octet-stream') .send(folderSnapshot); }); ``` ### Server-Side Request Example (SvelteKit) ```typescript import { snapshot } from '@webcontainer/snapshot'; const SOURCE_CODE_FOLDER = './path/to/your/source-code'; const sourceSnapshot = await snapshot(SOURCE_CODE_FOLDER); export function getSnapshot(req: Request) { return new Response(sourceSnapshot, { headers: { 'content-type': 'application/octet-stream', }, }); } ``` ### Client-Side Request Example ```javascript import { WebContainer } from '@webcontainer/api'; const webcontainer = await WebContainer.boot(); const snapshotResponse = await fetch('/snapshot'); const snapshot = await snapshotResponse.arrayBuffer(); await webcontainer.mount(snapshot); ``` ``` -------------------------------- ### Installing Dependencies in WebContainers Source: https://webcontainers.io/guides/running-processes An asynchronous function that installs project dependencies within a WebContainer instance using `npm install`. It returns the exit code of the installation process, indicating success or failure. ```javascript async function installDependencies() { // Install dependencies const installProcess = await webcontainerInstance.spawn('npm', ['install']); // Wait for install command to exit return installProcess.exit; } ``` -------------------------------- ### Configure Specific Page Headers in SvelteKit (hooks.server.js) Source: https://webcontainers.io/guides/configuring-headers This SvelteKit example shows how to apply Cross-Origin Isolation headers to a specific page (e.g., '/tutorial') using the `hooks.server.js` file. It checks the request path and conditionally adds the headers, allowing for granular control over security policies. ```javascript export const handle = async ({ request, resolve }) => { const response = await resolve(request); if (request.path === '/tutorial') { response.headers.set('Cross-Origin-Embedder-Policy', 'require-corp'); response.headers.set('Cross-Origin-Opener-Policy', 'same-origin'); } return response; }; ``` -------------------------------- ### Write File with Encoding (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Writes file content to a specified path using a given encoding. This allows for writing data in different character sets or formats. The example shows writing a string with 'latin1' encoding. ```javascript await webcontainerInstance.fs.writeFile( '/src/main.js', '\xE5\x8D\x83\xE8\x91\x89\xE5\xB8\x82\xE3\x83\x96\xE3\x83\xAB\xE3\x83\xBC\xE3\x82\xB9', { encoding: 'latin1' } ); ``` ```javascript await webcontainerInstance.fs.writeFile( '/src/main.js', '\xE5\x8D\x83\xE8\x91\x89\xE5\xB8\x82\xE3\x83\x96\xE3\x83\xAB\xE3\x83\xBC\xE3\x82\xB9', { encoding: 'latin1' } ); ``` -------------------------------- ### Mounting Files to a Different Path Source: https://webcontainers.io/guides/working-with-the-file-system Demonstrates how to mount a file system tree to a specific directory within the WebContainer, rather than the root. It also shows how to create the target directory beforehand if it doesn't exist. ```APIDOC ## Mounting Files to a Different Path ### Description Mounts a `FileSystemTree` to a specified `mountPoint`. Ensures the directory exists before mounting. ### Method `webcontainerInstance.mount(files: FileSystemTree, { mountPoint?: string }) webcontainerInstance.fs.mkdir(path: string) ### Parameters #### `mount` Method Parameters - **files** (`FileSystemTree`) - Required - The file system tree to mount. - **mountPoint** (`string`) - Optional - The path within the WebContainer to mount the files. Defaults to root. #### `mkdir` Method Parameters - **path** (`string`) - Required - The path of the directory to create. ### Request Example (Mounting with mountPoint) ```javascript /** @type {import('@webcontainer/api').FileSystemTree} */ const files = { 'package.json': { content: '{ "name": "my-app" }' }, 'index.html': { content: '

Hello

' }, }; await webcontainerInstance.mount(files, { mountPoint: 'my-mount-point' }); ``` ### Request Example (Creating directory and mounting) ```javascript await webcontainerInstance.fs.mkdir('my-mount-point'); await webcontainerInstance.mount(files, { mountPoint: 'my-mount-point' }); ``` ``` -------------------------------- ### writeFile - Write to a File Source: https://webcontainers.io/guides/working-with-the-file-system Writes content to a file at the specified path. Creates the file if it doesn't exist or overwrites it if it does. Encoding can also be specified. ```APIDOC ## PUT /fs/writeFile ### Description Writes data to a file at the specified path. If the file does not exist, it will be created. If it exists, it will be overwritten. An optional encoding can be provided. ### Method PUT ### Endpoint `/fs/writeFile` ### Parameters #### Query Parameters - **path** (string) - Required - The path where the file will be written. - **data** (string | Buffer | UInt8Array) - Required - The content to write to the file. - **options** (object) - Optional - Options for writing the file. - **encoding** (string) - Optional - The encoding to use when writing the file. Defaults to 'utf8'. ### Request Example ```js // Write a string to a file await webcontainerInstance.fs.writeFile('/src/main.js', 'console.log("Hello from WebContainers!")'); // Write with a specific encoding await webcontainerInstance.fs.writeFile( '/src/main.js', '\xE5\x8D\x83\xE8\x91\x89\xE5\xB8\x82\xE3\x83\x96\xE3\x83\xAB\xE3\x83\xBC\xE3\x82\xB9', { encoding: 'latin1' } ); ``` ### Response #### Success Response (200) Indicates the file was written successfully. No content is typically returned. ``` -------------------------------- ### Mounting Folders and Files in WebContainer JS Source: https://webcontainers.io/guides/working-with-the-file-system Illustrates how to mount directories and their contents within a WebContainer. Directories are represented by a `directory` key, and files within them are nested similarly. This allows for complex project structures to be loaded. ```javascript /** @type {import('@webcontainer/api').FileSystemTree} */ const files = { // This is a directory - provide its name as a key src: { // Because it's a directory, add the "directory" key directory: { // This is a file - provide its path as a key: 'main.js': { // Because it's a file, add the "file" key file: { contents: ` console.log('Hello from WebContainers!') `, }, }, // This is another file inside the same folder 'main.css': { // Because it's a file, add the "file" key file: { contents: ` body { margin: 0; } `, }, }, }, }, // This is a file outside the folder 'package.json': { /* Omitted for brevity */ }, // This is another file outside the folder 'index.html': { /* Omitted for brevity */ }, }; await webcontainerInstance.mount(files); ``` -------------------------------- ### Represent a directory in WebContainer's file system (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Illustrates how to represent a directory in the WebContainer's virtual file system. It shows the structure for defining a directory and preparing it to contain files. ```javascript const files = { src: { directory: { }, }, }; ``` -------------------------------- ### Generate and Mount Binary Snapshots in WebContainers Source: https://webcontainers.io/guides/working-with-the-file-system Explains how to generate a binary snapshot of a source code folder using `@webcontainer/snapshot` and serve it. The client-side application can then fetch this snapshot and mount it into a WebContainer instance, enabling efficient transfer of large codebases. ```typescript import { snapshot } from '@webcontainer/snapshot'; // snapshot is a `Buffer` const folderSnapshot = await snapshot(SOURCE_CODE_FOLDER); // for an express-based application app.get('/snapshot', (req, res) => { res .setHeader('content-type', 'application/octet-stream') .send(snapshot); }); // for a SvelteKit-like application export function getSnapshot(req: Request) { return new Response(sourceSnapshot, { headers: { 'content-type': 'application/octet-stream', }, }); } ``` ```typescript import { WebContainer } from '@webcontainer/api'; const webcontainer = await WebContainer.boot(); const snapshotResponse = await fetch('/snapshot'); const snapshot = await snapshotResponse.arrayBuffer(); await webcontainer.mount(snapshot); ``` -------------------------------- ### Create Directory (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Creates a directory at the specified path. If the directory already exists, an error will be thrown. The `recursive: true` option allows for the creation of nested directories in a single call. ```javascript await webcontainerInstance.fs.mkdir('src'); ``` ```javascript await webcontainerInstance.fs.mkdir('src'); ``` -------------------------------- ### Configure Specific Page Headers in Nuxt 3 (nuxt.config.js) Source: https://webcontainers.io/guides/configuring-headers This Nuxt 3 example configures Cross-Origin Isolation headers for a specific page, '/tutorial', using `nuxt.config.js`. By specifying the route '/tutorial' in `nitro.routeRules`, the headers are applied only to that particular path, providing targeted security settings. ```javascript // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ nitro: { routeRules: { '/tutorial': { headers: { 'Cross-Origin-Embedder-Policy': 'require-corp', 'Cross-Origin-Opener-Policy': 'same-origin', }, }, }, }, }); ``` -------------------------------- ### Mounting Multiple Files in WebContainer JS Source: https://webcontainers.io/guides/working-with-the-file-system Demonstrates how to load multiple files into a WebContainer instance by providing an object with file paths as keys to the `mount` method. Each file object contains its content. This is useful for setting up project structures. ```javascript /** @type {import('@webcontainer/api').FileSystemTree} */ const files = { 'package.json': { file: { contents: ` { "name": "vite-starter", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "devDependencies": { "vite": "^4.0.4" } }`, }, }, 'index.html': { file: { contents: ` Vite App
`, }, }, }; await webcontainerInstance.mount(files); ``` -------------------------------- ### Mount a single file into WebContainer's file system (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Loads a single file, `package.json`, into the root of the WebContainer's virtual file system using the `mount` method. Requires the `webcontainerInstance` to be initialized. ```javascript /** @type {import('@webcontainer/api').FileSystemTree} */ const files = { 'package.json': { file: { contents: ` { "name": "vite-starter", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "devDependencies": { "vite": "^4.0.4" } }`, }, }, }; await webcontainerInstance.mount(files); ``` -------------------------------- ### rm - Remove File or Directory Source: https://webcontainers.io/guides/working-with-the-file-system Deletes a file or a directory. For directories, a `recursive: true` option is required to delete its contents. ```APIDOC ## DELETE /fs/rm ### Description Deletes a file or a directory. If the path points to a file, the file is deleted. If the path points to a directory, the `recursive: true` option must be provided to delete the directory and all its contents. ### Method DELETE ### Endpoint `/fs/rm` ### Parameters #### Query Parameters - **path** (string) - Required - The path to the file or directory to remove. - **options** (object) - Optional - Options for removal. - **recursive** (boolean) - Required if removing a directory. If true, deletes the directory and its contents. - **force** (boolean) - Optional - If true, ignores errors if a specified file does not exist. ### Request Example ```js // Delete a file await webcontainerInstance.fs.rm('/src/main.js'); // Delete a directory await webcontainerInstance.fs.rm('/src', { recursive: true }); ``` ### Response #### Success Response (204) No content is returned upon successful deletion. ``` -------------------------------- ### Read a file from WebContainer's file system (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Reads the content of a file, specifically `/package.json`, from the WebContainer's virtual file system using the `readFile` method. ```javascript const file = await webcontainerInstance.fs.readFile('/package.json'); ``` -------------------------------- ### readdir - encoding Option Source: https://webcontainers.io/guides/working-with-the-file-system Allows specifying the encoding for the directory entries returned by `readdir`. By default, it returns strings. Setting encoding to 'buffer' returns `UInt8Array`. ```APIDOC ## GET /fs/readdir (with encoding) ### Description Reads the contents of a directory with a specified encoding. By default, `readdir` returns an array of strings. You can pass the `encoding` option to specify the encoding, such as 'buffer' to receive `UInt8Array`. ### Method GET ### Endpoint `/fs/readdir` ### Parameters #### Query Parameters - **path** (string) - Required - The path to the directory to read. - **encoding** (string) - Optional - Specifies the encoding. Use 'buffer' to receive `UInt8Array`. Defaults to 'utf8'. ### Request Example ```js const files = await webcontainerInstance.fs.readdir('/src', { encoding: 'buffer' }); ``` ### Response #### Success Response (200) - **files** (array) - An array of file and directory names. If encoding is 'buffer', the array contains `UInt8Array` objects. #### Response Example ```json [ // Example for encoding: 'buffer' "", "" ] ``` ``` -------------------------------- ### File System Operations (fs) Source: https://webcontainers.io/guides/working-with-the-file-system Details the available file system operations exposed via the `fs` property on the WebContainer instance, including `readFile`, `readdir`, `rm`, `writeFile`, and `mkdir`. ```APIDOC ## File System Operations (`fs`) ### Description Provides an interface for interacting with the WebContainer's file system. Supported methods include `readFile`, `readdir`, `rm`, `writeFile`, and `mkdir`. ### `fs.readFile(path: string, encoding?: string): Promise` Reads the file at the given path. Throws an error if the file does not exist. - **Parameters**: - `path` (`string`): The path to the file to read. - `encoding` (`string`, optional): The encoding to use when reading the file. If not provided, returns a `UInt8Array`. - **Returns**: A `UInt8Array` or a `string` (if encoding is specified). - **Example**: ```javascript // Read as UInt8Array const fileContent = await webcontainerInstance.fs.readFile('/package.json'); // Read as string const fileContentString = await webcontainerInstance.fs.readFile('/package.json', 'utf-8'); ``` ### `fs.readdir(path: string, options?: { withFileTypes?: boolean, encoding?: string }): Promise` Reads a directory and returns an array of its files and directories. Throws an error if the directory does not exist. - **Parameters**: - `path` (`string`): The path to the directory to read. - `options` (`object`, optional): An options object. - `withFileTypes` (`boolean`): If true, the reply will be an array of fs.Dirent: - `encoding` (`string`): Specifies the encoding of the file or directory names. - **Returns**: An array of strings (file/directory names) or `fs.Dirent` objects. - **Example**: ```javascript // Read directory entries as strings const files = await webcontainerInstance.fs.readdir('/src'); // Read directory entries with file types const filesWithTypes = await webcontainerInstance.fs.readdir('/src', { withFileTypes: true }); ``` ### `fs.rm(path: string, options?: { recursive?: boolean, force?: boolean }): Promise` Removes a file or directory. Use with caution, especially with `recursive: true`. - **Parameters**: - `path` (`string`): The path to the file or directory to remove. - `options` (`object`, optional): An options object. - `recursive` (`boolean`): If true, operations will be performed recursively. - `force` (`boolean`): If true, suppresses errors if the path does not exist. ### `fs.writeFile(path: string, data: string | Buffer | UInt8Array, options?: { encoding?: string, mode?: number, flag?: number }): Promise` Writes data to a file, replacing the file if it already exists. - **Parameters**: - `path` (`string`): The path to the file to write. - `data` (`string | Buffer | UInt8Array`): The data to write to the file. - `options` (`object`, optional): An options object for encoding, mode, and flag. ### `fs.mkdir(path: string, options?: { recursive?: boolean }): Promise` Creates a directory. - **Parameters**: - `path` (`string`): The path of the directory to create. - `options` (`object`, optional): An options object. - `recursive` (`boolean`): If true, creates parent directories as needed. ``` -------------------------------- ### readdir - withFileTypes Option Source: https://webcontainers.io/guides/working-with-the-file-system Reads the contents of a directory. When `withFileTypes` is set to `true`, the method returns an array of `Dirent` objects, each containing file name and type information. ```APIDOC ## GET /fs/readdir ### Description Reads the contents of a directory. When `withFileTypes` is set to `true`, the method returns an array of `Dirent` objects. ### Method GET ### Endpoint `/fs/readdir` ### Parameters #### Query Parameters - **path** (string) - Required - The path to the directory to read. - **withFileTypes** (boolean) - Optional - If true, returns `Dirent` objects. Defaults to false. - **encoding** (string) - Optional - Specifies the encoding for the file names. Defaults to 'utf8'. Can be 'buffer' to return `UInt8Array`. ### Request Example ```js const files = await webcontainerInstance.fs.readdir('/src', { withFileTypes: true }); ``` ### Response #### Success Response (200) - **files** (array) - An array of file and directory names, or `Dirent` objects if `withFileTypes` is true. - **Dirent Object Properties**: - **name** (string) - The name of the file or directory. - **isFile()** (function) - Returns true if the entry is a file. - **isDirectory()** (function) - Returns true if the entry is a directory. #### Response Example ```json [ { "name": "index.html", "isFile": () => true, "isDirectory": () => false }, { "name": "src", "isFile": () => false, "isDirectory": () => true } ] ``` ``` -------------------------------- ### Write File (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Writes content to a file at the specified path. If the file does not exist, it will be created. If it already exists, its content will be overwritten. An optional third argument can specify the encoding of the file content. ```javascript await webcontainerInstance.fs.writeFile('/src/main.js', 'console.log("Hello from WebContainers!")'); ``` ```javascript await webcontainerInstance.fs.writeFile('/src/main.js', 'console.log("Hello from WebContainers!")'); ``` -------------------------------- ### Represent a folder with a file in WebContainer's file system (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Shows how to represent a directory containing a file within the WebContainer's virtual file system. This includes defining the directory and then a nested file with its content. ```javascript const files = { src: { directory: { 'main.js': { file: { contents: ` console.log('Hello from WebContainers!') `, }, }, }, }, }; ``` -------------------------------- ### Mount Files to a Custom Path in WebContainers Source: https://webcontainers.io/guides/working-with-the-file-system Demonstrates how to mount a file system tree to a specific directory within the WebContainer using the `mountPoint` option. Ensures the target directory exists before mounting to prevent errors. This method is useful for organizing project files or mounting external resources to non-root locations. ```javascript /** @type {import('@webcontainer/api').FileSystemTree} */ const files = { 'package.json': { /* Omitted for brevity */ }, 'index.html': { /* Omitted for brevity */ }, }; await webcontainerInstance.mount(files, { mountPoint: 'my-mount-point' }); ``` ```javascript await webcontainerInstance.fs.mkdir('my-mount-point'); await webcontainerInstance.mount(files, { mountPoint: 'my-mount-point' }); ``` -------------------------------- ### Represent a JSON file in WebContainer's file system (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Demonstrates the data structure for representing a single file, specifically a `package.json`, within the WebContainer's virtual file system. It shows how to define the file path and its content. ```javascript const files = { 'package.json': { file: { contents: ` { "name": "vite-starter", "private": true, // ... }, "devDependencies": { "vite": "^4.0.4" } }`, }, }, }; ``` -------------------------------- ### Read File Content with Encoding in WebContainers Source: https://webcontainers.io/guides/working-with-the-file-system Illustrates how to read the content of a file from the WebContainer's file system using `webcontainerInstance.fs.readFile`. It shows how to retrieve the content as a `UInt8Array` by default, or as a string when a specific encoding like 'utf-8' is provided. ```javascript const file = await webcontainerInstance.fs.readFile('/package.json'); // ^ it is a UInt8Array ``` ```javascript const file = await webcontainerInstance.fs.readFile('/package.json', 'utf-8'); // ^ it is a string ``` -------------------------------- ### Create Nested Directory Recursively (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Creates a nested directory structure in a single operation using the `recursive: true` option. This is convenient for setting up complex directory layouts without needing to create each directory individually. ```javascript await webcontainerInstance.fs.mkdir('this/is/my/nested/folder', { recursive: true }); ``` ```javascript await webcontainerInstance.fs.mkdir('this/is/my/nested/folder', { recursive: true }); ``` -------------------------------- ### Read Directory with Encoding Option (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Reads the contents of a directory and allows specifying the encoding of the returned file names. By default, `readdir` returns an array of strings. When `encoding` is set to 'buffer', it returns an array of `UInt8Array`. ```javascript const files = await webcontainerInstance.fs.readdir('/src', { encoding: 'buffer' }); // ^ it is an array of UInt8Array ``` ```javascript const files = await webcontainerInstance.fs.readdir('/src', { encoding: 'buffer' }); // ^ it is an array of UInt8Array ``` -------------------------------- ### Remove File or Directory (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Deletes a file or a directory. For files, a simple path is sufficient. For directories, the `recursive: true` option must be provided to delete the directory and all its contents. The `force` option can also be used for deletion. ```javascript // Delete a file await webcontainerInstance.fs.rm('/src/main.js'); // Delete a directory await webcontainerInstance.fs.rm('/src', { recursive: true }); ``` ```javascript // Delete a file await webcontainerInstance.fs.rm('/src/main.js'); // Delete a directory await webcontainerInstance.fs.rm('/src', { recursive: true }); ``` -------------------------------- ### Read Directory with File Types (JavaScript) Source: https://webcontainers.io/guides/working-with-the-file-system Reads the contents of a directory and returns an array of `Dirent` objects. Each `Dirent` object contains information about the file or directory, such as its name and type (file or directory). This is useful for distinguishing between files and subdirectories without needing to perform additional file system operations. ```javascript const files = await webcontainerInstance.fs.readdir('/src', { withFileTypes: true, }); ``` ```javascript const files = await webcontainerInstance.fs.readdir('/src', { withFileTypes: true, }); ``` -------------------------------- ### Run Command in Specific Directory with WebContainer Source: https://webcontainers.io/guides/troubleshooting This code snippet shows how to execute a command within a specific directory using the WebContainer API's `spawn` method. It demonstrates passing the `--cwd` flag to the `turbo` command, followed by the desired project path and the actual command to execute (e.g., `astro dev`). This is useful for managing multiple projects or running commands in isolated environments. ```javascript webcontainer.spawn('turbo', ['--cwd', `~/projects/${id}`, 'exec', 'astro', 'dev']); ``` ```javascript webcontainer.spawn('turbo', ['--cwd', `~/projects/${id}`, 'exec', 'astro', 'dev']); ``` -------------------------------- ### Configure All Page Headers in Next.js (next.config.js) Source: https://webcontainers.io/guides/configuring-headers This Next.js configuration sets Cross-Origin Isolation headers for all pages using the `headers` function in `next.config.js`. The `source: '/(.*)'` pattern targets all incoming requests, applying the specified headers globally across the application. ```javascript // https://nextjs.org/docs/api-reference/next.config.js/introduction module.exports = { async headers() { return [ { source: '/(.*)', headers: [ { key: 'Cross-Origin-Embedder-Policy', value: 'require-corp', }, { key: 'Cross-Origin-Opener-Policy', value: 'same-origin', }, ], }, ]; }, }; ``` -------------------------------- ### Configure All Page Headers in SvelteKit (hooks.server.js) Source: https://webcontainers.io/guides/configuring-headers This snippet configures Cross-Origin Isolation headers for all pages in a SvelteKit application by modifying the `hooks.server.js` file. It intercepts requests and adds the required headers to the response. This is useful for ensuring consistent security policies across your entire site. ```javascript export const handle = async ({ request, resolve }) => { const response = await resolve(request); response.headers.set('Cross-Origin-Embedder-Policy', 'require-corp'); response.headers.set('Cross-Origin-Opener-Policy', 'same-origin'); return response; }; ``` -------------------------------- ### Reading Process Output in WebContainers Source: https://webcontainers.io/guides/running-processes Shows how to capture and process the output of a spawned process in WebContainers. The `output` property of the `WebContainerProcess` is piped to a `WritableStream` to log the data to the console. ```javascript const installProcess = await webcontainerInstance.spawn('npm', ['install']); installProcess.output.pipeTo(new WritableStream({ write(data) { console.log(data); } })); ``` -------------------------------- ### Configure Specific Page Headers in SvelteKit (+page.server.js) Source: https://webcontainers.io/guides/configuring-headers This SvelteKit code demonstrates setting Cross-Origin Isolation headers for a specific page using its `+page.server.js` file. The `setHeaders` function is used within the `load` export to directly configure headers for that particular route. This method is cleaner for single-page header configurations. ```javascript /** @type {import('./$types').PageServerLoad} */ export const load = ({ setHeaders }) => { setHeaders({ 'Cross-Origin-Embedder-Policy': 'require-corp', 'Cross-Origin-Opener-Policy': 'same-origin', }); }; ``` -------------------------------- ### Configure All Page Headers in Nuxt 3 (nuxt.config.js) Source: https://webcontainers.io/guides/configuring-headers This Nuxt 3 configuration sets Cross-Origin Isolation headers for all pages by utilizing the `nitro.routeRules` in `nuxt.config.js`. The `'**'` pattern ensures that the headers are applied globally to every route within the application. ```javascript // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ nitro: { routeRules: { '**': { headers: { 'Cross-Origin-Embedder-Policy': 'require-corp', 'Cross-Origin-Opener-Policy': 'same-origin', }, }, }, }, }); ``` -------------------------------- ### Configure Page-Specific Headers in Next.js Source: https://webcontainers.io/guides/configuring-headers This snippet shows how to define custom HTTP headers for a specific route ('/tutorial') in a Next.js application. It uses the `headers` function within `next.config.js` to return an array of header configurations. The configuration includes the `source` path and an array of `headers` with their respective `key` and `value`. ```javascript // https://nextjs.org/docs/api-reference/next.config.js/introduction module.exports = { async headers() { return [ { source: '/tutorial', headers: [ { key: 'Cross-Origin-Embedder-Policy', value: 'require-corp', }, { key: 'Cross-Origin-Opener-Policy', value: 'same-origin', }, ], }, ]; }, }; ``` -------------------------------- ### Add CORS Headers with Vite Plugin Source: https://webcontainers.io/guides/troubleshooting This JavaScript code snippet demonstrates how to add Cross-Origin Opener Policy (COOP), Cross-Origin Embedder Policy (COEP), and Cross-Origin Resource Policy (CORP) headers using a Vite plugin. This is useful for ensuring cross-origin isolation, which is required for certain WebContainer features. The plugin configures the server middleware to set these headers for all responses. ```javascript { name: 'add-cors', configureServer(server) { server.middlewares.use((_req, res, next) => { res.setHeader('Cross-Origin-Opener-Policy', 'same-origin'); res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp'); res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); next(); }); }, } ``` ```javascript { name: 'add-cors', configureServer(server) { server.middlewares.use((_req, res, next) => { res.setHeader('Cross-Origin-Opener-Policy', 'same-origin'); res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp'); res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); next(); }); }, } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.