### GET Request Example with Query Parameters Source: https://context7_llms Illustrates how to perform a GET request with URL query parameters for filtering or pagination. ```APIDOC ## GET Request Example with Query Parameters ### Description This example demonstrates making a GET request to retrieve a list of users, utilizing query parameters to specify the page number and limit. ### Method `GET` ### Endpoint `/users` ### Query Parameters - **page** (string) - Required - The page number to retrieve. - **limit** (string) - Required - The maximum number of items per page. ### Request Example ```typescript const UsersSchema = z.array(z.object({ id: z.number(), name: z.string(), email: z.string().email(), })); const url = new URL("https://api.example.com/users"); url.searchParams.set("page", "1"); url.searchParams.set("limit", "10"); const users = await $fetch(url.toString(), UsersSchema); ``` ### Response #### Success Response (200) - An array of user objects, each containing: - **id** (number) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane.smith@example.com" } ] ``` ``` -------------------------------- ### Turborepo CI Pipeline Example Source: https://context7_llms Example YAML snippet demonstrating how a CI pipeline can leverage Turborepo for efficient dependency installation and running validation tasks. It assumes pnpm is used for package management. ```yaml # Your CI pipeline benefits from Turborepo's cache - name: Install dependencies run: pnpm install --frozen-lockfile - name: Validate run: pnpm turbo run validate ``` -------------------------------- ### Installation of @zap-studio/fetch Source: https://context7_llms Provides commands for installing the @zap-studio/fetch package using pnpm or npm. ```bash pnpm add @zap-studio/fetch # or npm install @zap-studio/fetch ``` -------------------------------- ### Install @zap-studio/permit Source: https://context7_llms Installs the @zap-studio/permit library using either pnpm or npm package managers. ```bash pnpm add @zap-studio/permit # or npm install @zap-studio/permit ``` -------------------------------- ### Vitest test example Source: https://context7_llms A basic example of how to write a test case using Vitest. It demonstrates importing testing utilities and defining a test suite with a simple assertion. ```typescript import { describe, it, expect } from "vitest"; describe("myFunction", () => { it("should return the correct value", () => { expect(myFunction(2)).toBe(4); }); }); ``` -------------------------------- ### Build Blog API Client with TypeScript and Zod Source: https://context7_llms Provides a complete example of creating a blog API client using TypeScript and the `@zap-studio/fetch` library. It defines various Zod schemas for posts and comments, and then constructs functions to interact with the API for fetching, creating, updating, and deleting posts, as well as adding comments. The example also shows basic usage of the created client. ```typescript import { z } from "zod"; import { createFetch } from "@zap-studio/fetch"; // Schemas const PostSchema = z.object({ id: z.string(), title: z.string(), content: z.string(), authorId: z.string(), published: z.boolean(), createdAt: z.string(), updatedAt: z.string(), }); const PostListSchema = z.object({ posts: z.array(PostSchema), total: z.number(), hasMore: z.boolean(), }); const CommentSchema = z.object({ id: z.string(), postId: z.string(), authorId: z.string(), content: z.string(), createdAt: z.string(), }); // Create API client const { api } = createFetch({ baseURL: "https://api.myblog.com/v1", headers: { Authorization: `Bearer ${getAuthToken()}`, }, }); // Blog API functions export const blogApi = { // Get all posts async getPosts(page = 1, limit = 10) { return api.get("/posts", PostListSchema, { searchParams: { page: String(page), limit: String(limit) }, }); }, // Get single post async getPost(id: string) { return api.get(`/posts/${id}`, PostSchema); }, // Create post async createPost(data: { title: string; content: string }) { return api.post("/posts", PostSchema, { body: data }); }, // Update post async updatePost(id: string, data: Partial<{ title: string; content: string; published: boolean }>) { return api.patch(`/posts/${id}`, PostSchema, { body: data }); }, // Delete post async deletePost(id: string) { return api.delete(`/posts/${id}`, z.object({ success: z.boolean() })); }, // Add comment async addComment(postId: string, content: string) { return api.post(`/posts/${postId}/comments`, CommentSchema, { body: { content }, }); }, }; // Usage const { posts, hasMore } = await blogApi.getPosts(); const newPost = await blogApi.createPost({ title: "My First Post", content: "Hello, world!", }); await blogApi.updatePost(newPost.id, { published: true }); ``` -------------------------------- ### Tauri Logging Configuration Setup Source: https://context7_llms Provides the basic setup for configuring the Tauri logging plugin in Rust. It defines the output targets (stdout, webview, log directory), timezone strategy, and maximum file size for log rotation. ```rust use tauri_plugin_log::{Target, TargetKind, TimezoneStrategy}; pub fn build() -> tauri_plugin_log::Builder { tauri_plugin_log::Builder::new() .targets([ Target::new(TargetKind::Stdout), Target::new(TargetKind::Webview), Target::new(TargetKind::LogDir { file_name: Some("logs".to_string()), }), ]) .timezone_strategy(TimezoneStrategy::UseLocal) .max_file_size(50_000) } ``` -------------------------------- ### Rust Logging Example Source: https://context7_llms Demonstrates how to use the standard Rust `log` macros for logging messages with different levels. This is useful for debugging and tracking application events within the Rust backend. ```rust log::info!("Application started"); log::debug!("Processing user: {}", user_id); log::warn!("Deprecated API called"); log::error!("Failed to save settings: {}", error); ``` -------------------------------- ### Install Project Dependencies Source: https://www.zapstudio.dev/local-ts Install all the required project dependencies using the pnpm package manager. This step ensures that all necessary libraries and tools are available for development. ```bash pnpm install ``` -------------------------------- ### GET Request with Query Parameters using $fetch Source: https://context7_llms This example shows how to make a GET request with query parameters using the $fetch function. It constructs a URL with search parameters and passes a schema for response validation. This is useful for filtering or paginating API results. ```typescript const url = new URL("https://api.example.com/users"); url.searchParams.set("page", "1"); url.searchParams.set("limit", "10"); const users = await $fetch(url.toString(), UsersSchema); ``` -------------------------------- ### Generate Database Migration for New Setting Source: https://context7_llms Provides a command-line example for generating a new database migration using Diesel, demonstrating the creation of SQL files for schema changes. ```bash cd src-tauri diesel migration generate add_my_setting ``` -------------------------------- ### Install @zap-studio/validation Source: https://context7_llms Instructions for installing the @zap-studio/validation package using pnpm or npm. This package provides standard schema utilities and ValidationError helpers for consistent validation across libraries. ```bash pnpm add @zap-studio/validation # or npm install @zap-studio/validation ``` -------------------------------- ### GET /products Source: https://context7_llms Fetches a list of products with support for query parameters like search term, page number, and limit. ```APIDOC ## GET /products ### Description Fetches a list of products based on the provided search query and pagination parameters. ### Method GET ### Endpoint /products ### Query Parameters - **q** (string) - Required - The search query string. - **page** (integer) - Optional - The page number to retrieve (defaults to 1). - **limit** (integer) - Optional - The number of items per page (defaults to 20). ### Response #### Success Response (200) - **products** (array) - An array of product objects. - **total** (integer) - The total number of products found. - **page** (integer) - The current page number. - **perPage** (integer) - The number of products per page. #### Response Example ```json { "products": [ { "id": "string", "name": "string", "price": "number" } ], "total": "number", "page": "number", "perPage": "number" } ``` ``` -------------------------------- ### Blog Post Authorization Example (TypeScript) Source: https://context7_llms Demonstrates how to check if a user can edit a blog post based on their role and if they are the author. It uses a predefined policy and context objects to simulate user interactions. This example highlights simple role-based and ownership-based authorization checks. ```typescript // Scenario: User trying to edit a blog post const context: AppContext = { user: { id: "user-123", role: "user", permissions: [], organizationId: "org-1" }, timestamp: new Date(), }; const post = { id: "post-456", authorId: "user-123", // Same as context.user.id (so user is the author) title: "My First Post", visibility: "public" as const, createdAt: new Date(), }; // The user is the author, so this returns true according to the policy const canEdit = policy.can(context, "write", "post", post); console.log(canEdit); // true // A different user trying to edit const otherContext: AppContext = { user: { id: "user-789", role: "user", permissions: [], organizationId: "org-1" }, timestamp: new Date(), }; const canOtherEdit = policy.can(otherContext, "write", "post", post); console.log(canOtherEdit); // false ``` -------------------------------- ### POST Request Example with JSON Body Source: https://context7_llms Demonstrates how to make a POST request with a JSON body and schema validation. ```APIDOC ## POST Request Example with JSON Body ### Description This example shows how to send a POST request to create a user, providing a JSON body and a `UserSchema` for validation. ### Method `POST` ### Endpoint `/users` ### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```typescript const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.string().email(), createdAt: z.string().datetime(), }); const user = await $fetch("https://api.example.com/users", UserSchema, { method: "POST", body: { name: "John Doe", email: "john@example.com", }, }); ``` ### Response #### Success Response (200) - **id** (number) - The unique identifier for the created user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **createdAt** (string) - The timestamp when the user was created (ISO format). #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john@example.com", "createdAt": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Install Diesel CLI (Rust) Source: https://context7_llms Installs the Diesel CLI, a command-line interface for the Diesel ORM, which is used for database migrations. This command requires Rust and Cargo to be installed. ```bash cargo install diesel_cli ``` -------------------------------- ### Turborepo available commands Source: https://context7_llms A list of common Turborepo commands for managing the monorepo, including starting development servers, building, linting, testing, and running validation checks. ```markdown ### Available Commands | Command | Description | |---------|-------------| | `turbo dev` | Start Vite dev server | | `turbo tauri -- dev` | Start full Tauri app with hot reload | | `turbo tauri -- build` | Build production app | | `turbo build` | Build frontend | | `turbo check` | TypeScript type checking | | `turbo lint` | Run Ultracite linter | | `turbo format` | Format code with Ultracite | | `turbo test` | Run Vitest tests | | `turbo test:coverage` | Generate coverage report | | `turbo validate` | Run all checks (build, check, lint, test) | ``` -------------------------------- ### Install @zap-studio/webhooks Source: https://context7_llms Installs the @zap-studio/webhooks library using either pnpm or npm package managers. This library is for type-safe webhook handling in TypeScript applications. ```bash pnpm add @zap-studio/webhooks # or npm install @zap-studio/webhooks ``` -------------------------------- ### Run Development Server (Frontend Only) Source: https://context7_llms Starts only the Vite development server, which is useful for frontend development without the native Tauri window. This command allows for quick iteration on the user interface. ```bash turbo dev ``` -------------------------------- ### TypeScript Types for Settings Source: https://context7_llms Illustrates importing and using TypeScript types for settings, including `Settings`, `SettingsUpdate`, `Theme`, and `LogLevel`. Provides examples of their structure and usage in function signatures. ```typescript import type { Settings, SettingsUpdate, Theme, LogLevel } from "@/lib/tauri/settings/types"; // Theme: "light" | "dark" | "system" // LogLevel: "error" | "warn" | "info" | "debug" | "trace" function processSettings(settings: Settings) { console.log(settings.theme); } // The Settings interface: // interface Settings { // theme: Theme; // sidebarExpanded: boolean; // showInTray: boolean; // launchAtLogin: boolean; // enableLogging: boolean; // logLevel: LogLevel; // enableNotifications: boolean; // } ``` -------------------------------- ### Custom Headers Example Source: https://context7_llms Demonstrates how to include custom headers in a request, such as authentication tokens or request identifiers. ```APIDOC ## Custom Headers Example ### Description This example shows how to add custom headers to a request, including an `Authorization` token, an `Accept-Language` header, and a unique `X-Request-ID`. ### Method `GET` ### Endpoint `/users/1` ### Request Body None for this example. ### Request Example ```typescript const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.string().email(), createdAt: z.string().datetime(), }); const user = await $fetch("https://api.example.com/users/1", UserSchema, { headers: { Authorization: "Bearer YOUR_AUTH_TOKEN", "Accept-Language": "en-US", "X-Request-ID": crypto.randomUUID(), // Example of a dynamic header }, }); ``` ### Response #### Success Response (200) - **id** (number) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **createdAt** (string) - The timestamp when the user was created (ISO format). #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john.doe@example.com", "createdAt": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Tauri Bundle Configuration (JSON) Source: https://context7_llms A minimal JSON configuration example for the Tauri bundle section in `tauri.conf.json`. It enables bundling, sets the targets to 'all', and defines a unique application identifier. ```json { "bundle": { "active": true, "targets": "all", "identifier": "com.yourcompany.yourapp" } } ``` -------------------------------- ### Validation Example with @zap-studio/fetch Source: https://context7_llms This example demonstrates the benefit of using @zap-studio/fetch with runtime validation. It shows how a `ValidationError` is thrown immediately if the API response does not match the provided `UserSchema`, preventing subtle bugs. ```typescript // With validation const user = await api.get("/api/users/1", UserSchema); // If the API returns { id: "123" }, you get a ValidationError // instead of silent type mismatch ``` -------------------------------- ### Setup Tauri System Tray Menu Items in Rust Source: https://context7_llms Defines how to set up menu items for the Tauri system tray using Rust. It involves creating `MenuItem` instances with IDs and labels, then building a `Menu` from these items. This function is typically called during application startup. ```rust use tauri::menu::{Menu, MenuItem}; pub fn setup(app: &App, pool: &DbPool) -> Result<(), Box> { // Create menu items let show_i = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?; let hide_i = MenuItem::with_id(app, "hide", "Hide", true, None::<&str>)?; let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; // Build the menu let menu = Menu::with_items(app, &[&show_i, &hide_i, &quit_i])?; // ... rest of setup } ``` -------------------------------- ### Refactor Authorization Logic with @zap-studio/permit Source: https://context7_llms Illustrates how to refactor scattered authorization logic into a centralized policy using @zap-studio/permit. The 'Before' example shows duplicated logic, while the 'After' example demonstrates a clean, declarative approach. ```typescript // Authorization logic scattered everywhere app.delete("/posts/:id", async (req, res) => { const post = await getPost(req.params.id); const user = req.user; // 😱 Logic duplicated across routes if (user.role !== "admin" && post.authorId !== user.id) { return res.status(403).json({ error: "Forbidden" }); } await deletePost(post.id); res.json({ success: true }); }); // --- AFTER --- import { createPolicy, when, or, hasRole } from "@zap-studio/permit"; // ✨ Centralized, declarative authorization const policy = createPolicy({ resources, actions, rules: { post: { delete: when( or( hasRole("admin"), (ctx, _, post) => ctx.user.id === post.authorId ) ), }, }, }); // Clean route handler app.delete("/posts/:id", async (req, res) => { const post = await getPost(req.params.id); if (!policy.can(req.context, "delete", "post", post)) { return res.status(403).json({ error: "Forbidden" }); } await deletePost(post.id); res.json({ success: true }); }); ``` -------------------------------- ### Build Tauri Application (Bash) Source: https://context7_llms Command to build production-ready bundles and installers for a Tauri application across all configured targets. The build artifacts are placed in `src-tauri/target/release/bundle/`. ```bash turbo tauri -- build ``` -------------------------------- ### Create Policy with Allow Rule - TypeScript Source: https://context7_llms Example of creating a policy using `@zap-studio/permit` in TypeScript, demonstrating the use of the `allow()` rule builder for public resources. ```typescript import { createPolicy, allow, when } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { // Anyone can read posts (we'll refine this with conditions later) read: allow(), }, documentation: { // API docs are always public read: allow(), }, }, }); ``` -------------------------------- ### JavaScript Logging Example with Tauri Plugin Source: https://context7_llms Shows how to import and use the Tauri log plugin in JavaScript to send log messages from the frontend. This allows for consistent logging across both backend and frontend. ```typescript import { info, debug, warn, error, trace } from "@tauri-apps/plugin-log"; await info("User clicked button"); await debug(`Processing item ${itemId}`); await warn("This feature is deprecated"); await error("Failed to fetch data"); ``` -------------------------------- ### Using Valibot for Schema Validation Source: https://context7_llms This example demonstrates using Valibot with @zap-studio/fetch for runtime validation. It defines a `UserSchema` using Valibot's syntax and then employs `api.get` to fetch and validate user information. ```typescript import * as v from "valibot"; import { api } from "@zap-studio/fetch"; const UserSchema = v.object({ id: v.number(), name: v.string(), email: v.pipe(v.string(), v.email()), createdAt: v.pipe(v.string(), v.isoTimestamp()), }); const user = await api.get("/users/1", UserSchema); ``` -------------------------------- ### TypeScript @zap-studio/permit: and() Combinator Usage Source: https://context7_llms Example demonstrating the usage of the `and()` combinator from the @zap-studio/permit library in TypeScript. It shows how to combine multiple conditions to create a policy rule that requires all conditions to be met. ```typescript import { createPolicy, when, and } from "@zap-studio/permit"; // User must be authenticated AND be the owner AND post must be published const canEditPublishedPost = and( (ctx) => ctx.user !== null, (ctx, _, post) => ctx.user?.id === post.authorId, (_, __, post) => post.status === "published" ); const policy = createPolicy({ resources, actions, rules: { post: { edit: when(canEditPublishedPost), }, }, }); ``` -------------------------------- ### Ultracite CLI Commands Source: https://context7_llms Bash commands for managing code quality using Ultracite, a zero-configuration linter and formatter. Includes commands for fixing issues, checking for problems, and diagnosing setup. ```bash # Format and fix all issues pnpm dlx ultracite fix # Check for issues without fixing pnpm dlx ultracite check # Diagnose setup issues pnpm dlx ultracite doctor ``` -------------------------------- ### Define Actions for Resources Source: https://context7_llms Defines the allowed actions for each resource type. This example uses a `readonly` array and `as const` to ensure literal types for actions, which aids in autocompletion and type checking. ```typescript import type { Actions } from "@zap-studio/permit/types"; const actions = { post: ["read", "write", "delete", "publish"], comment: ["read", "write", "delete"], user: ["read", "update", "delete", "ban"], } as const satisfies Actions; ``` -------------------------------- ### Create Policy with When Rule - TypeScript Source: https://context7_llms Example of creating a policy using `@zap-studio/permit` in TypeScript, illustrating the use of the `when()` rule builder for conditional access, such as allowing only the author to edit or delete their own post. ```typescript import { createPolicy, when } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { // Only the author can edit their post write: when((ctx, _, post) => ctx.user?.id === post.authorId), // Only the author can delete their post delete: when((ctx, _, post) => ctx.user?.id === post.authorId), }, }, }); ``` -------------------------------- ### TypeScript @zap-studio/permit: or() Combinator Usage Source: https://context7_llms Example demonstrating the usage of the `or()` combinator from the @zap-studio/permit library in TypeScript. It shows how to combine multiple conditions to create a policy rule where any of the conditions being met grants access. ```typescript import { createPolicy, when, or } from "@zap-studio/permit"; // User can access if they're the owner OR an admin OR explicitly shared const canAccess = or( (ctx, _, doc) => ctx.user?.id === doc.ownerId, (ctx) => ctx.user?.role === "admin", (ctx, _, doc) => doc.sharedWith.includes(ctx.user?.id ?? "") ); const policy = createPolicy({ resources, actions, rules: { document: { read: when(canAccess), }, }, }); ``` -------------------------------- ### Turborepo validate command example Source: https://context7_llms Demonstrates the usage of the `turbo validate` command, which orchestrates multiple quality checks including build, type checking, linting, and testing. This command is useful for ensuring code quality before commits or in CI pipelines. ```bash turbo validate ``` -------------------------------- ### Create Policy with Deny Rule - TypeScript Source: https://context7_llms Example of creating a policy using `@zap-studio/permit` in TypeScript, showing the use of the `deny()` rule builder to block specific actions like deleting permanently archived posts or using deprecated features. ```typescript import { createPolicy, allow, deny, when } from "@zap-studio/permit"; const policy = createPolicy({ resources, actions, rules: { post: { read: allow(), write: when((ctx, _, post) => ctx.user?.id === post.authorId), // Permanently archived posts cannot be deleted delete: deny(), }, legacyFeature: { // This feature is deprecated and disabled use: deny(), }, }, }); ``` -------------------------------- ### Create Fetch Client with Base URL and Absolute Path Source: https://context7_llms Illustrates creating a fetch client with a base URL but making a request using an absolute URL. Absolute URLs, starting with 'http://', 'https://', or '//', will ignore the configured `baseURL`. ```typescript const { api } = createFetch({ baseURL: "https://api.example.com" }); // Fetches https://other-api.com/data (ignores baseURL) const data = await api.get("https://other-api.com/data", DataSchema); ``` -------------------------------- ### Install and Use Cargo Tarpaulin for Coverage Source: https://context7_llms Instructions for installing and using Cargo Tarpaulin to generate code coverage reports for Rust projects. It covers installation, generating an HTML report, and viewing it in a browser. ```bash # Install tarpaulin cargo install cargo-tarpaulin # Generate HTML coverage report cargo tarpaulin --out Html # View in browser open tarpaulin-report.html ``` -------------------------------- ### Create Fetch Client with Base URL and Relative Path Source: https://context7_llms Demonstrates how to initialize a fetch client with a base URL and make a request using a relative path. The base URL is automatically prepended to relative paths. Leading slashes in relative paths are optional. ```typescript const { api } = createFetch({ baseURL: "https://api.example.com" }); // Fetches https://api.example.com/users const users = await api.get("/users", UsersSchema); // Leading slash is optional const user = await api.get("users/1", UserSchema); ``` -------------------------------- ### Tauri Logging: Log to Separate Files by Level Source: https://context7_llms An example of configuring the logging system to write logs to separate files based on their level. This example directs errors to an 'errors' file and all other logs to an 'all' file, in addition to stdout. ```rust .targets([ Target::new(TargetKind::Stdout), Target::new(TargetKind::LogDir { file_name: Some("errors".to_string()) }) .filter(|metadata| metadata.level() == log::Level::Error), Target::new(TargetKind::LogDir { file_name: Some("all".to_string()) }), ]) ``` -------------------------------- ### Tailwind CSS Dark Mode Styling Examples Source: https://context7_llms Demonstrates how to apply dark mode styles using Tailwind CSS. The first example shows CSS class overrides, while the second uses Tailwind's utility classes for inline styling. Both methods rely on the 'dark' class being present on an ancestor element. ```css .card { background: white; } .dark .card { background: #1a1a1a; } ``` ```html
Content
``` -------------------------------- ### Run Development Server (Tauri) Source: https://context7_llms Starts the application in development mode using the Turbo build system and Tauri. This command launches the Vite development server, enables hot reloading, and opens the app in a native window, providing instant updates for React code changes. ```bash turbo tauri -- dev ``` -------------------------------- ### Standard Schema Validation with ArkType Source: https://context7_llms Provides an example of utilizing ArkType with the $fetch API for runtime data validation. ```APIDOC ## Using ArkType for Validation ### Description This example shows how to use ArkType, a schema library with a 1:1 TypeScript syntax, with the `@zap-studio/fetch` API for robust runtime validation. ### Method `GET` ### Endpoint `/users/1` ### Parameters (Assumes standard parameters for a GET request to fetch a single user) ### Request Example ```typescript import { type } from "arktype"; import { $fetch } from "@zap-studio/fetch"; const UserSchema = type({ id: "number", name: "string", email: "email", createdAt: "string", // ArkType can infer datetime format for validation }); try { const user = await $fetch("/users/1", UserSchema); console.log("Validated user:", user); } catch (error) { // Handle validation or fetch errors console.error(error); } ``` ### Response #### Success Response (200) - **id** (number) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **createdAt** (string) - The timestamp when the user was created. #### Error Response - **ValidationError**: Thrown if the response data does not match `UserSchema`. - **FetchError**: Thrown for non-2xx HTTP status codes (if `throwOnFetchError` is true). ``` -------------------------------- ### Standard Schema Validation with Zod Source: https://context7_llms Provides an example of using Zod with the $fetch API for runtime data validation. ```APIDOC ## Using Zod for Validation ### Description This example demonstrates how to integrate Zod, a popular schema validation library, with the `@zap-studio/fetch` API to ensure data integrity. ### Method `GET` ### Endpoint `/users/1` ### Parameters (Assumes standard parameters for a GET request to fetch a single user) ### Request Example ```typescript import { z } from "zod"; import { $fetch } from "@zap-studio/fetch"; const UserSchema = z.object({ id: z.number(), name: z.string(), email: z.string().email(), createdAt: z.string().datetime(), }); try { const user = await $fetch("/users/1", UserSchema); console.log("Validated user:", user); } catch (error) { if (error instanceof ValidationError) { console.error("Validation failed:", error.message); } else { console.error("Fetch error:", error); } } ``` ### Response #### Success Response (200) - **id** (number) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. - **createdAt** (string) - The timestamp when the user was created (ISO format). #### Error Response - **ValidationError**: Thrown if the response data does not match `UserSchema`. - **FetchError**: Thrown for non-2xx HTTP status codes (if `throwOnFetchError` is true). ``` -------------------------------- ### POST /users Source: https://context7_llms Creates a new user resource on the server. ```APIDOC ## POST /users ### Description Creates a new user with the provided name, email, and password. ### Method POST ### Endpoint /users ### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (200 or 201) - **id** (string) - The unique identifier of the created user. - **name** (string) - The name of the created user. - **email** (string) - The email address of the created user. - **createdAt** (string) - The timestamp when the user was created. #### Response Example ```json { "id": "user-abc-123", "name": "John Doe", "email": "john.doe@example.com", "createdAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Tauri Autostart Settings Integration Source: https://context7_llms TypeScript function to handle the 'Launch at Login' setting in Local.ts. It toggles the autostart functionality using the Tauri plugin and updates the application settings. ```typescript const handleAutostartChange = async (enabled: boolean) => { if (enabled) { await enable(); } else { await disable(); } await updateSettings({ launchAtLogin: enabled }); }; ``` -------------------------------- ### Delete a Resource using DELETE in TypeScript Source: https://context7_llms Provides an example of removing a resource from the server using the `api.delete` method. It includes a schema for validating the deletion response. ```typescript const DeleteResponseSchema = z.object({ success: z.boolean(), deletedAt: z.string(), }); async function deletePost(postId: string) { const result = await api.delete( `https://api.example.com/posts/${postId}`, DeleteResponseSchema ); if (result.success) { console.log(`Post deleted at ${result.deletedAt}`); } return result; } ``` -------------------------------- ### Format Code Source: https://context7_llms Automatically formats the project's code according to predefined style guidelines. This command ensures consistency across the codebase. ```bash turbo format ``` -------------------------------- ### Clone Local.ts Repository Source: https://www.zapstudio.dev/local-ts Clone the Local.ts starter kit repository to begin building your local-first application. This command initializes your project by downloading the necessary files from GitHub. ```bash git clone https://github.com/zap-studio/local.ts.git my-app cd my-app ``` -------------------------------- ### Tauri Logging: Change File Rotation Size Source: https://context7_llms Illustrates how to modify the `max_file_size` configuration option for log files. This example sets the maximum file size to 100KB. ```rust .max_file_size(100_000) // 100KB per file ``` -------------------------------- ### Basic Fetch vs. @zap-studio/fetch Source: https://context7_llms Illustrates the difference between unsafe type assertions with standard fetch and the type-safe, validated approach using @zap-studio/fetch. ```typescript const response = await fetch("/api/users/1"); const data = await response.json(); const user = data as User; // 😱 Unsafe type assertion ``` ```typescript import { api } from "@zap-studio/fetch"; const user = await api.get("/api/users/1", UserSchema); // ✨ Typed, validated, and safe! ``` -------------------------------- ### Run Tests Source: https://context7_llms Executes all defined tests within the project to verify the functionality and stability of the application. ```bash turbo test ``` -------------------------------- ### TypeScript @zap-studio/permit: not() Combinator Usage Source: https://context7_llms Example demonstrating the usage of the `not()` combinator from the @zap-studio/permit library in TypeScript. It shows how to negate a condition, allowing access only when the original condition evaluates to false. ```typescript import { not } from "@zap-studio/permit"; not(condition) ``` -------------------------------- ### Creating Multiple API Clients Source: https://context7_llms Illustrates the creation of distinct API clients for different services (e.g., GitHub, Stripe, internal API) using `createFetch`. Each client can be configured with its own `baseURL`, headers, and other options, allowing for modular API interactions within an application. ```typescript import { z } from "zod"; import { createFetch } from "@zap-studio/fetch"; // GitHub API client const github = createFetch({ baseURL: "https://api.github.com", headers: { Authorization: `token ${process.env.GITHUB_TOKEN}`, Accept: "application/vnd.github.v3+json", }, }); // Stripe API client const stripe = createFetch({ baseURL: "https://api.stripe.com/v1", headers: { Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`, }, }); // Internal API client const internal = createFetch({ baseURL: process.env.API_URL, headers: { "X-Internal-Key": process.env.INTERNAL_API_KEY, }, }); // Schemas const RepoSchema = z.object({ id: z.number(), name: z.string(), full_name: z.string(), private: z.boolean(), }); const CustomerSchema = z.object({ id: z.string(), email: z.string(), name: z.string().nullable(), }); // Usage const repo = await github.api.get("/repos/owner/repo", RepoSchema); const customer = await stripe.api.get("/customers/cus_123", CustomerSchema); ``` -------------------------------- ### Initialize Theme Store and Listen for System Changes (TypeScript) Source: https://context7_llms This TypeScript code snippet initializes the theme store, applying the initial theme and resolving it if set to 'system'. It also sets up an event listener to detect changes in the operating system's color scheme preference and updates the resolved theme accordingly if the user's preference is 'system'. This ensures the app UI updates instantly when the OS theme changes. ```typescript export const useTheme = create((set) => ({ // ... initialize: () => { const settings = useSettings.getState().settings; if (settings) { const resolved = applyThemeToDOM(settings.theme); set({ theme: settings.theme, resolvedTheme: resolved }); } const handleChange = () => { const currentTheme = useTheme.getState().theme; if (currentTheme === "system") { const resolved = applyThemeToDOM("system"); set({ resolvedTheme: resolved }); } }; // Listen for system theme changes const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); mediaQuery.addEventListener("change", handleChange); }, })); ``` -------------------------------- ### Generate App Icons using Tauri CLI (Bash) Source: https://context7_llms This command-line instruction shows how to generate application icons for various platforms using the Tauri CLI. It requires a source PNG image (1024x1024 minimum, transparent background recommended) and places the generated icons in the `src-tauri/icons/` directory. ```bash turbo tauri -- icon path/to/your-icon.png ``` -------------------------------- ### Importing Lucide React Icons Source: https://context7_llms Demonstrates how to import icons from the Lucide React library for use in the application's UI components, such as the sidebar. ```typescript import { FileText, Calendar, Mail, Bell } from "lucide-react"; ``` -------------------------------- ### Tauri Bundle Icon Configuration Source: https://context7_llms Example JSON configuration for Tauri to specify application bundle icons. This ensures the correct icons are used across different platforms when the application is bundled. ```json { "tauri": { "bundle": { "icon": [ "icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" ] } } } ``` -------------------------------- ### CI/CD GitHub Action Workflow for Tauri Apps Source: https://context7_llms Automates the build and release process for Tauri applications across multiple platforms (macOS, Linux, Windows). It utilizes a matrix strategy for parallel builds, caches dependencies, and creates draft GitHub releases with artifacts. Triggered manually or by pushing to the 'release' branch. ```yaml name: Publish # Trigger the workflow manually or when pushing to the 'release' branch on: workflow_dispatch: push: branches: - release jobs: build: strategy: matrix: include: # macOS - target: aarch64-apple-darwin os: ubuntu-latest # This is a workaround to ensure the correct runner is used for macOS # See https://github.com/actions/runner-images/issues/4080 runs-on: macos-latest - target: x86_64-apple-darwin os: ubuntu-latest runs-on: macos-latest # Linux - target: x86_64-unknown-linux-gnu os: ubuntu-22.04 runs-on: ubuntu-latest # Windows - target: x86_64-pc-windows-msvc os: windows-latest runs-on: windows-latest runs-on: ${{ matrix.runs-on }} steps: - name: Checkout repository uses: actions/checkout@v4 - name: Setup pnpm uses: pnpm/action-setup@v2 with: version: 8 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: pnpm - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: targets: ${{ matrix.target }} # Cache rust dependencies cache: true - name: Install dependencies run: pnpm install --frozen-lockfile # Install platform dependencies for macOS - name: Install macOS dependencies if: matrix.target == 'aarch64-apple-darwin' || matrix.target == 'x86_64-apple-darwin' run: |+ brew install - rustup-init webkit2png webkit2gtk-4.0 # for older ubuntu versions openssl # install webkit2png to avoid build errors # curl -L https://github.com/Automattic/node-canvas/releases/download/v2.10.1/canvas-prebuilt-aarch64.tar.gz | tar xz # sudo mv canvas-prebuilt-aarch64/include/ /usr/local/include/ # sudo mv canvas-prebuilt-aarch64/lib/ /usr/local/lib/ # Install platform dependencies for Linux - name: Install Linux dependencies if: matrix.target == 'x86_64-unknown-linux-gnu' run: |+ sudo apt-get update sudo apt-get install -y webkit2gtk-4.0 # Install platform dependencies for Windows - name: Install Windows dependencies if: matrix.target == 'x86_64-pc-windows-msvc' run: |+ # Install openssl using scoop scoop install openssl - name: Build the application uses: tauri-apps/tauri-action@v0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: # Use the release profile for the build releaseProfile: 'release' # Use the platform-specific target package বিশুদ্ধ: ${{ matrix.target }} - name: Upload artifacts uses: actions/upload-artifact@v3 with: name: tauri-app-${{ matrix.target }} path: target/release/bundle/${{ matrix.target }}/* ``` -------------------------------- ### Turborepo Code Quality Commands Source: https://context7_llms Bash commands utilizing Turborepo to run code quality checks and formatting tasks. These commands leverage the configured Ultracite setup for linting and formatting. ```bash turbo format # Fix issues turbo lint # Check issues ``` -------------------------------- ### Tauri Autostart Plugin Usage Source: https://context7_llms TypeScript code demonstrating how to enable, disable, and check the status of the Tauri autostart plugin within a React application. This allows the app to launch automatically on system login. ```typescript import { enable, disable, isEnabled } from "@tauri-apps/plugin-autostart"; // Enable autostart await enable(); // Disable autostart await disable(); // Check if enabled const enabled = await isEnabled(); ```