### Install Node.js and pnpm on Linux Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Installs Node.js version 18.19.x using nvm and pnpm using corepack on Linux systems. Ensure Node.js is active before proceeding with other installations. ```bash # Install Node.js: 18.19.x nvm install 18.19 && nvm use 18.19 # Install pnpm: latest version corepack enable && corepack prepare pnpm@latest --activate ``` -------------------------------- ### Clone SwissJS Repository and Install Dependencies Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Clones the SwissJS repository and installs project dependencies using pnpm. This is a foundational step for setting up the development environment. ```bash # Create and navigate to the work directory mkdir -p ~/work && cd ~/work # Clone the repository git clone https://github.com/ThembaMzumara/SWISS.git cd SWISS # Use the specified Node.js version nvm use # Install workspace dependencies pnpm install ``` -------------------------------- ### Basic Runtime Service Usage Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md Demonstrates the basic usage of the `runtimeService` in TypeScript. It shows how to start the runtime, register a component, load a plugin, and retrieve the current runtime state. This example serves as a starting point for integrating the core runtime functionalities. ```typescript import { runtimeService } from '@swissjs/core' // Start the runtime await runtimeService.start() // Register a component runtimeService.registerComponent('app-counter', CounterComponent) // Load a plugin await runtimeService.loadPlugin(analyticsPlugin) // Get runtime state const state = runtimeService.getState() console.log('Components:', state.components.size) ``` -------------------------------- ### Server Setup Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/core/docs/ssr-system.md Demonstrates how to set up the SwissJS SSR server, defining routes, layouts, and data fetching for server-side rendering. ```APIDOC ## Server Setup ### Description This example shows how to initialize and start the SwissJS SSR server. ### Method `createSwissServer(options: ServerOptions).start()` ### Endpoint N/A (Server initialization) ### Parameters #### Request Body (ServerOptions) - **port** (number) - Required - The port number for the server to listen on. - **routes** (Array) - Required - An array of route configurations. - **layouts** (object) - Required - An object containing layout components. ### Request Example ```typescript import { createSwissServer } from '@swissjs/core/ssr/ssrSystem'; import { HomePage, ProductPage } from './pages'; import { MainLayout } from './layouts'; createSwissServer({ port: 3000, routes: [ { path: '/', component: HomePage, layout: 'MainLayout' }, { path: '/products/:id', component: ProductPage, layout: 'MainLayout', getServerData: async ({ params }) => ({ product: await fetchProduct(params.id) }) } ], layouts: { MainLayout } }).start(); ``` ### Response #### Success Response (200) Server starts listening on the specified port. #### Response Example ``` Server started on port 3000 ``` ``` -------------------------------- ### Example Plugin Implementation Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/plugins.md This example demonstrates how to implement the Plugin interface to create an 'analytics' plugin. It shows how to define plugin metadata and use the install method to register custom directives. ```typescript const analyticsPlugin: Plugin = { name: 'analytics', version: '1.0.0', capabilities: [CAPABILITIES.NETWORK_REQUESTS], install(context: PluginContext) { context.registerDirective('track', this.trackDirective.bind(this)) }, trackDirective(element: Element, binding: DirectiveBinding) { console.log(`Tracking: ${binding.value}`) } } ``` -------------------------------- ### Plugin Runtime Integration Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md Illustrates how to create and integrate a plugin that extends the `runtimeService` in TypeScript. The example defines a plugin named 'runtime-extensions' that intercepts the `start` method to add custom logging before and after the original start procedure is executed. ```typescript // Plugin that extends runtime const runtimePlugin: Plugin = { name: 'runtime-extensions', version: '1.0.0', install(context: PluginContext) { // Extend runtime service const originalStart = runtimeService.start.bind(runtimeService) runtimeService.start = async () => { console.log('Extended runtime starting...') await originalStart() console.log('Extended runtime started!') } } } await runtimeService.loadPlugin(runtimePlugin) ``` -------------------------------- ### Install Node.js and pnpm on macOS Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Installs Node.js version 18.19.x using Homebrew's nvm and pnpm using corepack on macOS. This ensures the correct Node.js version is available for the project. ```bash # Install nvm and Node.js: 18.19.x brew install nvm && nvm install 18.19 && nvm use 18.19 # Install pnpm: latest version corepack enable && corepack prepare pnpm@latest --activate ``` -------------------------------- ### Common SwissJS Monorepo Commands Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md A collection of essential commands for managing the SwissJS monorepo, including dependency installation, building, development server, testing, linting, and documentation generation. ```bash # Install all dependencies pnpm install # Build all packages pnpm build # Start the development server (workspace graph) pnpm dev # Run tests (watch mode) pnpm -w test # Lint all packages pnpm -w lint # Type check all packages pnpm -w type-check # Generate API documentation pnpm docs:api # Build the VitePress site pnpm docs:build # Full project validation and reset pnpm reset ``` -------------------------------- ### Development Server Usage Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md Illustrates how to set up and use the `DevServerService` in TypeScript for a development environment. The example shows configuring the server with options like port, HMR, and file watching, starting the server, and implementing custom logic for handling file changes to trigger hot reloads or full reloads. ```typescript import { DevServerService } from '@swissjs/core' const devServer = new DevServerService({ port: 3000, open: true, hmr: true, watch: ['src/**/*.ts', 'src/**/*.ui'], ignore: ['node_modules/**'] }) // Start development server await devServer.start() // Watch for file changes devServer.watch(['src/**/*']) // Handle hot reload devServer.on('file-change', (filePath) => { if (filePath.endsWith('.ui')) { devServer.hotReload(filePath) } else { devServer.fullReload() } }) ``` -------------------------------- ### Server Runtime Configuration Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md Demonstrates configuring the `RuntimeConfig` for a server-side environment using TypeScript. This example sets server-specific options such as disabling developer tools, enabling telemetry, and setting a warning log level. The configuration is then applied to the `runtimeService` before starting the application. ```typescript // Server-specific runtime configuration const serverConfig: RuntimeConfig = { devtools: false, telemetry: true, logging: 'warn' } runtimeService.setState({ config: serverConfig }) await runtimeService.start() ``` -------------------------------- ### Custom Runtime Service Implementation Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md Provides a TypeScript example of creating a custom implementation of the `RuntimeService` interface. This demonstrates how to extend or replace the default runtime behavior by implementing the required lifecycle and management methods, such as `start` and `stop`, with custom logic. ```typescript class CustomRuntimeService implements RuntimeService { private state: RuntimeState = { started: false, components: new Map(), plugins: new Map(), config: { devtools: false, telemetry: false } } async start(): Promise { console.log('Starting custom runtime...') this.state.started = true // Custom initialization logic } async stop(): Promise { console.log('Stopping custom runtime...') this.state.started = false // Custom cleanup logic } // ... implement other methods } // Use custom runtime const customRuntime = new CustomRuntimeService() await customRuntime.start() ``` -------------------------------- ### Browser Runtime Configuration Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md Shows how to configure the `RuntimeConfig` for a browser environment in TypeScript. This example sets environment-specific options like enabling developer tools based on `NODE_ENV` and configuring telemetry and logging levels, then applies this configuration to the `runtimeService` before starting it. ```typescript // Browser-specific runtime configuration const browserConfig: RuntimeConfig = { devtools: process.env.NODE_ENV === 'development', telemetry: false, logging: 'info' } runtimeService.setState({ config: browserConfig }) await runtimeService.start() ``` -------------------------------- ### TypeScript Example of a Well-Structured Plugin Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/plugins.md Illustrates a well-structured TypeScript plugin following best practices. This example demonstrates how to define a plugin with its name, version, required capabilities, and implement the 'install' method to register directives and services using a provided context. ```typescript const goodPlugin: Plugin = { name: 'my-plugin', version: '1.0.0', capabilities: [CAPABILITIES.MODIFY_DOM], install(context: PluginContext) { // Check required capabilities if (!context.checkCapabilities(this.requiredCapabilities || [])) { throw new Error('Required capabilities not available') } // Register directives context.registerDirective('my-directive', this.handleDirective.bind(this)) // Register services context.registerService('my-service', new MyService()) }, handleDirective(element: Element, binding: DirectiveBinding) { // Directive implementation } } ``` -------------------------------- ### Plugin Lifecycle Methods: Install and Uninstall Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/plugins.md This code demonstrates the asynchronous nature of plugin installation and uninstallation. The `install` method is always called, while `uninstall` is optional and handles cleanup logic. ```typescript // Plugin installation await plugin.install(context) // Plugin cleanup await plugin.uninstall?.(context) ``` -------------------------------- ### Layout Component Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/plugins/file-router/README.md An example of a layout component using SwissJS's template syntax. It includes navigation links and a placeholder for child routes using ``. ```html

