### Query Tinybird Datasource Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Example of how to run SQL queries directly against a Tinybird datasource using the Tinybird CLI. ```bash pnpm exec tb datasource query events "SELECT count() FROM events WHERE organization_id = 'org_123'" ``` -------------------------------- ### Start EmitKit Development Server Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Starts the SvelteKit development server, allowing you to view and interact with your EmitKit application locally. The application will be accessible at http://localhost:5173. ```bash pnpm run dev ``` -------------------------------- ### Tinybird CLI - Version Check Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Verifies the installation of the Tinybird CLI tool. ```APIDOC ## Verify CLI Installation This command checks if the Tinybird CLI is installed correctly as a project dependency. ### Method ```bash POST ``` ### Endpoint ``` pnpm exec tb --version ``` ### Parameters None ### Request Example ```bash pnpm exec tb --version ``` ### Response #### Success Response (200) - **version** (string) - The installed version of the Tinybird CLI. #### Response Example ```json { "version": "1.2.3" } ``` ``` -------------------------------- ### Start PostgreSQL with Docker Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Starts a PostgreSQL database container using Docker. This is the recommended method for local development and makes PostgreSQL available on port 5433. ```bash pnpm run docker:up ``` -------------------------------- ### Essential EmitKit Development Commands Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md A collection of useful commands for developing with EmitKit. Includes starting the development server, opening the database GUI, performing type checking, generating database migrations, and querying Tinybird data. Assumes pnpm is the package manager. ```bash # Start development server pnpm run dev # Open database GUI pnpm run db:studio # Type checking pnpm run check # Generate database migrations pnpm run db:generate # View Tinybird data cd tinybird pnpm exec tb datasource query events "SELECT * FROM events LIMIT 10" ``` -------------------------------- ### Copy Environment Configuration Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Copies the example environment file (.env.example) to a new file (.env). This new file will be used to store your project's configuration settings. ```bash cp .env.example .env ``` -------------------------------- ### Tinybird CLI - List Data Sources Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Lists all data sources currently deployed in your Tinybird workspace. ```APIDOC ## List Tinybird Data Sources This command retrieves and displays a list of all data sources that have been deployed to your Tinybird workspace. ### Method ```bash GET ``` ### Endpoint ```bash pnpm exec tb datasource ls ``` ### Parameters None ### Request Example ```bash pnpm exec tb datasource ls ``` ### Response #### Success Response (200) - **datasources** (array) - A list of objects, each describing a deployed data source. - **name** (string) - The name of the data source. - **type** (string) - The type of the data source (e.g., `events`). - **last_update** (string) - Timestamp of the last update. #### Response Example ```json { "datasources": [ { "name": "events", "type": "events", "last_update": "2024-07-28T10:00:00Z" } ] } ``` ``` -------------------------------- ### Clone EmitKit Repository Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Clones the EmitKit repository from GitHub to your local machine using Git. This is the first step to get the project's source code. ```bash git clone https://github.com/yourusername/blip-sk.git cd blip-sk ``` -------------------------------- ### Verify Tinybird CLI Installation Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Checks if the Tinybird CLI is installed and accessible. This command requires Node.js and pnpm to be installed as it uses 'pnpm exec' to run the CLI tool. ```bash pnpm exec tb --version ``` -------------------------------- ### Tinybird CLI - List Pipes Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Lists all pipes (API endpoints) currently deployed in your Tinybird workspace. ```APIDOC ## List Tinybird Pipes This command retrieves and displays a list of all pipes (which function as API endpoints) deployed to your Tinybird workspace. ### Method ```bash GET ``` ### Endpoint ```bash pnpm exec tb pipe ls ``` ### Parameters None ### Request Example ```bash pnpm exec tb pipe ls ``` ### Response #### Success Response (200) - **pipes** (array) - A list of objects, each describing a deployed pipe. - **name** (string) - The name of the pipe. - **last_update** (string) - Timestamp of the last update. #### Response Example ```json { "pipes": [ { "name": "stream_events", "last_update": "2024-07-28T10:05:00Z" }, { "name": "get_events_paginated", "last_update": "2024-07-28T10:05:00Z" }, { "name": "get_events_stats", "last_update": "2024-07-28T10:05:00Z" } ] } ``` ``` -------------------------------- ### Tinybird CLI - Deploy Resources Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Deploys all data sources and pipes defined in the Tinybird configuration to your Tinybird workspace. ```APIDOC ## Deploy All Tinybird Resources This command deploys all data sources and pipes from the local `tinybird/` directory to your Tinybird workspace. It's used after making changes to your data source definitions or pipe logic. ### Method ```bash POST ``` ### Endpoint ```bash cd tinybird pnpm exec tb deploy ``` ### Parameters None ### Request Example ```bash cd tinybird pnpm exec tb deploy ``` ### Response #### Success Response (200) - **deployed_resources** (array) - A list of resources (datasources, pipes) that were successfully deployed. - **message** (string) - A confirmation message. #### Response Example ```json { "deployed_resources": [ "datasources/events.datasource", "pipes/stream_events.pipe", "pipes/get_events_paginated.pipe", "pipes/get_events_stats.pipe", "pipes/events_hourly_mv.pipe", "pipes/events_daily_mv.pipe" ], "message": "All resources deployed successfully." } ``` ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Installs all necessary project dependencies, including SvelteKit, Drizzle ORM, Better Auth, shadcn-svelte, and the Tinybird CLI, using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Example TypeScript Event Retention Logic Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Illustrates how event retention policies work in Tinybird based on an organization's subscription tier. It shows how events created under different tiers are handled over time. ```typescript // Event created on Basic plan (90-day retention) Event A created on Day 0 // Organization upgrades to Premium on Day 60 Event B created on Day 61 (365-day retention) // Query on Day 150: // - Event A: Not visible (created 150 days ago, basic tier = 90 days) // - Event B: Visible (created 89 days ago, premium tier = 365 days) ``` -------------------------------- ### Start Development Servers Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Commands to start the SvelteKit development server and the Drizzle Studio for database management. ```bash pnpm run dev # Start SvelteKit dev server pnpm run db:studio # Open Drizzle Studio ``` -------------------------------- ### Tinybird CLI - Deploy Specific Resource Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Deploys a single data source or pipe to your Tinybird workspace. ```APIDOC ## Deploy Specific Tinybird Resource This command allows for targeted deployment of either a single data source definition or a specific pipe to your Tinybird workspace. This is efficient for updating individual components without redeploying everything. ### Method ```bash POST ``` ### Endpoint ```bash pnpm exec tb deploy [path_to_resource] ``` ### Parameters - **path_to_resource** (string) - Required - The file path to the specific data source or pipe definition to deploy (e.g., `datasources/events.datasource` or `pipes/stream_events.pipe`). ### Request Example Deploying a data source: ```bash pnpm exec tb deploy datasources/events.datasource ``` Deploying a pipe: ```bash pnpm exec tb deploy pipes/stream_events.pipe ``` ### Response #### Success Response (200) - **deployed_resource** (string) - The path of the resource that was successfully deployed. - **message** (string) - A confirmation message. #### Response Example ```json { "deployed_resource": "datasources/events.datasource", "message": "Resource deployed successfully." } ``` ``` -------------------------------- ### Open Drizzle Studio Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Launches Drizzle Studio, a GUI tool for inspecting and managing your database. This is useful for verifying that the database schema has been applied correctly. ```bash pnpm run db:studio ``` -------------------------------- ### Environment File Template (.env.example) Source: https://github.com/emitkithq/emitkit/blob/main/docs/configuration.md This snippet provides a template for the .env file, detailing required environment variables for application configuration, database connection, authentication, AI integration, web push notifications, and analytics. It includes example values and generation commands for sensitive keys. ```bash # ============================================================================= # Environment Configuration # ============================================================================= # ----------------------------------------------------------------------------- # Application URLs # ----------------------------------------------------------------------------- VERCEL_URL=http://localhost:5173 # ----------------------------------------------------------------------------- # Database (Neon PostgreSQL) # ----------------------------------------------------------------------------- DATABASE_URL="postgres://root:mysecretpassword@localhost:5433/local" # ----------------------------------------------------------------------------- # Redis (Upstash - Required for SSE pub/sub in production) # ----------------------------------------------------------------------------- UPSTASH_REDIS_REST_URL="https://your-region.upstash.io" UPSTASH_REDIS_REST_TOKEN="your-token-here" # ----------------------------------------------------------------------------- # Authentication (Better Auth) # ----------------------------------------------------------------------------- # Generate: openssl rand -base64 32 # BETTER_AUTH_SECRET="your-secret-here" # BETTER_AUTH_URL="${VERCEL_URL}" # ----------------------------------------------------------------------------- # AI / LLM Integration # ----------------------------------------------------------------------------- OPENAI_API_KEY="your-openai-api-key-here" # ----------------------------------------------------------------------------- # Web Push Notifications (VAPID Keys) # ----------------------------------------------------------------------------- # Generate: pnpm dlx web-push generate-vapid-keys # PUBLIC_VAPID_KEY="YOUR_PUBLIC_VAPID_KEY" # VAPID_KEY="YOUR_VAPID_KEY" # VAPID_SUBJECT="mailto:your-email@example.com" # ----------------------------------------------------------------------------- # Tinybird (Events & Analytics) # ----------------------------------------------------------------------------- TINYBIRD_TOKEN="your-tinybird-token-here" TINYBIRD_API_URL="https://api.tinybird.co" # ----------------------------------------------------------------------------- # Optional: Analytics & Monitoring # ----------------------------------------------------------------------------- # SENTRY_DSN="your-sentry-dsn" ``` -------------------------------- ### Tinybird CLI - Authentication Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Logs in to your Tinybird account, storing credentials locally. ```APIDOC ## Authenticate with Tinybird This command initiates the authentication process with Tinybird, typically opening a browser window for login and saving credentials to a local file. ### Method ```bash POST ``` ### Endpoint ``` pnpm exec tb login ``` ### Parameters None ### Request Example ```bash pnpm exec tb login ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful authentication. - **credentials_stored** (boolean) - Confirms that credentials have been saved locally (usually in `.tinyb`). #### Response Example ```json { "status": "success", "credentials_stored": true } ``` ``` -------------------------------- ### Tinybird Pipe - Stats Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Monitors the real-time statistics and performance of a specific pipe. ```APIDOC ## Monitor Tinybird Pipe Statistics This command provides insights into the real-time performance and usage statistics of a specific pipe, such as request rates and latency. ### Method ```bash GET ``` ### Endpoint ```bash pnpm exec tb pipe stats [pipe_name] ``` ### Parameters - **pipe_name** (string) - Required - The name of the pipe for which to view statistics. ### Request Example ```bash pnpm exec tb pipe stats stream_events ``` ### Response #### Success Response (200) - **stats** (object) - An object containing various performance metrics for the pipe. - **requests_per_second** (number) - Average requests per second. - **latency_ms** (number) - Average request latency in milliseconds. - **errors_per_second** (number) - Average errors per second. - **(other relevant metrics)** #### Response Example ```json { "stats": { "requests_per_second": 15.5, "latency_ms": 250, "errors_per_second": 0.1 } } ``` ``` -------------------------------- ### Tinybird Pipe - Test Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Tests a specific pipe locally by providing required parameters. ```APIDOC ## Test Tinybird Pipe Locally This command allows you to test the functionality of a specific pipe by sending it test data with specified parameters. This is useful for debugging pipe logic before deploying. ### Method ```bash POST ``` ### Endpoint ```bash pnpm exec tb pipe test [pipe_name] ``` ### Parameters - **pipe_name** (string) - Required - The name of the pipe to test. - **--param** (string) - Multiple - Key-value pairs for parameters to pass to the pipe (e.g., `organization_id=org_123`). ### Request Example ```bash pnpm exec tb pipe test stream_events \ --param organization_id=org_123 \ --param channel_id=ch_456 \ --param since="2024-01-01 00:00:00" ``` ### Response #### Success Response (200) - **result** (any) - The output returned by the pipe for the given test parameters. The structure depends on the pipe's logic. #### Response Example ```json { "result": [ { "event_id": "evt_abc", "timestamp": "2024-07-28T12:00:00Z", "data": { ... } } ] } ``` ``` -------------------------------- ### Deploy All Tinybird Resources Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Deploys all data sources and pipes defined in the 'tinybird' directory to the Tinybird service. This command assumes you are in the 'tinybird' directory or have configured paths correctly. ```bash cd tinybird pnpm exec tb deploy ``` -------------------------------- ### Run Database Migrations (Bash) Source: https://github.com/emitkithq/emitkit/blob/main/docs/deployment.md Commands to set the DATABASE_URL environment variable and then generate and push the database schema using pnpm. Requires Node.js and pnpm. ```bash # Set DATABASE_URL locally export DATABASE_URL="your-neon-connection-string" # Generate and push schema pnpm run db:generate pnpm run db:push ``` -------------------------------- ### Deploy and Test Tinybird Resources Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Explains how to manage and deploy changes made to Tinybird resources, such as datasources and pipes. It covers editing the relevant files, deploying them using the Tinybird CLI, and testing specific pipes with parameters. This ensures Tinybird infrastructure stays synchronized with the project. ```bash # Edit .datasource or .pipe files in tinybird/ # Deploy changes cd tinybird && pnpm exec tb deploy # Test pipes pnpm exec tb pipe test PIPE_NAME --param key=value ``` -------------------------------- ### Configure Sentry Initialization (TypeScript) Source: https://github.com/emitkithq/emitkit/blob/main/docs/configuration.md Initialize the Sentry SDK with configuration options such as DSN, environment, and sampling rates for traces and replays. This code snippet shows the typical setup in a TypeScript environment. ```typescript Sentry.init({ dsn: sentryDsn, environment: process.env.NODE_ENV || 'production', tracesSampleRate: 0.1, // 10% of requests replaysSessionSampleRate: 0.01, // 1% of sessions replaysOnErrorSampleRate: 1.0 // 100% of error sessions }); ``` -------------------------------- ### Troubleshoot Build Errors with pnpm and Node.js Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Addresses common build errors such as TypeScript issues or missing dependencies. It provides commands to clean the project, reinstall dependencies, verify the Node.js version, and run TypeScript checks. Ensure Node.js version is 18 or higher. ```bash # Clean install rm -rf node_modules pnpm-lock.yaml pnpm install # Verify Node version (must be 18+) node --version # Check for TypeScript errors pnpm run check ``` -------------------------------- ### TypeScript: Creating Descriptive Loggers Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md This example shows the best practice of using descriptive names when creating loggers. It contrasts 'good' examples with specific contexts like 'job-posting' against 'bad' examples that are too generic. ```typescript // Good const logger = createContextLogger('job-posting'); const logger = createContextLogger('payment-webhook'); const logger = createContextLogger('email-service'); // Bad const logger = createContextLogger('service'); const logger = createContextLogger('handler'); ``` -------------------------------- ### Authenticate with Tinybird CLI Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Logs you into the Tinybird CLI using your account credentials. This command typically opens a browser window for authentication and is required before deploying Tinybird resources. ```bash cd tinybird pnpm exec tb login ``` -------------------------------- ### Deploy Specific Tinybird Resources Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Deploys individual Tinybird resources, such as a specific data source or pipe. This is useful for deploying only the modified resources, saving time during development. ```bash pnpm exec tb deploy datasources/events.datasource pnpm exec tb deploy pipes/stream_events.pipe ``` -------------------------------- ### Configure PostgreSQL Connection String in .env Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Sets the DATABASE_URL environment variable in the .env file to configure the connection string for PostgreSQL. Supports both Dockerized and existing PostgreSQL instances. ```env DATABASE_URL="postgres://root:mysecretpassword@localhost:5433/local" ``` ```env DATABASE_URL="postgres://user:password@localhost:5432/blip" ``` -------------------------------- ### Deploy Tinybird Resources Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Deploys data sources, streaming pipes, and analytics pipes to your Tinybird account. This command uses the Tinybird CLI to provision the necessary resources for data ingestion and processing. ```bash pnpm exec tb deploy ``` -------------------------------- ### Start Tracked Operation with Logger in TypeScript Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md This TypeScript code illustrates how to start a tracked operation using a logger instance. The `start` method takes an operation name and optional metadata, returning an `OperationLogger` instance. This instance is used to log steps and mark the end of the operation, either successfully or with an error, including timing information. ```typescript const operation = logger.start('Process payment', { amount: 5000, currency: 'USD' }); ``` -------------------------------- ### Authenticate with Tinybird CLI Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Logs the user into the Tinybird service using the CLI. This process opens a web browser for authentication and stores the credentials securely in a `.tinyb` file, which is typically gitignored. ```bash pnpm exec tb login ``` -------------------------------- ### Configure OpenAI API Key in .env Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Sets the OPENAI_API_KEY environment variable in the .env file to enable AI-powered features such as channel description generation. Requires an API key from OpenAI. ```env OPENAI_API_KEY="your-openai-api-key" ``` -------------------------------- ### Authentication Header Example Source: https://github.com/emitkithq/emitkit/blob/main/bruno/README.md Demonstrates the required `Authorization` header format for authenticating API requests. This header must include a valid Bearer token. ```text Authorization: Bearer emitkit_xxxxxxxxxxxxxxxxxxxxx ``` -------------------------------- ### REST API - Get Events Stats Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Retrieves aggregated statistics related to events, useful for dashboard visualizations. ```APIDOC ## Get Events Stats API This endpoint provides aggregated statistics derived from event data, making it ideal for populating dashboards. It can return metrics such as total event counts, unique user counts, and distributions of event tags. Filtering by `organization_id`, optional `channel_id`, and date ranges (`date_from`, `date_to`) is supported. ### Method ```http GET ``` ### Endpoint ```http https://api.tinybird.co/v0/pipes/get_events_stats.json ``` ### Parameters #### Query Parameters - **organization_id** (string) - Required - The identifier for the organization. - **channel_id** (string) - Optional - The identifier for the channel. If omitted, stats are aggregated across all channels for the organization. - **date_from** (date) - Optional - Start date for the statistics period (format: `YYYY-MM-DD`). - **date_to** (date) - Optional - End date for the statistics period (format: `YYYY-MM-DD`). ### Request Example ```http GET https://api.tinybird.co/v0/pipes/get_events_stats.json?organization_id=org_123&date_from=2024-07-01&date_to=2024-07-27 ``` ### Response #### Success Response (200) - **stats** (object) - An object containing various statistical aggregates. - **event_count** (integer) - Total number of events within the specified period. - **unique_users** (integer) - Count of distinct users associated with events. - **tag_distribution** (object) - A map where keys are tags and values are the counts of events associated with that tag. #### Response Example ```json { "stats": { "event_count": 15000, "unique_users": 3500, "tag_distribution": { "new_feature": 5000, "bug": 2000, "performance": 3000 } } } ``` ``` -------------------------------- ### REST API - Get Events Paginated Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Retrieves a paginated list of historical events, allowing for filtering by date range and other criteria. ```APIDOC ## Get Events Paginated API This endpoint provides a paginated list of historical events. It allows users to browse through past events with options to filter by `channel_id`, `organization_id`, and specific date ranges (`date_from`, `date_to`). It also supports standard pagination parameters like `limit` and `offset`. ### Method ```http GET ``` ### Endpoint ```http https://api.tinybird.co/v0/pipes/get_events_paginated.json ``` ### Parameters #### Query Parameters - **organization_id** (string) - Required - The identifier for the organization. - **channel_id** (string) - Optional - The identifier for the channel. - **limit** (integer) - Optional - The maximum number of events to return per page (default: 100). - **offset** (integer) - Optional - The number of events to skip for pagination (default: 0). - **date_from** (date) - Optional - Start date for filtering events (format: `YYYY-MM-DD`). - **date_to** (date) - Optional - End date for filtering events (format: `YYYY-MM-DD`). ### Request Example ```http GET https://api.tinybird.co/v0/pipes/get_events_paginated.json?organization_id=org_123&limit=50&offset=100&date_from=2024-07-01&date_to=2024-07-27 ``` ### Response #### Success Response (200) - **data** (array) - A list of event objects matching the query criteria. - Each event object contains details like `event_id`, `created_at`, `title`, etc. - **total_count** (integer) - The total number of events available matching the filters (before pagination). #### Response Example ```json { "data": [ { "event_id": "evt_xyz1", "organization_id": "org_123", "channel_id": "ch_456", "created_at": "2024-07-26T15:30:00Z", "title": "Item Added to Cart", "metadata": { ... } }, // ... more events up to the limit ], "total_count": 1500 } ``` ``` -------------------------------- ### SvelteKit Development Workflow Commands Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md This snippet lists essential pnpm commands for SvelteKit development, including starting the dev server, accessing Drizzle Studio, generating migrations, pushing schema changes, and performing type checking. ```bash # Start development pnpm run dev # Database operations pnpm run db:studio # Open Drizzle Studio pnpm run db:generate # Generate migrations pnpm run db:push # Push schema changes # Type checking pnpm run check # Must have zero errors ``` -------------------------------- ### Configure Vite Development Server Port Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Provides a solution for the 'Port already in use' error, specifically for port 5173. It suggests either stopping conflicting processes or changing the port within the Vite configuration file. The example shows how to set the server port to 3000. ```typescript import { defineConfig } from 'vite'; export default defineConfig({ server: { port: 3000 // Change to any available port } }); ``` -------------------------------- ### Local Development and Deployment Commands (Bash) Source: https://github.com/emitkithq/emitkit/blob/main/docs/deployment.md Provides essential bash commands for local development, type checking, database operations, deployment, log viewing, and environment variable management for the EmitKit project. ```bash # Local development pnpm run dev # Type check pnpm run check # Database commands pnpm run db:generate # Generate migrations pnpm run db:push # Push to database pnpm run db:studio # Open Drizzle Studio # Deploy vercel --prod # View logs vercel logs --prod # Environment variables vercel env ls vercel env add VARIABLE_NAME production ``` -------------------------------- ### Feature Directory Structure Example Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Illustrates the feature-first organizational pattern where all related code for a feature (server logic, components, validators, types) resides within a single directory. This promotes cohesion and simplifies management. ```tree src/ ├── lib/ │ ├── features/ │ │ ├── channels/ │ │ │ ├── server/ │ │ │ │ └── repository.ts │ │ │ ├── components/ │ │ │ ├── validators.ts │ │ │ └── types.ts │ │ ├── sites/ │ │ │ ├── server/ │ │ │ │ ├── repository.ts │ │ │ │ └── service.ts │ │ │ └── ... │ │ ├── events/ │ │ │ ├── server/ │ │ │ │ ├── tinybird.service.ts │ │ │ │ └── mutations.ts │ │ │ └── ... │ │ └── [other-features]/ │ │ │ ├── server/ │ │ ├── db/ │ │ │ ├── schema/ │ │ │ ├── migrations/ │ │ │ ├── utils.ts │ │ │ └── index.ts │ │ ├── logger/ │ │ ├── cache.ts │ │ └── tinybird.ts │ │ │ └── components/ │ └── ui/ ``` -------------------------------- ### Configure Tinybird for Events and Analytics (Bash) Source: https://github.com/emitkithq/emitkit/blob/main/docs/configuration.md Set the API token and URL for Tinybird, used for event storage and analytics. This integration allows for detailed event tracking and analysis. Refer to the Tinybird Setup Guide for more. ```bash TINYBIRD_TOKEN="your-tinybird-token-here" TINYBIRD_API_URL="https://api.tinybird.co" ``` -------------------------------- ### Service Layer: Create Site with API Key (TypeScript) Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Demonstrates creating a site and generating an API key, showcasing complex business logic involving multiple operations. This function is intended for use when repository logic becomes too complex. ```typescript export async function createSiteWithApiKey( orgId: string, data: SiteInput ): Promise<{ site: Site; apiKey: string }> { // Complex business logic involving multiple operations const site = await createSite({ ...data, organizationId: orgId }); const apiKey = await generateApiKey(site.id); return { site, apiKey }; } ``` -------------------------------- ### TypeScript: Using Appropriate Log Levels Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md This example demonstrates the correct usage of different log levels (info, success, warn, error) for various scenarios. It shows how to log routine operations, important positive outcomes, potential issues, and actual errors. ```typescript // Info - normal operation logger.info('User logged in', { userId: '123' }); // Success - important positive outcome logger.success('Payment processed', { orderId: '123', amount: 5000 }); // Warn - potential issue, but not critical logger.warn('High memory usage', { usage: 85, threshold: 80 }); // Error - actual error requiring attention logger.error('Database connection failed', error); ``` -------------------------------- ### Truncate Tinybird Datasource Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Command to delete all data from a Tinybird datasource. This operation is irreversible and should only be used in development environments. ```bash pnpm exec tb datasource truncate events --yes ``` -------------------------------- ### Pagination: List Channels Example (TypeScript) Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Illustrates a standardized pagination approach for listing channels, using helper functions like `buildPaginatedQuery`. This function takes organization ID and optional pagination parameters to return a paginated result set. ```typescript import { buildPaginatedQuery, type PaginationParams } from '$lib/server/db/utils'; export async function listChannels( orgId: string, pagination?: PaginationParams ): Promise> { const page = pagination?.page ?? 1; const limit = pagination?.limit ?? 20; const offset = (page - 1) * limit; const query = db.query.channel.findMany({ where: eq(schema.channel.organizationId, orgId), limit, offset }); const countQuery = db .select({ count: sql`count(*)` }) .from(schema.channel) .where(eq(schema.channel.organizationId, orgId)); return await buildPaginatedQuery(query, countQuery, { page, limit }); } ``` -------------------------------- ### REST API - Stream Events Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Provides real-time event streaming, suitable for live dashboards. Clients poll this endpoint periodically. ```APIDOC ## Stream Events API This endpoint provides a stream of events in real-time, designed for dynamic dashboards. It supports filtering by `channel_id`, `organization_id`, and fetching events `since` a specific timestamp. Clients are expected to poll this endpoint regularly, typically every 3 seconds, to receive updates. ### Method ```http GET ``` ### Endpoint ```http https://api.tinybird.co/v0/pipes/stream_events.json ``` ### Parameters #### Query Parameters - **organization_id** (string) - Required - The identifier for the organization. - **channel_id** (string) - Required - The identifier for the channel. - **since** (timestamp) - Optional - Fetches events that occurred after this timestamp (e.g., `YYYY-MM-DD HH:MM:SS`). ### Request Example ```http GET https://api.tinybird.co/v0/pipes/stream_events.json?organization_id=org_123&channel_id=ch_456&since=2024-07-28T10:00:00Z ``` ### Response #### Success Response (200) - **data** (array) - A list of event objects. - Each event object contains details like `event_id`, `created_at`, and other relevant event data. #### Response Example ```json { "data": [ { "event_id": "evt_abc1", "organization_id": "org_123", "channel_id": "ch_456", "created_at": "2024-07-28T10:01:05Z", "title": "User Login", "metadata": { ... } }, { "event_id": "evt_abc2", "organization_id": "org_123", "channel_id": "ch_456", "created_at": "2024-07-28T10:01:10Z", "title": "Page View", "metadata": { ... } } ] } ``` ``` -------------------------------- ### Basic Logging in TypeScript Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Demonstrates the basic usage of the logging system in TypeScript. It shows how to create a context-aware logger and use its methods for different log levels like info, warn, error, and success, including passing structured metadata. ```typescript import { createContextLogger } from '$lib/server/logger'; // Create a logger with context const logger = createContextLogger('feature-name'); // Simple logging logger.info('User logged in', { userId: '123', email: 'user@example.com' }); logger.warn('Rate limit approaching', { current: 95, max: 100 }); logger.error('Database query failed', error, { query: 'SELECT...' }); logger.success('Job published', { jobId: 'abc', slug: 'software-engineer' }); ``` -------------------------------- ### Configure Better Auth in .env Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Sets the BETTER_AUTH_SECRET and BETTER_AUTH_URL environment variables in the .env file for Better Auth configuration. The secret should be randomly generated. ```env BETTER_AUTH_SECRET="your-generated-secret-here" BETTER_AUTH_URL="http://localhost:5173" ``` -------------------------------- ### Deploy to Vercel (Bash) Source: https://github.com/emitkithq/emitkit/blob/main/docs/deployment.md Two methods for deploying the project to Vercel in production. Option 1 uses the Vercel dashboard, while Option 2 uses the Vercel CLI. ```bash # Option 1: Deploy via Vercel Dashboard # Click "Deploy" button # Option 2: Deploy via CLI vercel --prod ``` -------------------------------- ### Monitor Tinybird Pipe Statistics Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Displays real-time statistics for a specific Tinybird pipe. This helps in monitoring the performance and usage of your API endpoints. ```bash pnpm exec tb pipe stats stream_events ``` -------------------------------- ### Redeploy Project (Bash) Source: https://github.com/emitkithq/emitkit/blob/main/docs/deployment.md Command to trigger a redeployment of the Vercel project after updating environment variables or configuration. Assumes the Vercel CLI is installed and configured. ```bash vercel --prod ``` -------------------------------- ### Import Lucide Svelte Icon Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Demonstrates the correct way to import icons from the '@lucide/svelte' package. It emphasizes importing the full path to avoid issues with the 'lucide-svelte' package not existing. ```typescript import ZapIcon from '@lucide/svelte/icons/zap'; ``` -------------------------------- ### Configure VAPID Keys in .env Source: https://github.com/emitkithq/emitkit/blob/main/docs/installation.md Sets the PUBLIC_VAPID_KEY, VAPID_KEY, and VAPID_SUBJECT environment variables in the .env file for web push notifications. These are generated using the web-push CLI. ```env PUBLIC_VAPID_KEY="BPx1...xyz" VAPID_KEY="abc...123" VAPID_SUBJECT="mailto:your-email@example.com" ``` -------------------------------- ### Reinstall Project Dependencies (Bash) Source: https://github.com/emitkithq/emitkit/blob/main/docs/troubleshooting.md Remove existing `node_modules` and lock files, then reinstall project dependencies. This can resolve issues caused by corrupted installations or dependency mismatches. ```bash rm -rf node_modules pnpm install ``` -------------------------------- ### Test Tinybird Pipe Locally Source: https://github.com/emitkithq/emitkit/blob/main/docs/tinybird.md Tests a specific Tinybird pipe (e.g., 'stream_events') with provided parameters. This is useful for debugging pipes locally before deploying them to the Tinybird service. ```bash pnpm exec tb pipe test stream_events \ --param organization_id=org_123 \ --param channel_id=ch_456 \ --param since="2024-01-01 00:00:00" ``` -------------------------------- ### Database Management Commands Source: https://github.com/emitkithq/emitkit/blob/main/CLAUDE.md Commands for managing database migrations and schema changes. 'db:generate' creates migration files, 'db:migrate' applies them, and 'db:push' is for development-only schema updates. ```bash pnpm run db:generate # Generate migration files pnpm run db:migrate # Apply migrations pnpm run db:push # Push schema changes (dev only) ```