Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Workleap Squide
https://github.com/workleap/wl-squide
Admin
Modular application shell for building web applications at Workleap.
Tokens:
51,310
Snippets:
204
Trust Score:
9.7
License:
Apache-2.0
Update:
8 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
================ LIBRARY RULES ================ - When generating Squide code, generate modular code using local modules only. Do not generate remote modules code or Module Federation code unless the prompt explicitly asks for it ================ CODE SNIPPETS ================ ### Scaffold application with degit Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-local-module.md Use degit to quickly scaffold a new application based on the wl-squide getting started template. This is a convenient way to start a new project if you prefer not to follow the full guide. ```bash pnpx degit https://github.com/workleap/wl-squide/templates/getting-started ``` -------------------------------- ### Install Logging Package - Bash Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Installs the @workleap/logging package in the host application's terminal. This is a prerequisite for enabling console logging. ```bash pnpm add @workleap/logging ``` -------------------------------- ### Install Honeycomb Packages Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-honeycomb.md Installs the necessary @workleap/telemetry and @opentelemetry/api packages for Honeycomb integration. This command should be run from the root of your host application. ```bash pnpm add @workleap/telemetry @opentelemetry/api ``` -------------------------------- ### Install i18next Packages Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-i18next.md Installs the required i18next packages for internationalization in a Squide project using pnpm. This includes core i18next, react-i18next, and squide's i18next integration. ```bash pnpm add @squide/i18next i18next i18next-browser-languagedetector react-i18next ``` -------------------------------- ### Install MSW and MSW Storybook Addon (Bash) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Installs the Mock Service Worker (MSW) and its Storybook addon. These packages are essential for mocking API requests within Storybook. ```bash pnpm add msw msw-storybook-addon ``` -------------------------------- ### Install LogRocket Package - Bash Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Installs the @workleap/logrocket package in the host application's terminal. This is an alternative to @workleap/telemetry for capturing logs in LogRocket. ```bash pnpm add @workleap/logrocket ``` -------------------------------- ### Install Telemetry Package - Bash Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Installs the @workleap/telemetry package in the host application's terminal. This is required for capturing logs in LogRocket. ```bash pnpm add @workleap/telemetry ``` -------------------------------- ### Install Host Application Dependencies Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Installs development and runtime dependencies for the host application. This includes build tools, configuration packages, and core libraries for the modular application framework. ```bash pnpm add -D @workleap/rsbuild-configs @workleap/browserslist-config @rsbuild/core @rspack/core browserslist typescript @types/react @types/react-dom pnpm add @squide/firefly @tanstack/react-query react react-dom react-router msw launchdarkly-js-client-sdk ``` -------------------------------- ### Install development packages Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-local-module.md Install necessary TypeScript and React development dependencies for the local module. These packages are essential for building and type-checking the module's components and logic. ```bash pnpm add -d typescript @types/react @types/react-dom ``` -------------------------------- ### Define Localized Resource Files Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-i18next.md Defines localized resource files in JSON format for different locales. This example shows files for `en-US` and `fr-CA`, containing navigation and page-specific text, enabling internationalization within the application. ```json { "navigationItems": { "page": "Page - en-US" }, "Page": { "bodyText": "Hello from Page!" } } ``` ```json { "navigationItems": { "page": "Page - fr-CA" }, "Page": { "bodyText": "Bonjour depuis la page!" } } ``` -------------------------------- ### Create MSW Start Function (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-msw.md Defines an asynchronous function `startMsw` that takes an array of MSW request handlers and sets up the browser worker. It configures unhandled requests to be bypassed. ```typescript import type { RequestHandler } from "msw"; import { setupWorker } from "msw/browser"; export async function startMsw(moduleRequestHandlers: RequestHandler[]) { const worker = setupWorker(...moduleRequestHandlers); await worker.start({ onUnhandledRequest: "bypass" }); } ``` -------------------------------- ### Install and Configure TanStack Query Devtools Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-tanstack-query.md This snippet shows how to install and integrate TanStack Query Devtools into a React application. After installing the necessary package, the ReactQueryDevtools component is added within the QueryClientProvider. This allows for real-time inspection and debugging of server state management within the application. ```bash pnpm install -D @tanstack/react-query-devtools ``` ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import { registerHost } from "./register.tsx"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ localModules: [registerHost] }); const queryClient = new QueryClient(); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <QueryClientProvider client={queryClient}> <App /> <ReactQueryDevtools /> </QueryClientProvider> </FireflyProvider> ); ``` -------------------------------- ### Configure PNPM Dev Script with cross-env (JSON) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-msw.md Updates the `dev` script in the `package.json` to use `cross-env` to set the `USE_MSW` environment variable to `true` when starting the development server with Rsbuild. ```json { "scripts": { "dev": "cross-env USE_MSW=true rsbuild dev --config ./rsbuild.dev.ts" } } ``` -------------------------------- ### Initialize MSW with PNPM Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-msw.md Initializes Mock Service Worker (MSW) in the host application's public directory using PNPM. This command should be run from the root of the host application. ```bash pnpx msw init ./public ``` -------------------------------- ### Update Host Application Bootstrapping (TypeScript/React) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-msw.md Updates the main entry point of a React host application to conditionally initialize and start MSW based on the `USE_MSW` environment variable. It dynamically imports MSW handlers to avoid including them in production bundles. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { registerHost } from "./register.tsx"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ useMsw: !!process.env.USE_MSW, localModules: [registerHost], startMsw: async x => { // Files that includes an import to the "msw" package are included dynamically to prevent adding // unused MSW stuff to the code bundles. return (await import("../mocks/browser.ts")).startMsw(x.requestHandlers); } }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Add cross-env for Environment Variables (Bash) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-msw.md Installs the `cross-env` package as a development dependency using PNPM. This package is used to set environment variables in a cross-platform compatible way. ```bash pnpm add -D cross-env ``` -------------------------------- ### Package.json Development Script (JSON) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Adds a 'dev' script to the package.json file to start the Rsbuild development server, using the specified development configuration file. ```json { "dev": "rsbuild dev --config ./rsbuild.dev.ts" } ``` -------------------------------- ### Initialize Mock Service Worker (Bash) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Generates the `mockServiceWorker.js` file in the `/public` folder if it's missing. This file is required for MSW to function correctly. ```bash pnpm dlx msw init ``` -------------------------------- ### Install Squide Firefly Storybook Package (Bash) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Installs the Squide package specifically designed for integrating Firefly with Storybook. This package provides necessary utilities for setting up runtime instances and decorators. ```bash pnpm add @squide/firefly-rsbuild-storybook ``` -------------------------------- ### Enable Console Logging with React - TypeScript Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Explicitly provides a BrowserConsoleLogger instance during Firefly initialization to maintain console logging. This example uses React and TypeScript. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { BrowserConsoleLogger } from "@workleap/logging"; import { MyLogger } from "./MyLogger.tsx"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ loggers: [new MyLogger(), new BrowserConsoleLogger()] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Install @squide/fakes package Source: https://github.com/workleap/wl-squide/blob/main/docs/recipes/add-authentication.md Installs the necessary @squide/fakes package using pnpm. This package provides utilities for creating fake API endpoints and session management. ```bash pnpm add @squide/fakes ``` -------------------------------- ### Setup Firefly Decorator with Runtime (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Configures Storybook to use the `withFireflyDecorator` provided by Squide. This decorator wraps stories with the initialized Firefly runtime, enabling its features. ```tsx import { initializeFireflyForStorybook, withFireflyDecorator } from "@squide/firefly-rsbuild-storybook"; import type { Decorator, Meta, StoryObj } from "storybook-react-rsbuild"; import { Page } from "./Page.tsx"; import { registerModule } from "./registerModule.tsx"; const runtime = await initializeFireflyForStorybook({ localModules: [registerModule] }); const meta = { title: "Page", component: Page, decorators: [ withFireflyDecorator(runtime) ] } satisfies Meta<typeof Page>; export default meta; type Story = StoryObj<typeof meta>; export const Default = {} satisfies Story; ``` -------------------------------- ### Configure Custom Loggers with React - TypeScript Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Replaces the default console logging behavior by providing custom loggers during Firefly initialization. This example uses React and TypeScript. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { MyLogger } from "./MyLogger.tsx"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ loggers: [new MyLogger()] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Capture Logs in LogRocket with React - TypeScript Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Provides an instance of LogRocketLogger during Firefly initialization to capture logs in LogRocket session replays. This example uses React and TypeScript. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { LogRocketLogger } from "@workleap/telemetry/react"; // or from "@workleap/logrocket/react"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ loggers: [new LogRocketLogger()] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Setup MSW Request Handlers for Storybook Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Forwards MSW request handlers registered by modules to the Storybook addon. This ensures that network requests made by Squide components are intercepted and handled correctly within Storybook. It utilizes `initializeFireflyForStorybook` and `FireflyDecorator` from `@squide/firefly-rsbuild-storybook`. ```tsx import { initializeFireflyForStorybook, FireflyDecorator } from "@squide/firefly-rsbuild-storybook"; import type { Decorator, Meta, StoryObj } from "storybook-react-rsbuild"; import { Page } from "./Page.tsx"; import { registerModule } from "./registerModule.tsx"; const runtime = await initializeFireflyForStorybook({ localModules: [registerModule] }); const meta = { title: "Page", component: Page, decorators: [ story => ( <FireflyDecorator runtime={runtime}> {story()} </FireflyDecorator> ) ], parameters: { msw: { handlers: runtime.requestHandlers } } } satisfies Meta<typeof Page>; export default meta; type Story = StoryObj<typeof meta>; export const Default = {} satisfies Story; ``` -------------------------------- ### Enable Console Logging in Production with React - TypeScript Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-logger.md Enables logging to the browser console when Squide is running in production mode by providing a BrowserConsoleLogger instance at initialization. This example uses React and TypeScript. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { BrowserConsoleLogger } from "@workleap/logging"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ mode: "production", loggers: [new BrowserConsoleLogger()] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Register MSW Addon in Storybook Preview (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Updates the `.storybook/preview.tsx` file to register the MSW addon and configure a suspense fallback decorator. This enables MSW's functionality within Storybook. ```tsx import { initialize as initializeMsw, mswLoader } from "msw-storybook-addon"; import { Suspense } from "react"; import type { Preview } from "storybook-react-rsbuild"; initializeMsw({ onUnhandledRequest: "bypass" }); const preview: Preview = { decorators: [ Story => { return ( <Suspense fallback="UNHANDLED SUSPENSE BOUNDARY, should be handled in your components..."> <Story /> </Suspense> ); } ], loaders: [mswLoader] }; export default preview; ``` -------------------------------- ### Configure TanStack Query Client in React App Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-tanstack-query.md This code snippet demonstrates how to configure the TanStack Query client within a React application. It involves creating a QueryClient instance and wrapping the application with QueryClientProvider. This setup is essential for enabling server state management features provided by TanStack Query. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { registerHost } from "./register.tsx"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ localModules: [registerHost] }); const queryClient = new QueryClient(); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <QueryClientProvider client={queryClient}> <App /> </QueryClientProvider> </FireflyProvider> ); ``` -------------------------------- ### Layout Code Example for Rendering Additional Props Source: https://github.com/workleap/wl-squide/blob/main/docs/essentials/register-nav-items.md This React component example shows how to retrieve navigation items, extract `$additionalProps` (like `highlight`), and use them to style the rendered navigation links. It utilizes hooks and types from `@squide/firefly`. ```tsx import { Suspense } from "react"; import { Link, Outlet } from "react-router"; import { useNavigationItems, useRenderedNavigationItems, isNavigationLink, type RenderItemFunction, type RenderSectionFunction } from "@squide/firefly"; const renderItem: RenderItemFunction = (item, key) => { if (!item.canRender()) { return null; } if (!isNavigationLink(item)) { return null; } const { label, linkProps, additionalProps: { highlight, ...additionalProps } } = item; return ( <li key={key} style={{ fontWeight: highlight ? "bold" : "normal" }}> <Link {...linkProps} {...additionalProps}> {label} </Link> </li> ); }; const renderSection: RenderSectionFunction = (elements, key) => { return ( <ul key={key}> {elements} </ul> ); }; export function RootLayout() { // Retrieve the navigation items registered by the modules. const navigationItems = useNavigationItems(); // Transform the navigation items into React elements. const navigationElements = useRenderedNavigationItems(navigationItems, renderItem, renderSection); return ( <> <nav>{navigationElements}</nav> <Suspense fallback={<div>Loading...</div>}> <Outlet /> </Suspense> </> ); } ``` -------------------------------- ### Execute Deferred Registrations Without Remote Data (TypeScript/React) Source: https://github.com/workleap/wl-squide/blob/main/docs/essentials/register-deferred-nav-items.md This example shows how to execute deferred registrations when they do not depend on any remote data. The `useDeferredRegistrations` hook is called without any arguments. Similar to the previous example, `useIsBootstrapping` manages the loading state. ```tsx import { AppRouter, useIsBootstrapping, useDeferredRegistrations } from "@squide/firefly"; import { createBrowserRouter, Outlet } from "react-router"; import { RouterProvider } from "react-router/dom"; function BootstrappingRoute() { useDeferredRegistrations(); if (useIsBootstrapping()) { return <div>Loading...</div>; } return <Outlet />; } export function App() { return ( <AppRouter> {({ rootRoute, registeredRoutes, routerProviderProps }) => { return ( <RouterProvider router={createBrowserRouter([ { element: rootRoute, children: [ { element: <BootstrappingRoute />, children: registeredRoutes } ] } ])} {...routerProviderProps} /> ); }} </AppRouter> ); } ``` -------------------------------- ### Configure Storybook Static Directories (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Updates the `.storybook/main.ts` file to set the `staticDirs` option to `["public"]`. This ensures that static assets, such as the `mockServiceWorker.js` file, are correctly served by Storybook. ```tsx import { createRequire } from "node:module"; import { dirname, join } from "node:path"; import type { StorybookConfig } from "storybook-react-rsbuild"; const require = createRequire(import.meta.url); const storybookConfig: StorybookConfig = { framework: getAbsolutePath("storybook-react-rsbuild"), staticDirs: ["public"] }; export default storybookConfig; // eslint-disable-next-line @typescript-eslint/no-explicit-any function getAbsolutePath(value: string): any { return dirname(require.resolve(join(value, "package.json"))); } ``` -------------------------------- ### Fetch Global Public Data and Set Up Routing Source: https://github.com/workleap/wl-squide/blob/main/docs/essentials/fetch-public-global-data.md This React TypeScript example demonstrates how to fetch global public data using the `usePublicDataQueries` hook and display a loading spinner with `useIsBootstrapping`. It sets up the `AppRouter` with `waitForPublicData` enabled and provides the fetched data through a React context. ```tsx import { AppRouter, usePublicDataQueries, useIsBootstrapping } from "@squide/firefly"; import { createBrowserRouter, Outlet } from "react-router"; import { RouterProvider } from "react-router/dom"; import { FetchCountContext } from "@sample/shared"; function BootstrappingRoute() { const [fetchCount] = usePublicDataQueries([ { queryKey: ["/api/count"], queryFn: async () => { const response = await fetch("/api/count"); if (!response.ok) { throw new Error("Cannot fetch data!"); } const data = await response.json(); return data.count as number; } } ]); if (useIsBootstrapping()) { return <div>Loading...</div>; } return ( <FetchCountContext.Provider value={fetchCount}> <Outlet /> </FetchCountContext.Provider> ); } export function App() { return ( <AppRouter waitForPublicData> {({ rootRoute, registeredRoutes, routerProviderProps }) => { return ( <RouterProvider router={createBrowserRouter([ { element: rootRoute, children: [ { element: <BootstrappingRoute />, children: registeredRoutes } ] } ])} {...routerProviderProps} /> ); }} </AppRouter> ); } ``` -------------------------------- ### Initialize LaunchDarkly Client in React App Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-launch-darkly.md Initializes the LaunchDarkly SDK client and integrates it with the FireflyRuntime in a React application. It requires the 'launchdarkly-js-client-sdk' and '@squide/firefly' packages. The client must be initialized before calling 'initializeFirefly'. ```tsx import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { initialize as initializeLaunchDarkly } from "launchdarkly-js-client-sdk"; import { createRoot } from "react-dom/client"; import { App } from "./App.tsx"; import { registerHost } from "./register.tsx"; const launchDarklyClient = initializeLaunchDarkly("123", { kind: "user", anonymous: true }, { // It's important to use the stream mode to receive feature flags // updates in real time. streaming: true }); try { // Always initialize the client before forwarding the instance to the "initializeFirefly" function. await launchDarklyClient.waitForInitialization(5); } catch (error: unknown) { // Failed to initialize LaunchDarkly... } const runtime = initializeFirefly({ localModules: [registerHost], launchDarklyClient }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Initialize Firefly Runtime for Storybook (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Initializes a runtime instance of Firefly for use within Storybook stories. It takes `localModules` as an argument, allowing custom module registration. ```tsx import { initializeFireflyForStorybook } from "@squide/firefly-rsbuild-storybook"; import type { Decorator, Meta, StoryObj } from "storybook-react-rsbuild"; import { Page } from "./Page.tsx"; import { registerModule } from "./registerModule.tsx"; const runtime = await initializeFireflyForStorybook({ localModules: [registerModule] }); const meta = { title: "Page", component: Page } satisfies Meta<typeof Page>; export default meta; type Story = StoryObj<typeof meta>; export const Default = {} satisfies Story; ``` -------------------------------- ### Setup MSW Handler for Subscription API Source: https://github.com/workleap/wl-squide/blob/main/docs/essentials/fetch-protected-global-data.md Configures a Mock Service Worker (MSW) handler for the `/api/subscription` endpoint. This handler returns hardcoded subscription data for testing purposes. It uses `msw` and `HttpResponse` from `msw`. ```ts import { HttpResponse, http, type HttpHandler } from "msw"; export const requestHandlers: HttpHandler[] = [ http.get("/api/subscription", () => { // NOTE: The user id should be retrieved from the current session and the subscription should be retrieved from a database with this id. // For the sake of simplicity, we haven't done it for this guide, instead we return hardcoded data. return HttpResponse.json([{ "status": "paid" }]); }) ]; ``` -------------------------------- ### Configure Rsbuild for Environment Variables (JavaScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-msw.md Defines development configuration for Rsbuild, specifically enabling the `USE_MSW` environment variable to be included in the application bundles if it's set to 'true' in the Node.js environment. ```js import { defineDevConfig } from "@squide/firefly-webpack-configs"; export default defineDevConfig({ environmentVariables: { "USE_MSW": process.env.USE_MSW === "true" } }); ``` -------------------------------- ### Send Custom Traces with OpenTelemetry API Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-honeycomb.md Demonstrates how to send custom traces to Honeycomb using the OpenTelemetry API directly within a React component. This example shows starting and ending a span named 'my-span' on component mount. ```tsx import { useEffect } from "react"; import { trace } from "@opentelemetry/api"; const tracer = trace.getTracer("my-tracer"); export function Page() { useEffect(() => { // OK, this is a pretty bad example. const span = tracer.startSpan("my-span"); span.end(); }, []); return ( <div>Hello from a page!</div> ); } ``` -------------------------------- ### Initialize Firefly Runtime and Render App Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Initializes the Firefly runtime and renders the main application component using React. This code sets up the root element and wraps the application with the FireflyProvider. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { App } from "./App.tsx"; const runtime = initializeFirefly(); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Package.json Build Script (JSON) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Adds a 'build' script to the package.json file to create a production build of the application, using the specified build configuration file. ```json { "build": "rsbuild build --config rsbuild.build.ts" } ``` -------------------------------- ### Initialize Firefly and Bootstrap Application Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md This code initializes the Squide Firefly runtime with local modules and then renders the main App component within a FireflyProvider. It sets up the root element for the React application. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { registerHost } from "./register.tsx"; import { App } from "./App.tsx"; const runtime = initializeFirefly({ localModules: [registerHost] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### HTML Index Template (HTML) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Provides a basic HTML template for the application's entry point. It includes a root div where the React application will be mounted. ```html <!DOCTYPE html> <html> <head> </head> <body> <div id="root"></div> </body> </html> ``` -------------------------------- ### Environment Variable Initialization and Access Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/learn-core-pieces.md Demonstrates how Squide attaches environment variables to a FireflyRuntime instance, promoting modularity and testability. The first snippet shows initialization with custom variables, and the second shows how to access a specific variable. Requires '@squide/firefly'. ```ts import { initializeFirefly } from "@squide/firefly"; const runtime = initializeFirefly({ environmentVariables: { apiBaseUrl: "https://my-api.com", telemetryBaseUrl: "https://my-telemetry.com" } }); ``` ```ts import { useEnvironmentVariable } from "@squide/firefly"; const variable = useEnvironmentVariable("apiBaseUrl"); ``` -------------------------------- ### Configure package.json for module export Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-local-module.md Define the 'name', 'version', and 'exports' fields in the local module's package.json. The 'exports' field specifies the entry point for the module, making it discoverable by other applications. ```json { "name": "@getting-started/local-module", "version": "0.0.1", "exports": "./src/register.tsx" } ``` -------------------------------- ### Update Deferred Registrations with Remote Data (React/TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/essentials/register-deferred-nav-items.md This example demonstrates how to use the `useDeferredRegistrations` hook with TanStack Query to automatically update deferred registrations when new remote data is provided. It fetches user information and passes it as a `DeferredRegistrationData` object to the hook. Ensure `@squide/firefly`, `react-router`, and `@sample/shared` are installed. ```tsx import { useIsBootstrapping, useDeferredRegistrations, usePublicDataQueries } from "@squide/firefly"; import { Outlet } from "react-router"; import { DeferredRegistrationData, UserInfo } from "@sample/shared"; import { useMemo } from "react"; function BootstrappingRoute() { const [userInfo] = usePublicDataQueries([ { queryKey: ["/api/user-info"], queryFn: async () => { const response = await fetch("/api/user-info"); const data = await response.json(); const userInfo: UserInfo = { isAdmin: data.isAdmin }; return userInfo; } } ]); // The useMemo hook is super important otherwise the hook will consider that the user info // object changed everytime the hook is rendered. const data: DeferredRegistrationData = useMemo(() => ({ userInfo }), [userInfo]); useDeferredRegistrations(data); if (useIsBootstrapping()) { return <div>Loading...</div>; } return <Outlet />; } ``` -------------------------------- ### Initialize Firefly with local modules Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-local-module.md Register the local module with the host application by calling 'initializeFirefly'. This function takes an array of module registration functions, including the host's own registration and any local modules. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { register as registerMyLocalModule } from "@getting-started/local-module"; import { App } from "./App.tsx"; import { registerHost } from "./register.tsx"; // Register the modules. const runtime = initializeFirefly({ localModules: [registerHost, registerMyLocalModule] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Browserslist Configuration (Plain Text) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Specifies the target browsers for the project using an extends directive to inherit configurations from a shared Workleap browserslist package. ```plaintext extends @workleap/browserslist-config ``` -------------------------------- ### Global Data Fetching with Tanstack Query Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/learn-core-pieces.md Demonstrates how to fetch public and protected global data using Squide's primitives built on Tanstack Query. It handles loading states, conditional fetching based on page type, and displays a unified loading spinner. Dependencies include '@squide/firefly' and '@sample/shared'. ```tsx import { usePublicDataQueries, useProtectedDataQueries, useIsBootstrapping } from "@squide/firefly"; import { Outlet } from "react-router"; import { FetchCountContext, SubscriptionContext, isApiError } from "@sample/shared"; function BootstrappingRoute() { const [fetchCount] = usePublicDataQueries([ { queryKey: ["/api/count"], queryFn: async () => { // ... } } ]); const [subscription] = useProtectedDataQueries([ { queryKey: ["/api/subscription"], queryFn: async () => { // ... } } ], error => isApiError(error) && error.status === 401); if (useIsBootstrapping()) { return <div>Loading...</div>; } return ( <FetchCountContext.Provider value={fetchCount}> <SubscriptionContext.Provider value={subscription}> <Outlet /> </SubscriptionContext.Provider> </FetchCountContext.Provider> ); } ``` -------------------------------- ### Rsbuild Build Configuration (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Defines the Rsbuild configuration for a production build environment using the `defineBuildConfig` function from the `@workleap/rsbuild-configs` library. ```ts import { defineBuildConfig } from "@workleap/rsbuild-configs"; export default defineBuildConfig(); ``` -------------------------------- ### Define Session and SessionManager Interfaces (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/recipes/add-authentication.md Defines the `Session` interface with user details and the `SessionManager` interface with methods for getting and clearing the session. These are shared types used across the application. ```typescript export interface Session { user: { name: string; }; } export interface SessionManager { getSession: () => Session | undefined; clearSession: () => void; } ``` -------------------------------- ### Register i18next Plugin with FireflyRuntime Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-i18next.md Registers the i18nextPlugin with the FireflyRuntime during application bootstrapping. This configuration sets up supported languages, a fallback language, and the querystring parameter for language detection. ```tsx import { createRoot } from "react-dom/client"; import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { i18nextPlugin } from "@squide/i18next"; import { App } from "./App.tsx"; import { registerHost } from "./register.tsx"; const runtime = initializeFirefly({ localModules: [registerHost], plugins: [x => { // In this example: // - The supported languages are "en-US" and "fr-CA" // - The fallback language is "en-US" // - The URL querystring parameter to detect the current language is "language" const i18nextPlugin = new i18nextPlugin(x, ["en-US", "fr-CA"], "en-US", "language"); // Always detect the user language early on. i18nextPlugin.detectUserLanguage(); return i18nextPlugin; }] }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Define peer dependencies in package.json Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-local-module.md Specify the 'peerDependencies' in the local module's package.json. These are dependencies that the module expects to be provided by the host application, ensuring compatibility. ```json { "name": "@getting-started/local-module", "version": "0.0.1", "exports": "./src/register.tsx", "peerDependencies": { "@opentelemetry/api": "^1.2.3", "@squide/firefly": "^1.2.3", "@tanstack/react-query": "^1.2.3", "launchdarkly-js-client-sdk": "^1.2.3", "msw": "^1.2.3", "react": "^1.2.3", "react-dom": "^1.2.3", "react-router": "^1.2.3" } } ``` -------------------------------- ### Embed FireflyDecorator Component in Existing Decorator (TypeScript) Source: https://github.com/workleap/wl-squide/blob/main/docs/integrations/setup-storybook.md Demonstrates embedding the `FireflyDecorator` component within an existing Storybook decorator. This approach allows for more flexible integration of Firefly's capabilities. ```tsx import { initializeFireflyForStorybook, FireflyDecorator } from "@squide/firefly-rsbuild-storybook"; import type { Decorator, Meta, StoryObj } from "storybook-react-rsbuild"; import { Page } from "./Page.tsx"; import { registerModule } from "./registerModule.tsx"; const runtime = await initializeFireflyForStorybook({ localModules: [registerModule] }); const meta = { title: "Page", component: Page, decorators: [ story => ( <FireflyDecorator runtime={runtime}> {story()} </FireflyDecorator> ) ] } satisfies Meta<typeof Page>; export default meta; type Story = StoryObj<typeof meta>; export const Default = {} satisfies Story; ``` -------------------------------- ### Add local module dependency to host Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-local-module.md Include the local module as a dependency in the host application's package.json. This makes the local module available for use within the main application. Use 'workspace:*' in monorepos. ```json { "dependencies": { "@getting-started/local-module": "0.0.1" } } ``` -------------------------------- ### Initialize Firefly Runtime with Honeycomb Tracing (TypeScript/React) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/learn-core-pieces.md Sets up the Firefly runtime with Honeycomb integration for performance tracing using '@workleap/telemetry/react'. This requires the 'react-dom/client' package. The code initializes the telemetry client with Honeycomb configuration and then passes the Honeycomb instrumentation client to the Firefly runtime. ```TypeScript import { FireflyProvider, initializeFirefly } from "@squide/firefly"; import { initializeTelemetry } from "@workleap/telemetry/react"; import { createRoot } from "react-dom/client"; import { App } from "./App.tsx"; const telemetryClient = initializeTelemetry({ honeycomb: { namespace: "sample", serviceName: "squide-sample", apiServiceUrls: [/.+/g,], options: { proxy: "https://my-proxy.com" } } }); const runtime = initializeFirefly({ honeycombInstrumentationClient: telemetryClient.honeycomb }); const root = createRoot(document.getElementById("root")!); root.render( <FireflyProvider runtime={runtime}> <App /> </FireflyProvider> ); ``` -------------------------------- ### Register Root Layout with Routes (TypeScript/TSX) Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Registers the root layout for the application, including placeholders for public and protected routes, and a specific home page route. This uses the Firefly runtime to manage routing. ```tsx import { PublicRoutes, ProtectedRoutes, type ModuleRegisterFunction, type FireflyRuntime } from "@squide/firefly"; import { HomePage } from "./HomePage.tsx"; import { RootLayout } from "./RootLayout.tsx"; export const registerHost: ModuleRegisterFunction<FireflyRuntime> = runtime => { runtime.registerRoute({ // Pathless route to declare a root layout. element: <RootLayout />, children: [ // Placeholders indicating where non hoisted or nested public and protected routes will be rendered. PublicRoutes, ProtectedRoutes ] }, { hoist: true }); runtime.registerRoute({ index: true, element: <HomePage /> }); }; ``` -------------------------------- ### Define AppRouter with Bootstrapping and Registered Routes Source: https://github.com/workleap/wl-squide/blob/main/docs/introduction/create-host.md Sets up the main application router using React Router and the Squide AppRouter. It includes a bootstrapping route to handle loading states and integrates dynamically registered routes from modules. ```tsx import { AppRouter, useIsBootstrapping } from "@squide/firefly"; import { createBrowserRouter, Outlet } from "react-router"; import { RouterProvider } from "react-router/dom"; function BootstrappingRoute() { if (useIsBootstrapping()) { return <div>Loading...</div>; } return <Outlet />; } export function App() { return ( <AppRouter> {({ rootRoute, registeredRoutes, routerProviderProps }) => { return ( <RouterProvider router={createBrowserRouter([ { element: rootRoute, children: [ { element: <BootstrappingRoute />, children: registeredRoutes } ] } ])} {...routerProviderProps} /> ); }} </AppRouter> ); } ```