© 2025 SwissJS App

``` -------------------------------- ### Manage SwissLibrary API Documentation Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Commands for managing and maintaining API documentation within the SwissLibrary project. It includes commands to generate API docs deterministically and to build and preview them locally. ```bash pnpm docs:api && pnpm docs:api:index ``` ```bash pnpm docs:dev ``` -------------------------------- ### Initialize and Manage SwissFramework Instance Source: https://context7.com/thembamzumara/swisslibrary/llms.txt Demonstrates how to get the singleton instance of the SwissFramework, access its core services like routing and HTTP client, manage hooks and plugins, and start or stop the framework. It is the central point for framework-wide operations. ```typescript import { SwissFramework, SwissApp } from '@swissjs/core'; // Get framework instance const framework = SwissFramework.getInstance(); // Access core services const router = framework.services.router; const httpClient = framework.services.http; const stateManager = framework.services.state; // Start framework framework.start(); // Access internal systems const hookRegistry = framework.hooks; const pluginManager = framework.plugins; const componentRegistry = framework.components; // Stop framework when done framework.stop(); ``` -------------------------------- ### SSR Example Usage (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/core/docs/SSR_Hydration_Documentation.md Demonstrates a basic example of how to initiate the server-side rendering process for a component using the `serverInit` function, which generates the initial HTML to be sent to the client. ```typescript const html = await serverInit.call(MyComponent, props); // html is sent to the client ``` -------------------------------- ### Managing Package Versions with Changesets Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Commands for managing package version bumps and publishing to a registry using Changesets. This is used for releasing new versions of packages within the monorepo. ```bash # Create a changeset for version bumping pnpm changeset # Apply version bumps across packages pnpm release:version # Publish packages to the registry pnpm release:publish ``` -------------------------------- ### Install Swiss Skeleton with PNPM Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/skltn/README.md This command installs the @swissjs/skltn package using the PNPM package manager. It is the primary step to begin using the Swiss Skeleton framework in your project. ```bash pnpm add @swissjs/skltn ``` -------------------------------- ### Utilize onRuntimeReady Hook in TypeScript Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/plugins/examples.md An example of the `onRuntimeReady` lifecycle hook in SwissJS plugins, used for initializing adapters or starting background tasks once the runtime environment is prepared. It includes a check for the 'node' runtime type. ```typescript export const runtimePlugin: Plugin = { name: "runtime-plugin", version: "0.0.1", onRuntimeReady(ctx) { // initialize adapters or start background tasks when runtime is ready if (ctx.runtime?.type === "node") { // Node-specific setup } }, }; ``` -------------------------------- ### Example: Auditing Security Events (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/security.md Illustrates manual and plugin auditing. The first example shows how to manually log an 'ACCESS_USER_DATA' event with its context. The second example demonstrates auditing a plugin, checking its required capabilities and logging any validation failures. This example requires the CAPABILITIES constant and the audit/auditPlugin functions. ```typescript // Manual audit entry audit({ target: 'user-profile', capability: CAPABILITIES.ACCESS_USER_DATA, granted: true, context: { user: 'user123', permissions: new Set([CAPABILITIES.ACCESS_USER_DATA]) } }) // Plugin audit const result = auditPlugin({ name: 'analytics-plugin', version: '1.0.0', requiredCapabilities: [CAPABILITIES.NETWORK_REQUESTS] }) if (!result.valid) { console.error('Plugin validation failed:', result.errors) } ``` -------------------------------- ### Install SwissJS Extension from VSIX (Bash) Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/devtools/vscode_extension/README.md This command demonstrates installing a SwissJS extension from a local .vsix file. After building the package, this command can be used within VSCode/Windsurf to install the extension. ```bash ext install SwissJS.swissjs ``` -------------------------------- ### Initialize and Start SWITE Development Server Source: https://context7.com/thembamzumara/swisslibrary/llms.txt Instantiate and start the SWITE development server using the SwiteServer class. Configurable with options for root directory, public directory, port, host, and automatic browser opening. ```typescript import { SwiteServer } from '@swissjs/swite'; // Create server const server = new SwiteServer({ root: process.cwd(), publicDir: 'public', port: 3000, host: 'localhost', open: true }); // Start server await server.start(); // Server running at http://localhost:3000 // Server features: // - Compiles .ui/.uix files on-demand // - Transpiles TypeScript automatically // - Resolves bare imports from node_modules // - Injects HMR client // - Serves static files from public/ // - SPA fallback to index.html ``` -------------------------------- ### Install @swissjs/css Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/css/README.md Installs the @swissjs/css package using pnpm. This is the initial step to integrate CSS and asset handling into your Swiss framework project. ```bash pnpm add @swissjs/css ``` -------------------------------- ### Plugin Security with Capabilities (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/security.md Illustrates how to define a secure plugin by specifying its capabilities and required capabilities. Includes logic to verify that required capabilities are met before installation and an audit log for the installation process. ```typescript const securePlugin: Plugin = { name: 'secure-plugin', version: '1.0.0', capabilities: [CAPABILITIES.NETWORK_REQUESTS], requiredCapabilities: [CAPABILITIES.MODIFY_DOM], async install(context: PluginContext) { // Verify required capabilities if (!checkCapabilities(context.component, this.requiredCapabilities)) { throw new Error('Required capabilities not available') } // Audit plugin installation auditPlugin(this) } } ``` -------------------------------- ### Install @swissjs/plugin-file-router Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/plugins/file-router/README.md Installs the file-based routing plugin for SwissJS using npm. This is the primary step to integrate the plugin into your project. ```bash npm install @swissjs/plugin-file-router ``` -------------------------------- ### Service Registration Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/development/plugins.md Demonstrates how to register a service within a plugin using the preferred method in `onRegisterServices`. It shows both the context-based and static PluginManager approaches. ```javascript // Using context.app.registerService context.app?.registerService('myService', myServiceInstance); // Using PluginManager.registerService PluginManager.registerService('anotherService', anotherServiceInstance); ``` -------------------------------- ### Example Tooltip Directive Implementation Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/plugins.md This example shows a 'tooltip' directive implementation using the DirectiveLifecycle interface. The 'mounted' hook creates and appends a tooltip element, and returns a cleanup function to remove it. ```typescript const tooltipDirective: DirectiveLifecycle = { mounted(element: Element, binding: DirectiveBinding) { const tooltip = document.createElement('div') tooltip.className = 'tooltip' tooltip.textContent = String(binding.value) document.body.appendChild(tooltip) return () => { tooltip.remove() } } } ``` -------------------------------- ### Example: Custom Security Gateway (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/security.md Demonstrates how to implement and set a custom SecurityGateway. The 'customGateway' evaluates permissions based on a user's permission set, logs audit entries, and includes placeholder logic for rate limiting and plugin validation. This example requires the SecurityGateway interface and SecurityContext. ```typescript // Custom security gateway const customGateway: SecurityGateway = { evaluate(target: string, context: SecurityContext): boolean { // Custom evaluation logic return context.permissions?.has(target) ?? false }, audit(entry: CapabilityAuditLog): void { console.log('Security audit:', entry) }, checkRateLimit(target: string, context: SecurityContext): boolean { // Rate limiting logic return true }, validatePlugin(plugin: Plugin): ValidationResult { return { valid: true, errors: [] } } } setSecurityGateway(customGateway) ``` -------------------------------- ### Install Dependencies for SwissJS VSCode Extension (Bash) Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/devtools/vscode_extension/README.md This command installs all the necessary project dependencies for developing the SwissJS VSCode extension. It uses pnpm as the package manager. ```bash pnpm install ``` -------------------------------- ### Plugin Registration and Lifecycle Hooks Example (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/plugins/lifecycle-and-registry.md Demonstrates how to register a plugin with the PluginManager and utilize the new lifecycle hooks like onRegisterServices, onCapabilityAudit, and onRuntimeReady. This example also shows how to set the experimental feature flag and register a service. ```ts import { PluginManager } from "@swissjs/core/plugins/pluginManager"; const pm = new PluginManager(); process.env.SWISS_EXPERIMENTAL_PLUGIN_LIFECYCLE = "1"; pm.register({ name: "example", version: "0.0.1", onRegisterServices(ctx) { pm.registerService("router", { navigate: (p: string) => { /* ... */ }, }); }, onCapabilityAudit(audit) { if (!audit.ok) console.warn("Capability issues:", audit.summary); }, onRuntimeReady(ctx) { // runtime is ready }, }); const audit = pm.getAudit(); ``` -------------------------------- ### SwissComponent Base Class and Counter Example (TypeScript) Source: https://context7.com/thembamzumara/swisslibrary/llms.txt Demonstrates the SwissComponent base class for creating reusable UI components. It covers lifecycle management (initialize, onMount, onUpdate, onDestroy), state management using `reactive`, dependency injection via `fenestrate`, and rendering virtual DOM. The Counter example shows how to implement these features. ```typescript import { SwissComponent, createElement, reactive, watch } from '@swissjs/core'; class Counter extends SwissComponent { // Declare required capabilities static requires = ['storage:local']; // Reactive state state = reactive({ count: 0, history: [] }); // Lifecycle: initialization initialize() { super.initialize(); // Watch state changes watch(this.state, 'count', (newVal, oldVal) => { this.state.history.push({ from: oldVal, to: newVal, timestamp: Date.now() }); }); // Load persisted count this.loadCount(); } // Lifecycle: mounted to DOM @onMount() handleMount() { console.log('Counter mounted'); } // Lifecycle: component updates @onUpdate() handleUpdate() { this.saveCount(); } // Lifecycle: before unmount @onDestroy() handleDestroy() { console.log('Counter destroyed'); } // Capability usage (fenestration) async loadCount() { const storage = await this.fenestrateAsync('storage:local'); if (storage) { const saved = await storage.getItem('count'); if (saved !== null) { this.state.count = parseInt(saved, 10); } } } async saveCount() { const storage = this.fenestrate('storage:local'); storage?.setItem('count', this.state.count.toString()); } // Event handlers increment() { this.state.count++; } decrement() { this.state.count--; } reset() { this.state.count = 0; } // Render virtual DOM render() { return createElement('div', { class: 'counter' }, createElement('h1', {}, `Count: ${this.state.count}`), createElement('div', { class: 'buttons' }, createElement('button', { onClick: () => this.decrement() }, '-'), createElement('button', { onClick: () => this.reset() }, 'Reset'), createElement('button', { onClick: () => this.increment() }, '+') ), createElement('div', { class: 'history' }, createElement('h3', {}, 'History'), createElement('ul', {}, ...this.state.history.map(h => createElement('li', {}, `${h.from} → ${h.to}`) ) ) ) ); } } // Mount component const counter = new Counter({}); counter.mount(document.getElementById('app')); ``` -------------------------------- ### Component Definition Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/core/docs/ssr-system.md Illustrates how to define a SwissJS component for server-side rendering, including data fetching and lifecycle methods. ```APIDOC ## Component Definition ### Description Defines a component for use with SwissJS SSR, including static methods for data fetching and rendering logic. ### Method `class ComponentName extends Component` ### Endpoint N/A (Component definition) ### Parameters #### Static Methods - **`static async getServerData(context)`** - Async data fetching hook. - **`render()`** - Synchronous method returning the component's HTML. - **`hydrate(element)`** - Client-side hydration logic. - **`clientDidMount()`** - Client lifecycle hook. ### Request Example ```typescript import { Component } from '@swissjs/core'; export class ProductPage extends Component { static async getServerData({ params }) { return { product: await db.products.find(params.id) }; } render() { const { product } = this.props; return `

