### Run Development Server (Bash) Source: https://github.com/vercel/bidc/blob/main/example/README.md Starts the Next.js development server. After installing dependencies and building the library, navigate to the 'example' directory and run this command. The demo will be accessible at http://localhost:3000. ```bash cd example npm run dev # or pnpm dev ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/vercel/bidc/blob/main/example/README.md Installs project dependencies using npm or pnpm. Navigate to the 'example' directory first. This is a prerequisite for running the development server. ```bash cd example npm install # or pnpm install ``` -------------------------------- ### Build BIDC Library (Bash) Source: https://github.com/vercel/bidc/blob/main/example/README.md Builds the BIDC library from the project's root directory. This step is necessary to make the library available for the Next.js example application. ```bash cd .. pnpm build ``` -------------------------------- ### Install BIDC using pnpm Source: https://github.com/vercel/bidc/blob/main/README.md This command installs the BIDC library using the pnpm package manager. Ensure you have pnpm installed globally before running this command. ```bash pnpm i bidc ``` -------------------------------- ### Promise Serialization Example (TypeScript) Source: https://github.com/vercel/bidc/blob/main/example/README.md Illustrates how the BIDC library serializes promises. When a promise is included in a message payload, it's sent as separate chunks as it resolves, enabling asynchronous data transfer. ```typescript // This promise will be sent when it resolves delayedResponse: new Promise(resolve => setTimeout(() => resolve(`Delayed response: "${message}"`), 2000) ) ``` -------------------------------- ### Parent Page Communication Setup (TypeScript) Source: https://github.com/vercel/bidc/blob/main/example/README.md The parent page (`pages/index.tsx`) in the Next.js app creates an iframe and establishes a bidirectional channel using `createChannel`. It demonstrates sending messages with promises that resolve asynchronously after a delay. ```typescript // Example of creating a channel on the parent side // Assuming 'iframe.contentWindow' is the target window object for the iframe const channel = createChannel('parent-iframe-demo', iframe.contentWindow); // Example of sending a message with a promise channel.postMessage({ type: 'GREETING', payload: { message: 'Hello from parent!', delayedResponse: new Promise(resolve => setTimeout(() => resolve(`Delayed response: "Hello from parent!"`), 2000) ) } }); ``` -------------------------------- ### Iframe Page Communication Setup (TypeScript) Source: https://github.com/vercel/bidc/blob/main/example/README.md The iframe page (`pages/iframe.tsx`) sets up its bidirectional channel by calling `createChannel` without a target, allowing it to communicate with the parent. It handles incoming messages, resolves promises, and sends complex data structures. ```typescript // Example of creating a channel on the iframe side // The library automatically detects the iframe context and uses window.parent const channel = createChannel('parent-iframe-demo'); channel.onMessage(async (message) => { console.log('Message received in iframe:', message); // Handle message and potential promise resolution }); // Example of sending complex data including promises channel.postMessage({ type: 'COMPLEX_DATA', payload: { map: new Map([['key1', 'value1']]), set: new Set([1, 2, 3]), bigInt: BigInt(12345), date: new Date(), asyncData: Promise.resolve({ success: true }) } }); ``` -------------------------------- ### Complex Data Support Example (TypeScript) Source: https://github.com/vercel/bidc/blob/main/example/README.md Demonstrates the seamless support for various complex data types within BIDC messages, including Map, Set, BigInt, Date, and nested promises. These types are serialized and deserialized correctly. ```typescript data: { map: new Map([['key1', 'value1']]), set: new Set([1, 2, 3]), bigInt: BigInt(12345), date: new Date(), asyncData: Promise.resolve({ success: true }) } ``` -------------------------------- ### Concurrent Messages with bidc Source: https://context7.com/vercel/bidc/llms.txt Demonstrates how `bidc` handles multiple simultaneous messages without blocking, utilizing unique message IDs. The example sends ten messages concurrently and uses `Promise.all` to wait for all responses, ensuring efficient processing of asynchronous operations. ```javascript import { createChannel } from 'bidc' const { send, receive } = createChannel(iframe.contentWindow) // Set up receiver await receive(async (data) => { // Simulate variable processing time await new Promise(resolve => setTimeout(resolve, Math.random() * 1000) ) return { processed: data.id } }) // Send multiple messages concurrently const promises = [] for (let i = 0; i < 10; i++) { promises.push( send({ id: i, data: `Message ${i}` }) .then(response => console.log(`Response ${i}:`, response)) ) } // All messages handled concurrently await Promise.all(promises) console.log('All messages processed') ``` -------------------------------- ### Implement Remote Callbacks with Async Functions using Bidc (JavaScript) Source: https://context7.com/vercel/bidc/llms.txt Demonstrates passing async functions between execution contexts using Bidc's `createChannel`. An async function defined in the parent window is sent to an iframe, where it's called. The example highlights how the function executes in its original context, and results are passed back, enabling cross-context asynchronous operations. ```javascript import { createChannel } from 'bidc' // Parent window - send an async function to iframe const { send } = createChannel(iframe.contentWindow) const parentCalculator = async (x) => { console.log('Executing in parent context, x =', x) await new Promise(resolve => setTimeout(resolve, 100)) return x * 3 } // Send function and receive wrapped version back const iframeCalculator = await send(parentCalculator) // Call the returned function (executes chain across contexts) const result = await iframeCalculator(5) console.log('Final result:', result) // 60 (5 * 2 * 3 * 2) // Iframe - receive parent function and wrap it const { receive } = createChannel() await receive((parentCalc) => { return async (y) => { console.log('Executing in iframe context, y =', y) const doubled = y * 2 // Call parent function (crosses back to parent context) const parentResult = await parentCalc(doubled) // Continue processing in iframe return parentResult * 2 } }) ``` -------------------------------- ### Implement Remote Callbacks with BIDC in JavaScript Source: https://github.com/vercel/bidc/blob/main/README.md Illustrates creating nested remote callback mechanisms where both parent and iframe can send and receive async functions. This allows for dynamic function execution across different contexts, enabling complex inter-component logic. The example shows how a function sent from the parent can be modified and returned by the iframe, creating a chain of asynchronous operations. ```javascript import { createChannel } from 'bidc' const { send } = createChannel(iframe.contentWindow) // Give an async function to the iframe // It will always be executed in the parent window's context const calc = await send( async x => { return x * 3 } ) console.log(await calc(1)) ``` ```javascript import { createChannel } from 'bidc' const { receive } = createChannel() receive(parentCalc => { return async y => { const result = await parentCalc(y * 2) return result * 4 } }) ``` -------------------------------- ### Handle Nested Promises with Bidc Channel (JavaScript) Source: https://context7.com/vercel/bidc/llms.txt Illustrates how Bidc handles deeply nested Promises across different contexts using `createChannel`. The example shows a Promise chain with multiple levels of asynchronous resolution, ensuring that each nested Promise is correctly awaited and resolved. ```javascript import { createChannel } from 'bidc' // Parent window const { send } = createChannel(iframe.contentWindow) await send({ level1: new Promise(resolve => { setTimeout(() => { resolve({ level2: new Promise(resolve => { setTimeout(() => { resolve({ level3: new Promise(resolve => { setTimeout(() => { resolve('deeply nested value') }, 500) }) }) }, 500) }) }) }, 500) }) }) // Iframe receiver const { receive } = createChannel() await receive(async (data) => { const result1 = await data.level1 console.log('Level 1 resolved:', result1) const result2 = await result1.level2 console.log('Level 2 resolved:', result2) const result3 = await result2.level3 console.log('Level 3 resolved:', result3) // 'deeply nested value' }) ``` -------------------------------- ### Cleanup and Resource Management with bidc Source: https://context7.com/vercel/bidc/llms.txt Details how to properly clean up communication channels created by `bidc`. The `cleanup` method removes event listeners and closes message ports, preventing memory leaks. An example using React's `useEffect` hook demonstrates lifecycle-aware cleanup. ```javascript import { createChannel } from 'bidc' const { send, receive, cleanup } = createChannel(iframe.contentWindow) // Set up channel await receive((data) => { return { processed: true } }) // Use the channel await send({ data: 'example' }) // Clean up when component unmounts or channel no longer needed cleanup() // Removes all event listeners and closes ports // Example in React import { useEffect } from 'react' useEffect(() => { const channel = createChannel(iframe.contentWindow) channel.receive((data) => { console.log(data) }) // Cleanup on unmount return () => { channel.cleanup() } }, []) ``` -------------------------------- ### Worker Communication with bidc Source: https://context7.com/vercel/bidc/llms.txt Establishes bidirectional communication channels with Web Workers using the `bidc` library. The main thread sends tasks to the worker and receives results, while the worker processes tasks and sends status updates back. This example showcases asynchronous operations within message handlers. ```javascript // Main thread - create worker and establish channel import { createChannel } from 'bidc' const worker = new Worker('./worker.js', { type: 'module' }) const { send, receive } = createChannel(worker) // Send work to worker const result = await send({ operation: 'compute', data: [1, 2, 3, 4, 5], transform: async (x) => x * x }) console.log('Worker result:', result) // Handle messages from worker await receive((status) => { console.log('Worker status:', status) return { acknowledged: true } }) // Worker script (worker.js) import { createChannel } from 'bidc' const { send, receive } = createChannel() await receive(async (task) => { const processed = [] for (const item of task.data) { processed.push(await task.transform(item)) } return { operation: task.operation, result: processed, timestamp: Date.now() } }) // Send status updates setInterval(() => { send({ status: 'alive', memory: performance.memory }) }, 5000) ``` -------------------------------- ### Communicate with Web Workers using BIDC in JavaScript Source: https://github.com/vercel/bidc/blob/main/README.md Shows how to establish communication channels between the main thread and Web Workers using BIDC. By passing a worker instance to `createChannel`, BIDC facilitates message passing for asynchronous operations. This simplifies worker integration for background task processing. ```javascript import { createChannel } from 'bidc' const worker = new Worker('./worker.js') const { send, receive } = createChannel(worker) // ... ``` ```javascript import { createChannel } from 'bidc' const { send, receive } = createChannel() ``` -------------------------------- ### createChannel() - Basic Usage Source: https://context7.com/vercel/bidc/llms.txt Creates a bidirectional communication channel between the current context and a target context. It returns an object with methods to send and receive data, and a cleanup function. ```APIDOC ## createChannel() - Basic Usage ### Description Creates a bidirectional communication channel between the current context and a target context, returning an object with methods to send and receive data. ### Method `createChannel(targetContext, [namespace])` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { createChannel } from 'bidc' // Parent window connecting to iframe const iframe = document.querySelector('iframe') const { send, receive, cleanup } = createChannel(iframe.contentWindow) // Set up receiver to handle incoming messages await receive((data) => { console.log('Received from iframe:', data) return { status: 'received', processed: true } }) // Send data and wait for response const response = await send({ message: 'Hello iframe!', timestamp: Date.now() }) console.log(response) // { status: 'received', processed: true } // Cleanup when done cleanup() ``` ### Response #### Success Response (on `receive` callback) - **data** (any) - The data sent from the other context. - **return value** (any) - The response sent back to the sender. #### Response Example (from `send`) ```json { "status": "received", "processed": true } ``` ``` -------------------------------- ### createChannel() - Namespaced Channels Source: https://context7.com/vercel/bidc/llms.txt Enables the creation of multiple independent channels between the same contexts by using unique namespace identifiers, preventing message conflicts. ```APIDOC ## createChannel() - Namespaced Channels ### Description Creates multiple independent channels between the same contexts using namespace identifiers to prevent message conflicts. ### Method `createChannel(targetContext, namespace)` or `createChannel(namespace)` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Parent window - create two separate channels import { createChannel } from 'bidc' const { send: sendAuth, receive: receiveAuth } = createChannel( iframe.contentWindow, 'auth-channel' ) const { send: sendData, receive: receiveData } = createChannel( iframe.contentWindow, 'data-channel' ) // Set up separate handlers for each namespace await receiveAuth((credentials) => { return { authenticated: true, token: 'jwt-token-here' } }) await receiveData((payload) => { return { processed: true, items: payload.items.length } }) // Inside iframe - match the namespaces const { send: sendAuth, receive: receiveAuth } = createChannel('auth-channel') const { send: sendData, receive: receiveData } = createChannel('data-channel') const authResult = await sendAuth({ username: 'user', password: 'pass' }) const dataResult = await sendData({ items: [1, 2, 3] }) ``` ### Response #### Success Response (on `receive` callback) - **data** (any) - The data sent from the other context for the specific namespace. - **return value** (any) - The response sent back to the sender for the specific namespace. #### Response Example (from `send`) ```json // For auth-channel { "authenticated": true, "token": "jwt-token-here" } // For data-channel { "processed": true, "items": 3 } ``` ``` -------------------------------- ### createChannel() - Default Target Source: https://context7.com/vercel/bidc/llms.txt Creates a channel to the parent context when called without arguments. It automatically detects whether running in an iframe or worker to establish the connection. ```APIDOC ## createChannel() - Default Target ### Description Creates a channel to the parent context when called without arguments, automatically detecting whether running in an iframe or worker. ### Method `createChannel([namespace])` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Inside iframe or worker - connects to parent automatically import { createChannel } from 'bidc' const { send, receive } = createChannel() // Handle messages from parent await receive((data) => { return data.value.toUpperCase() }) // Send messages to parent await send({ from: 'iframe', data: 'Hello parent!' }) ``` ### Response #### Success Response (on `receive` callback) - **data** (any) - The data sent from the parent context. - **return value** (any) - The response sent back to the parent. #### Response Example (from `send`) ```json { "from": "parent", "data": "HELLO PARENT!" } ``` ``` -------------------------------- ### Basic Data Transfer - Iframe Source: https://github.com/vercel/bidc/blob/main/README.md Sets up a channel to the parent window by default and defines a handler for incoming messages. The `receive` function processes the payload and returns a transformed value, which is sent back to the sender. ```javascript import { createChannel } from 'bidc' // Omitting the target will create a channel to the parent window by default // This is equivalent to `createChannel(window.parent)` const { receive } = createChannel() // Handle incoming messages and return a response receive(payload => { return payload.value.toUpperCase() }) ``` -------------------------------- ### Basic Data Transfer - Parent Window Source: https://github.com/vercel/bidc/blob/main/README.md Establishes a channel to an iframe and sends a message, then awaits a response. The `send` function will buffer messages until the connection is ready. It's designed for simple, one-way data transfer with a return acknowledgment. ```javascript import { createChannel } from 'bidc' // Connect to an iframe const { send } = createChannel(iframe.contentWindow) // Send a simple message to the iframe const result = await send({ value: 'Hello, iframe!' }) console.assert(result === 'HELLO, IFRAME!') ``` -------------------------------- ### Error Handling Across Contexts with bidc Source: https://context7.com/vercel/bidc/llms.txt Shows how `bidc` facilitates robust error handling for promises that reject across different JavaScript contexts. Both sending and receiving sides can manage promise rejections gracefully, preventing application crashes and providing clear error messages. ```javascript import { createChannel } from 'bidc' const { send, receive } = createChannel(iframe.contentWindow) // Send data with rejecting promise await send({ willFail: new Promise((resolve, reject) => { setTimeout(() => reject(new Error('Operation failed')), 1000) }), willSucceed: Promise.resolve('Success') }) // Receiver handles errors await receive(async (data) => { try { const failed = await data.willFail } catch (error) { console.error('Promise rejected:', error.message) // 'Operation failed' } const success = await data.willSucceed console.log('Promise resolved:', success) // 'Success' return { handled: true } }) ``` -------------------------------- ### Two-Way Communication - Parent Window Source: https://github.com/vercel/bidc/blob/main/README.md Sets up a bidirectional communication channel with an iframe. It simultaneously handles incoming messages via `receive` and sends outgoing messages using `send`, waiting for responses. ```javascript import { createChannel } from 'bidc' const { send, receive } = createChannel(iframe.contentWindow) // Handle incoming messages from the iframe receive((payload) => { console.log('Received from iframe:', payload) return { response: 'Message received!' } }) // Send a message to the iframe and wait for its response const responseFromIframe = await send({ value: 'Hello, iframe!' }) ``` -------------------------------- ### Transfer Complex JavaScript Data Types with Bidc Channel (JavaScript) Source: https://context7.com/vercel/bidc/llms.txt Demonstrates sending and receiving complex JavaScript data types, including primitives, special types, collections, binary data, Promises, and async functions, using the `createChannel` function from 'bidc'. The `send` function transmits the data, and `receive` handles the incoming data, demonstrating type preservation and async resolution. ```javascript import { createChannel } from 'bidc' const { send, receive } = createChannel(iframe.contentWindow) // Send complex data types await send({ // Primitives string: 'text', number: 42, boolean: true, bigInt: BigInt(9007199254740991), nullValue: null, undefinedValue: undefined, // Special types date: new Date('2024-01-01'), regex: /test-\d+/gi, // Collections map: new Map([['key1', 'value1'], ['key2', 'value2']]), set: new Set([1, 2, 3, 4, 5]), // Binary data arrayBuffer: new Uint8Array([1, 2, 3, 4]).buffer, typedArray: new Float32Array([1.1, 2.2, 3.3]), // Async values promise: Promise.resolve('resolved value'), asyncFunction: async (x) => { await new Promise(resolve => setTimeout(resolve, 100)) return x * 2 } }) // Receive and handle complex types await receive(async (data) => { console.log(data.date instanceof Date) // true console.log(data.regex.test('test-123')) // true console.log(data.map.get('key1')) // 'value1' console.log(data.set.has(3)) // true const promiseValue = await data.promise console.log(promiseValue) // 'resolved value' const result = await data.asyncFunction(5) console.log(result) // 10 return { processed: true } }) ``` -------------------------------- ### Create Namespaced Channels with BIDC in JavaScript Source: https://github.com/vercel/bidc/blob/main/README.md Demonstrates using namespaced channels in BIDC to prevent communication conflicts between different application parts. By specifying unique channel IDs (namespaces) when creating channels, multiple communication streams can coexist without interference. This is essential for complex applications with modular components. ```javascript import { createChannel } from 'bidc' const { send: sendA, receive: receiveA } = createChannel(iframe.contentWindow, 'namespaceA') const { send: sendB, receive: receiveB } = createChannel(iframe.contentWindow, 'namespaceB') ``` ```javascript import { createChannel } from 'bidc' const { send: sendA, receive: receiveA } = createChannel('namespaceA') const { send: sendB, receive: receiveB } = createChannel('namespaceB') ``` -------------------------------- ### Handle Nested Promises with BIDC in JavaScript Source: https://github.com/vercel/bidc/blob/main/README.md Demonstrates managing nested Promises within asynchronous workflows using BIDC. It shows how to send a Promise that resolves to an object containing another Promise, and how to await both Promises on the receiving end. This pattern is useful for complex asynchronous data fetching or processing. ```javascript import { createChannel } from 'bidc' const { send } = createChannel(iframe.contentWindow) await send({ foo: new Promise(resolve => { setTimeout(() => { resolve({ bar: new Promise(resolve => { setTimeout(() => { resolve('Hello from the parent!') }, 1000) }), }) }, 1000) }), }) ``` ```javascript // ... receive(async (data) => { const result = await data.foo const finalResult = await result.bar console.assert(finalResult === 'Hello from the parent!') }) ``` -------------------------------- ### Complex Data Types Transfer and Handling Source: https://github.com/vercel/bidc/blob/main/README.md Demonstrates sending and receiving complex JavaScript data types, including Dates, Maps, Sets, ArrayBuffers, Promises, and async functions. The receiving side handles promises and executes remote functions asynchronously. ```javascript // Send complex objects with various JavaScript types const response = await send({ date: new Date(), map: new Map([['key', 'value']]), set: new Set([1, 2, 3]), arrayBuffer: new Uint8Array([1, 2, 3]).buffer, promise: Promise.resolve('resolved value'), function: async (x) => { await sleep(1000) return x * 2 } }) console.assert(response.status === 'success') ``` ```javascript receive(async (payload) => { // Handle the promise const resolvedValue = await payload.promise console.assert(resolvedValue === 'resolved value') // Call the function const result = await payload.function(5) console.assert(result === 10) return { status: 'success' } }) ``` -------------------------------- ### Two-Way Communication - Iframe Source: https://github.com/vercel/bidc/blob/main/README.md Establishes bidirectional communication with the parent window. It defines a `receive` handler for messages from the parent and uses `send` to transmit messages and await acknowledgments. ```javascript import { createChannel } from 'bidc' const { send, receive } = createChannel() // Handle incoming messages from the parent window receive((payload) => { console.log('Received from parent:', payload) return { response: 'Hello, parent!' } }) // Send a message to the parent window and wait for its response const responseFromParent = await send({ value: 'Hello, parent!' }) ``` -------------------------------- ### Create Namespaced Bidirectional Channels Source: https://context7.com/vercel/bidc/llms.txt Establishes multiple independent bidirectional channels between the same contexts using namespace identifiers. This prevents message conflicts when communicating over different logical channels. Separate handlers are set up for each namespace on both the sending and receiving ends. ```javascript // Parent window - create two separate channels import { createChannel } from 'bidc' const { send: sendAuth, receive: receiveAuth } = createChannel( iframe.contentWindow, 'auth-channel' ) const { send: sendData, receive: receiveData } = createChannel( iframe.contentWindow, 'data-channel' ) // Set up separate handlers for each namespace await receiveAuth((credentials) => { return { authenticated: true, token: 'jwt-token-here' } }) await receiveData((payload) => { return { processed: true, items: payload.items.length } }) // Inside iframe - match the namespaces const { send: sendAuth, receive: receiveAuth } = createChannel('auth-channel') const { send: sendData, receive: receiveData } = createChannel('data-channel') const authResult = await sendAuth({ username: 'user', password: 'pass' }) const dataResult = await sendData({ items: [1, 2, 3] }) ``` -------------------------------- ### encode() Source: https://context7.com/vercel/bidc/llms.txt Encodes a serializable value into an async generator of string chunks. It streams promise resolutions as they occur, allowing for efficient transfer of complex asynchronous data structures. ```APIDOC ## encode() ### Description Encodes a serializable value into an async generator of string chunks, streaming promise resolutions as they occur. ### Method `encode(value)` ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **value** (any) - The value to encode. Can include Promises, Dates, RegExps, Maps, Sets, ArrayBuffers, TypedArrays, and nested structures. ### Request Example ```javascript import { encode } from 'bidc' const data = { immediate: 'available now', delayed: new Promise(resolve => setTimeout(() => resolve('resolved later'), 1000) ), nested: Promise.resolve({ inner: new Promise(resolve => setTimeout(() => resolve('deeply nested'), 2000) ) }) } // Stream encoded chunks for await (const chunk of encode(data)) { console.log('Chunk:', chunk) // First chunk: r:{"immediate":"available now","delayed":"P:0","nested":"P:1"} // Second chunk: p0:"resolved later" // Third chunk: p1:{"inner":"P:2"} // Fourth chunk: p2:"deeply nested" } ``` ### Response #### Success Response (Async Generator) - **chunk** (string) - A string chunk representing a part of the encoded data or a resolved promise. #### Response Example (console output) ``` Chunk: r:{"immediate":"available now","delayed":"P:0","nested":"P:1"} Chunk: p0:"resolved later" Chunk: p1:{"inner":"P:2"} Chunk: p2:"deeply nested" ``` ``` -------------------------------- ### Encode Data with Promises for Streaming Source: https://context7.com/vercel/bidc/llms.txt Encodes a JavaScript value, including Promises and nested Promises, into an asynchronous generator that yields string chunks. This process streams promise resolutions as they occur, allowing for efficient handling of asynchronous data across context boundaries. The output format includes indicators for immediate values, promises, and their resolved data. ```javascript import { encode } from 'bidc' const data = { immediate: 'available now', delayed: new Promise(resolve => setTimeout(() => resolve('resolved later'), 1000) ), nested: Promise.resolve({ inner: new Promise(resolve => setTimeout(() => resolve('deeply nested'), 2000) ) }) } // Stream encoded chunks for await (const chunk of encode(data)) { console.log('Chunk:', chunk) // First chunk: r:{"immediate":"available now","delayed":"P:0","nested":"P:1"} // Second chunk: p0:"resolved later" // Third chunk: p1:{"inner":"P:2"} // Fourth chunk: p2:"deeply nested" } ``` -------------------------------- ### Connection Recovery with bidc Source: https://context7.com/vercel/bidc/llms.txt Illustrates `bidc`'s ability to automatically re-establish connections when one side reloads (e.g., an iframe). Messages sent during a reload are buffered and sent once the connection is restored. The `onResetPort` event handler can be used to perform actions upon successful reconnection. ```javascript import { createChannel } from 'bidc' // Parent window const iframe = document.querySelector('iframe') const { send, receive, onResetPort } = createChannel(iframe.contentWindow) // Monitor connection resets onResetPort((newPort) => { console.log('Connection re-established after iframe reload') // Optional: re-send any critical state send({ type: 'reconnect', timestamp: Date.now() }) }) // Set up receiver await receive((data) => { console.log('Received:', data) return { status: 'ok' } }) // Send message - will wait if iframe is reloading await send({ message: 'Hello' }) // Iframe can reload at any time // The connection will automatically re-establish // Messages sent during reload are buffered ``` -------------------------------- ### Create and Use Bidirectional Channel (Parent to Iframe) Source: https://context7.com/vercel/bidc/llms.txt Creates a bidirectional communication channel between the parent window and an iframe. It allows sending data to the iframe and receiving responses, as well as setting up a receiver for incoming messages from the iframe. The channel can be cleaned up when no longer needed. ```javascript import { createChannel } from 'bidc' // Parent window connecting to iframe const iframe = document.querySelector('iframe') const { send, receive, cleanup } = createChannel(iframe.contentWindow) // Set up receiver to handle incoming messages await receive((data) => { console.log('Received from iframe:', data) return { status: 'received', processed: true } }) // Send data and wait for response const response = await send({ message: 'Hello iframe!', timestamp: Date.now() }) console.log(response) // { status: 'received', processed: true } // Cleanup when done cleanup() ``` -------------------------------- ### Create and Use Bidirectional Channel (Iframe/Worker to Parent) Source: https://context7.com/vercel/bidc/llms.txt Creates a bidirectional channel to the parent context automatically when called without arguments. This is suitable for use within iframes or Web Workers to communicate with their parent context. It allows receiving messages from the parent and sending messages back. ```javascript // Inside iframe or worker - connects to parent automatically import { createChannel } from 'bidc' const { send, receive } = createChannel() // Handle messages from parent await receive((data) => { return data.value.toUpperCase() }) // Send messages to parent await send({ from: 'iframe', data: 'Hello parent!' }) ``` -------------------------------- ### Decode Async Iterable Chunks into Original Value with Promises (JavaScript) Source: https://context7.com/vercel/bidc/llms.txt Decodes an asynchronous iterable of string chunks into the original value, supporting unresolved promises that resolve as chunks arrive. It utilizes the `decode` function from the 'bidc' library. The output includes immediate values and promises that require further awaiting. ```javascript import { decode } from 'bidc' // Simulate receiving chunks over time async function* mockChunks() { yield 'r:{"status":"ok","data":"P:0"}\n' await new Promise(resolve => setTimeout(resolve, 1000)) yield 'p0:{"result":"async value"}\n' } // Decode returns immediately with unresolved promises const result = await decode(mockChunks()) console.log(result.status) // "ok" console.log(result.data) // Promise (pending) // Wait for promise to resolve const data = await result.data console.log(data) // { result: "async value" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.