${product.name}

${product.description}

`; } hydrate(element) { // Client-side interactivity } clientDidMount() { // Client lifecycle } } ``` ### Response #### Success Response (200) Component renders to HTML string on the server and hydrates on the client. #### Response Example ```html

Example Product

This is a description.

``` ``` -------------------------------- ### Simple Route Definition Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/plugins/file-router/README.md Defines a basic route component and its metadata. This example shows a static route for the 'About Us' page with associated title and description. ```javascript // src/routes/about.ui export default { component: "AboutPage", meta: { title: "About Us", description: "Learn more about our company", }, }; ``` -------------------------------- ### Component Security with Capabilities (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/security.md Demonstrates how to secure a component using decorators to declare provided and required capabilities. Includes an example of explicitly checking capabilities before performing sensitive actions. ```typescript @component({ selector: 'secure-component', capabilities: [CAPABILITIES.ACCESS_USER_DATA] // Component provides }) @requires([CAPABILITIES.MODIFY_DOM]) // Component requires class SecureComponent extends SwissComponent { userData = null @capability(CAPABILITIES.ACCESS_USER_DATA) async loadUserData() { // Explicit capability check if (checkCapabilities(this, [CAPABILITIES.ACCESS_USER_DATA])) { this.userData = await fetchUserData() } } @onClick('save-button') saveData() { // This directive requires MODIFY_DOM capability this.saveUserData() } } ``` -------------------------------- ### Usage Examples Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/devtools.md Illustrates practical usage scenarios for the Devtools API, including implementing a custom bridge, collecting telemetry, subscribing to graph updates, and enabling devtools. ```APIDOC ## Usage Examples ### Custom Bridge Implementation Demonstrates how to create and set a custom `DevtoolsBridge`. ```typescript const customBridge: DevtoolsBridge = { componentMounted(payload: ComponentNodePayload) { console.log('Component mounted:', payload) // Send to external devtools sendToDevtools('component:mounted', payload) }, componentUpdated(payload: ComponentUpdatePayload) { console.log('Component updated:', payload) sendToDevtools('component:updated', payload) }, // ... implement other methods } setDevtoolsBridge(customBridge) ``` ### Telemetry Collection Shows how to enable telemetry and send custom telemetry events. ```typescript // Enable telemetry globalThis.SWISS_TELEMETRY = true // Custom telemetry events const bridge = getDevtoolsBridge() bridge.telemetry({ category: 'perf', name: 'component-render', timestamp: Date.now(), data: { duration: 5.2 }, componentId: 'comp-123' }) ``` ### Graph Subscription Illustrates how to subscribe to changes in the component graph and unsubscribe. ```typescript const bridge = getDevtoolsBridge() // Subscribe to graph changes const unsubscribe = bridge.subscribeToGraph((snapshot) => { console.log('Graph updated:', snapshot.components.length, 'components') }) // Later unsubscribe unsubscribe() ``` ### Enable Devtools Provides different methods to enable devtools in the application. ```typescript // Via environment variable process.env.SWISS_DEVTOOLS = '1' // Via global flag globalThis.SWISS_DEVTOOLS = true // Via configuration const app = new SwissFramework({ devtools: true }) ``` ``` -------------------------------- ### TypeScript Example of a Plugin with Robust Error Handling Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/plugins.md Demonstrates a robust TypeScript plugin implementation with comprehensive error handling for both installation and uninstallation processes. It utilizes try-catch blocks to gracefully manage potential errors during service setup, directive registration, and cleanup, logging errors to the console. ```typescript const robustPlugin: Plugin = { name: 'robust-plugin', version: '1.0.0', async install(context: PluginContext) { try { await this.setupServices(context) await this.registerDirectives(context) } catch (error) { console.error(`Plugin ${this.name} installation failed:`, error) throw error } }, async uninstall(context: PluginContext) { try { await this.cleanupServices(context) await this.unregisterDirectives(context) } catch (error) { console.error(`Plugin ${this.name} uninstallation failed:`, error) } } } ``` -------------------------------- ### Daily SwissJS Development Workflow Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Outlines the standard daily development workflow for SwissJS, including syncing branches, running the development server, coding, linting, testing, committing, and pushing code. ```bash # Sync with the develop branch git checkout develop git pull origin develop # Start a new feature branch git checkout -b feature/ # Install dependencies and start dev server nvm use pnpm install pnpm dev # Lint, type check, and test pnpm -w lint pnpm -w type-check pnpm -w test # Commit and push changes git commit -am "[TICKET] concise summary" git push -u origin feature/" ``` -------------------------------- ### Setting Up the SwissJS Server Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/core/docs/ssr-system.md Demonstrates how to create and start a SwissJS server with defined routes and layouts. It configures the server to listen on a specific port and sets up initial routes, including those with server-side data fetching. Dependencies include core SwissJS modules and page/layout components. ```typescript import { createSwissServer } from '@swissjs/core/ssr/ssrSystem'; import { HomePage, ProductPage } from './pages'; import { MainLayout } from './layouts'; createSwissServer({ port: 3000, routes: [ { path: '/', component: HomePage, layout: 'MainLayout' }, { path: '/products/:id', component: ProductPage, layout: 'MainLayout', getServerData: async ({ params }) => ({ product: await fetchProduct(params.id) }) } ], layouts: { MainLayout } }).start(); ``` -------------------------------- ### Start POS Application Development Server Source: https://github.com/thembamzumara/swisslibrary/blob/main/BUILD_GUIDE.md Starts the SWITE development server for the POS application. SWITE provides Hot Module Replacement (HMR), on-the-fly TypeScript compilation, JSX transformation, and module resolution for workspace packages, serving files at http://localhost:3000. ```bash cd c:/Users/themb/Documents/dev/SWS/SwissEnterpriseRepo/apps/pos node c:/Users/themb/Documents/dev/SWS/SWISS/packages/cli/dist/main.js dev ``` -------------------------------- ### Run Local CI Policy and Format Checks Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Executes local checks for project policies, barrels, and UI formatting. These commands are used to ensure code quality and consistency before committing or pushing changes, mirroring CI checks. ```bash pnpm -w check:barrels && pnpm check:policy && pnpm -w check:ui-format ``` -------------------------------- ### Registering Plugin Lifecycle Hooks (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/hooks.md Example for registering a hook that listens to plugin lifecycle events, such as installation or activation. This enables framework-level management and monitoring of plugins. ```typescript // Plugin lifecycle hook registry.register('plugin', 'lifecycle', async (context: PluginLifecycleContext) => { console.log('Plugin', context.plugin.name, context.phase) // Track plugin lifecycle }) ``` -------------------------------- ### Install @swissjs/router Package Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/router/README.md This snippet shows how to install the @swissjs/router package using the pnpm package manager. Ensure you have pnpm installed and configured in your project. ```bash pnpm add @swissjs/router ``` -------------------------------- ### Configure and Manage SwissApp Instance Source: https://context7.com/thembamzumara/swisslibrary/llms.txt Shows how to create and manage application instances using SwissApp. This includes registering plugins, accessing application-specific services, and starting or stopping the application. Supports multiple app instances within a single framework. ```typescript import { SwissApp } from '@swissjs/core'; import { fileRouterPlugin } from '@swissjs/plugins/file-router'; // Create named app instance const app = SwissApp.getInstance('my-app'); // Register plugins app.registerPlugins([ fileRouterPlugin({ routesDir: './src/routes' }) ]); // Access app services const routerService = app.services.router; // Start application app.start(); // Cleanup app.stop(); ``` -------------------------------- ### Configure Git Autocrlf on Windows Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Sets the Git configuration `core.autocrlf` to `input` globally on Windows. This helps manage line endings (CRLF vs LF) consistently across different operating systems, recommending LF for the repository. ```bash git config --global core.autocrlf input ``` -------------------------------- ### Plugin Development Example in TypeScript Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/README.md Shows a basic implementation of a 'database' plugin in TypeScript. It defines the plugin's name and capabilities, and implements the `initialize` method to register a 'DatabaseService' with the provided PluginContext. ```typescript import { Plugin, PluginContext } from 'swisslibrary'; class DatabaseService {} class DatabasePlugin implements Plugin { name = "database"; capabilities = ["database"]; initialize(context: PluginContext) { context.registerService("DatabaseService", new DatabaseService()); } } ``` -------------------------------- ### Example Hook Integration in a Plugin Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/plugins.md This example shows a plugin named 'lifecycle-hooks' that registers a callback for the 'component:mount' hook. The callback logs the name of the mounted component to the console. ```typescript const lifecyclePlugin: Plugin = { name: 'lifecycle-hooks', version: '1.0.0', install(context: PluginContext) { context.registerHook({ name: 'component:mount', phase: 'mount', callback: (component) => { console.log('Component mounted:', component.constructor.name) } }) } } ``` -------------------------------- ### Runtime Initialization (Conceptual) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/README.md Describes the sequence of events during application startup, including plugin registry initialization, service registration, component instantiation, capability validation, service injection, and the commencement of VDOM rendering. ```text Application starts ↓ Plugin Registry initializes ↓ Plugins register services ↓ Components instantiate ↓ Capability validation occurs ↓ Service injection happens ↓ VDOM rendering begins ``` -------------------------------- ### Graph Subscription Example - TypeScript Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/devtools.md Shows how to subscribe to changes in the component graph using the `subscribeToGraph` method. This example logs the number of components whenever the graph is updated and demonstrates how to unsubscribe. ```typescript const bridge = getDevtoolsBridge() // Subscribe to graph changes const unsubscribe = bridge.subscribeToGraph((snapshot) => { console.log('Graph updated:', snapshot.components.length, 'components') }) // Later unsubscribe unsubscribe() ``` -------------------------------- ### Quick Start: Register File Router Plugin in SwissJS Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/plugins/file-router/README.md Demonstrates how to initialize the SwissJS framework and register the file router plugin. It shows the basic configuration for routes directory, file extensions, layouts, and hot reloading. ```typescript import { SwissFramework } from "@swissjs/core"; import { fileRouterPlugin } from "@swissjs/plugin-file-router"; // Create framework instance const framework = SwissFramework.getInstance(); // Register the file router plugin framework.plugins.register( fileRouterPlugin({ routesDir: "./src/routes", extensions: [".ui", ".js"], layouts: true, lazyLoading: true, dev: { hotReload: true, }, }), ); // Initialize the app framework.initialize(); ``` -------------------------------- ### Router: Route Creation, Navigation, and Guards Source: https://context7.com/thembamzumara/swisslibrary/llms.txt Illustrates the creation and usage of the router for defining routes, handling navigation, and implementing navigation guards. It shows how to define routes with components and loaders, perform programmatic navigation, add routes dynamically, match routes, and control navigation flow based on conditions. ```typescript import { createRouter, type Route } from '@swissjs/router'; import Home from './pages/Home.ui'; import About from './pages/About.ui'; import UserProfile from './pages/UserProfile.ui'; import NotFound from './pages/NotFound.ui'; // Define routes const routes: Route[] = [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/users/:id', component: UserProfile, loader: async ({ params }) => { const response = await fetch(`/api/users/${params.id}`); if (!response.ok) throw new Error('User not found'); return response.json(); }, action: async ({ request, params }) => { if (request.method === 'POST') { const formData = await request.formData(); // Handle form submission return { success: true }; } } }, { path: '*', component: NotFound } ]; // Create router const router = createRouter({ routes, mode: 'history', // or 'hash' base: '/app' }); // Navigation router.push('/about'); router.replace('/users/123'); // Navigation with state router.push('/profile', { state: { from: 'dashboard' } }); // Programmatic route addition router.addRoute('/settings', SettingsComponent); // Route matching const match = router.match('/users/456'); if (match) { console.log('Matched route:', match); } // Navigation guards router.beforeEach(async (to, from) => { // Check authentication if (to.path.startsWith('/admin') && !isAuthenticated()) { return '/login'; } // Analytics console.log(`Navigating from ${from?.path} to ${to.path}`); // Allow navigation return true; }); // Load route data const data = await router.loadRouteData('/users/789'); console.log('Route data:', data); ``` -------------------------------- ### Runtime Performance Monitoring with TypeScript Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/runtime.md This snippet demonstrates how to use the `runtimeService` to monitor application startup performance. It utilizes `console.time` and `console.timeEnd` to measure the duration of the runtime initialization process and logs component registration events. ```typescript // Runtime performance hooks runtimeservice.on('start', () => { console.time('runtime-start') }) runtimeservice.on('started', () => { console.timeEnd('runtime-start') }) // Component performance runtimeservice.on('component-register', (name) => { console.log(`Component registered: ${name}`) }) ``` -------------------------------- ### Custom Bridge Implementation Example - TypeScript Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/devtools.md Demonstrates how to create and set a custom DevtoolsBridge implementation. This example shows logging component events and sending them to an external devtools service using `setDevtoolsBridge`. ```typescript const customBridge: DevtoolsBridge = { componentMounted(payload: ComponentNodePayload) { console.log('Component mounted:', payload) // Send to external devtools sendToDevtools('component:mounted', payload) }, componentUpdated(payload: ComponentUpdatePayload) { console.log('Component updated:', payload) sendToDevtools('component:updated', payload) }, // ... implement other methods } setDevtoolsBridge(customBridge) ``` -------------------------------- ### Resolve Node Version Mismatch Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Ensures the correct Node.js version is used for the project by leveraging the Node Version Manager (nvm). The command uses the `.nvmrc` file in the repository to set the active Node.js version. ```bash nvm use ``` -------------------------------- ### Configure Git for Long Paths on Windows Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/DEVELOPER_QUICKSTART.md Sets the Git configuration `core.longpaths` to `true` globally on Windows. This is crucial for handling long file paths that might cause issues on NTFS file systems. ```bash git config --global core.longpaths true ``` -------------------------------- ### Telemetry Collection Example - TypeScript Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/devtools.md Illustrates how to enable and use the telemetry feature within the Devtools API. This example shows setting a global flag for telemetry and sending custom performance events via the `telemetry` method. ```typescript // Enable telemetry globalThis.SWISS_TELEMETRY = true // Custom telemetry events const bridge = getDevtoolsBridge() bridge.telemetry({ category: 'perf', name: 'component-render', timestamp: Date.now(), data: { duration: 5.2 }, componentId: 'comp-123' }) ``` -------------------------------- ### Example: Component with Required Capabilities (TypeScript) Source: https://github.com/thembamzumara/swisslibrary/blob/main/docs/api/core/security.md Demonstrates how to use the '@requires' decorator to enforce specific capabilities for a SwissComponent. The 'loadUserData' method will only execute if the component possesses the ACCESS_USER_DATA capability. This example requires the SwissComponent base class and the CAPABILITIES constant. ```typescript @requires([CAPABILITIES.ACCESS_USER_DATA]) class UserProfile extends SwissComponent { userData = null @onMount() loadUserData() { // This will only execute if component has required capabilities this.userData = fetchUserData() } } ``` -------------------------------- ### Basic Signal and Effect Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/core/docs/observable-signals.md A simple example demonstrating the core functionality of signals and effects. A signal `count` is initialized, and an effect logs its value. When `count.value` is updated, the effect automatically re-runs, logging the new value. ```typescript const count = signal(0); effect(() => { console.log('Count:', count.value); }); count.value = 1; // Logs: Count: 1 ``` -------------------------------- ### Launch SwissJS Extension Development Host (Bash) Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/devtools/vscode_extension/README.md This command initiates the debugging process for the SwissJS VSCode extension. Pressing F5 in VSCode/Windsurf will launch a new extension development host window where breakpoints can be set and code behavior tested. ```bash F5 ``` -------------------------------- ### Computed Signal Usage Example Source: https://github.com/thembamzumara/swisslibrary/blob/main/packages/core/docs/observable-signals.md This example showcases the use of a computed signal. A `count` signal is defined, and a `double` computed signal derives its value by multiplying `count.value` by 2. An effect logs the value of `double`, which updates automatically when `count` changes. ```typescript const count = signal(2); const double = computed(() => count.value * 2); effect(() => { console.log('Double:', double.value); }); count.value = 3; // Logs: Double: 6 ``` -------------------------------- ### Generate Project Components and Pages with Swiss CLI Source: https://context7.com/thembamzumara/swisslibrary/llms.txt Commands to generate project elements like components, pages, and custom templates using the Swiss CLI. Supports interactive mode for guided generation. ```bash swiss forge swiss forge component Button swiss forge component Button --interactive swiss forge page HomePage swiss forge template MyTemplate ```