### Install and Run Development Server Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Clone the repository, install dependencies, and start the development server. The server will be accessible at http://localhost:5173/ with hot reload enabled. ```bash git clone https://github.com/choppu/prompt-base.git cd prompt-base npm install npm run dev ``` -------------------------------- ### Example: Running the Default Importer Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Example of how to import the default importer module and run its synchronization process, typically at application startup. ```typescript import * as DefaultImporter from './data/default_importer' // Run at application startup await DefaultImporter.run() // Remote prompts are now available locally ``` -------------------------------- ### Initialize PromptBase Development Environment Source: https://github.com/choppu/prompt-base/blob/master/README.md Commands to clone the repository, install dependencies, and launch the development server. ```bash #Clone and setup git clone https://github.com/choppu/prompt-base.git cd prompt-base #Install deps npm install #Start dev server npm run dev ``` -------------------------------- ### Development Server Script Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Command to start the development server using Vite. ```bash vite ``` -------------------------------- ### Initialize the App Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/00_START_HERE.md Open the database connection and start the default importer. The importer runs asynchronously in the background. ```typescript import * as DB from '@/data/db' import * as DefaultImporter from '@/data/default_importer' await DB.openDB() DefaultImporter.run() // Async import continues in background ``` -------------------------------- ### Typical Import Session Steps Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Outlines the steps for a full import of a repository with a large number of prompts on a fresh installation. ```text 1. Fetch /db.json → version: 50, exclude: [5, 15] 2. getRemoteDBVersion() → 1 → Start from version 1 3. Loop i=1 to i=50: For each i not in [5, 15]: - Fetch /db/{i}.json - Parse JSON - Convert image: atob() → Uint8Array - addPrompt(data) - setRemoteDBVersion(i + 1) 4. After loop: - purgeOutdated([5, 15]) 5. Return ``` -------------------------------- ### Example Usage of PromptGroup Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Shows how to create and iterate over a `PromptGroup`. Prompts within each group are sorted alphabetically by name. ```typescript const grouped: PromptGroup = new Map([ ['styles', [prompt1, prompt2, prompt3]], ['lighting', [prompt4, prompt5]], ['animals', [prompt6]] ]) // Iterate groups for (const [tag, promptList] of grouped) { console.log(`${tag}: ${promptList.length} prompts`) } // Get specific group const stylePrompts = grouped.get('styles') ``` -------------------------------- ### Example Usage of Search Parameters Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Demonstrates how to create and use SearchParams to query prompts. The searchString can be empty if no text search is needed. ```typescript const params: SearchParams = { searchString: 'sunset', filterTags: ['styles', 'lighting'] } const results = await DB.getPrompts(params.searchString, params.filterTags) ``` -------------------------------- ### Example Prompt Object Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Illustrates how to construct a `Prompt` object with sample data. The `id` field is optional as it's assigned by Dexie on insert. Ensure `imageData` is a `Uint8Array`. ```typescript const prompt: Prompt = { id: 5, remoteId: 42, name: 'Sunset Photography', prompts: { default: 'golden hour, warm sunset lighting, lens flare', vibrant: 'saturated colors, dramatic sky, golden sunset' }, notes: 'Works best with landscape models', tags: ['styles', 'lighting', 'photography'], image: imageData // Uint8Array } ``` -------------------------------- ### useDexieLiveQuery Example Usage Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Demonstrates how to use the useDexieLiveQuery composable to fetch and display tags from a Dexie database. It includes error handling and an initial value. ```typescript import { useDexieLiveQuery } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' export default { setup() { const allTags = useDexieLiveQuery( async () => { return await DB.getTags() }, { initialValue: new Set(), onError: (error) => console.error('Failed to load tags:', error) } ) return { allTags } } } ``` -------------------------------- ### Example Usage of PromptVariant Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Demonstrates how to create and access different prompt variants. Common keys include 'default', 'vibrant', 'realistic', 'sketch', and 'anime'. ```typescript const variants: PromptVariant = { default: 'portrait, beautiful face, soft lighting', dramatic: 'cinematic lighting, high contrast, moody atmosphere', anime: 'anime style, expressive eyes, watercolor background' } // Access variants const defaultText = variants['default'] ``` -------------------------------- ### Example Usage of Generation Parameters Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Demonstrates extracting and using generation parameters from image data. Checks if any parameters were found before accessing them. ```typescript const metadata = new IMGMetadata(imageData) const params = metadata.getGenerationParams() if (params.length > 0) { const p = params[0] console.log(`Model: ${p.model}, Steps: ${p.steps}, Seed: ${p.seed}`) } ``` -------------------------------- ### Define New Routes Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Example of how to add a new route definition to the application's router configuration in `src/router/index.ts`. ```typescript // In src/router/index.ts const router = createRouter({ history: createWebHashHistory(import.meta.env.BASE_URL), routes: [ { path: '/new-route', name: 'new-route', component: NewView } // ... ] }) ``` -------------------------------- ### Basic Database Operations Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates common database operations including opening the database, retrieving all prompts, searching by keyword, filtering by tags, getting available tags, and adding a new prompt. ```typescript import * as DB from '@/data/db' // Initialize on startup await DB.openDB() // Get all prompts const allPrompts = await DB.getPrompts() // Search const results = await DB.getPrompts('sunset') // Filter by tags const filtered = await DB.getPrompts('', ['styles', 'lighting']) // Get tags for UI const tags = await DB.getTags() // Add a prompt await DB.addPrompt({ remoteId: 999, name: 'My Prompt', prompts: { default: 'text...' }, notes: '', tags: ['custom'], image: imageData }) ``` -------------------------------- ### Get Prompts with Search Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Retrieves prompts from the database using a search term and optional tags. Ensure the DB module is imported. ```typescript import * as DB from '@/data/db' const results = await DB.getPrompts('sunset', ['styles']) ``` -------------------------------- ### Node.js Version Requirement Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Specifies the required Node.js versions for the project. Ensure your Node.js installation meets these criteria. ```json { "engines": { "node": "^20.19.0 || >=22.12.0" } } ``` -------------------------------- ### Vue Component with Reactive Query Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Shows how to use a custom hook `useDexieLiveQueryWithDeps` to create a reactive query in a Vue 3 setup function. The query updates automatically based on the `searchText` ref. ```typescript import { useDexieLiveQuery } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' import { ref } from 'vue' export default { setup() { const searchText = ref('') const prompts = useDexieLiveQueryWithDeps( searchText, async (text) => await DB.getPrompts(text), { initialValue: new Map() } ) return { prompts, searchText } } } ``` -------------------------------- ### Get All Unique Tags Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Retrieves all unique tags from the database. The result is cached for efficient access. ```typescript export const getTags = async (): Promise> ``` ```typescript const tags = await DB.getTags() // tags = Set { 'styles', 'lighting', 'effects', 'animals' } for (const tag of tags) { console.log(tag) } ``` -------------------------------- ### Get ComfyUI Workflow from Image Metadata Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Retrieves the ComfyUI workflow string if available in the image metadata. Returns a string or undefined. ```typescript .getWorkflow() ``` -------------------------------- ### Image Metadata Extraction Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md An example function that analyzes an image file to extract its dimensions and generation parameters, such as the model and positive prompt. It also checks for the presence of a ComfyUI workflow. ```typescript import IMGMetadata from '@/util/img_metadata' async function analyzeImage(file: File) { const buffer = await file.arrayBuffer() const data = new Uint8Array(buffer) const img = IMGMetadata.load(data) console.log(`Size: ${img.width}x${img.height}`) const params = img.getGenerationParams() if (params.length > 0) { console.log('Model:', params[0].model) console.log('Prompt:', params[0].positive_prompt) } const workflow = img.getWorkflow() if (workflow) { console.log('Has ComfyUI workflow') } } ``` -------------------------------- ### getRemoteDBVersion Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Retrieves the current remote database version from localStorage. Reads the remote database version from localStorage. Returns 1 as default if no version has been set, ensuring the import process starts from the beginning on first run. ```APIDOC ## getRemoteDBVersion ### Description Retrieves the current remote database version from localStorage. Reads the remote database version from localStorage. Returns 1 as default if no version has been set, ensuring the import process starts from the beginning on first run. ### Signature `export const getRemoteDBVersion = (): number` ### Parameters None ### Returns `number` - The stored version number, or 1 if not set ### Example ```typescript const currentVersion = DB.getRemoteDBVersion() console.log(`Local database is at version ${currentVersion}`) ``` ``` -------------------------------- ### Retrieve Remote Database Version Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Retrieves the remote database version from localStorage. Returns 1 as a default if no version has been set, ensuring the import process starts correctly on the first run. ```typescript export const getRemoteDBVersion = (): number ``` ```typescript const currentVersion = DB.getRemoteDBVersion() console.log(`Local database is at version ${currentVersion}`) ``` -------------------------------- ### Build and Preview Production Build Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Build the project for production and then preview the production build locally. The output will be placed in the dist/ directory. ```bash npm run build npm run preview ``` -------------------------------- ### Get Remote Database Version Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Retrieves the stored version number of the remote database. Returns a number. ```typescript getRemoteDBVersion() ``` -------------------------------- ### Preview Production Build Script Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Command to locally preview the production build of the project. ```bash vite preview ``` -------------------------------- ### run() Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Executes the full database synchronization process. It fetches remote prompt metadata, downloads new prompts incrementally, and cleans up removed prompts from the local IndexedDB. ```APIDOC ## run ### Description Executes the full database synchronization process. Fetches remote database manifest, then imports all new prompts since the last stored version. Each prompt is fetched individually, processed, and added to the local database. Prompts marked as excluded in the manifest are deleted from local storage. ### Method Asynchronous function call ### Parameters None ### Returns `Promise` — Resolves when import completes (may complete with errors suppressed) ### Example ```typescript import * as DefaultImporter from './data/default_importer' // Run at application startup await DefaultImporter.run() // Remote prompts are now available locally ``` ``` -------------------------------- ### Incremental Update Scenario Steps Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Describes the process for updating the application with new prompts when a local version already exists. ```text 1. Fetch /db.json → version: 35, exclude: [5, 15] 2. getRemoteDBVersion() → 30 → Start from version 30 3. Loop i=30 to i=35: Fetch and import prompts 30-35 (Only new prompts since last run) 4. purgeOutdated([5, 15]) (Already done if they existed locally) 5. Return ``` -------------------------------- ### Production Build Script Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Command to build the project for production, including type checking and building. ```bash run-p type-check build-only ``` -------------------------------- ### Access Database Prompts Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Demonstrates how to retrieve all prompts, search with filters, and add new prompts using the database API. ```typescript import * as DB from '@/data/db' // Get all prompts const allPrompts = await DB.getPrompts() // Search with filter const results = await DB.getPrompts('sunset', ['styles']) // Add a new prompt await DB.addPrompt({ remoteId: 999, name: 'Custom Prompt', prompts: { default: 'text...' }, notes: '', tags: ['custom'], image: imageData }) ``` -------------------------------- ### Get Generation Parameters Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/image-metadata.md Call `getGenerationParams` to extract and parse generation parameters from the image metadata. It supports multiple formats including Automatic1111, ComfyUI, and SwarmUI. ```typescript const metadata = new IMGMetadata(imageData) const params = metadata.getGenerationParams() if (params.length > 0) { const p = params[0] console.log(`Model: ${p.model}`) console.log(`Seed: ${p.seed}`) console.log(`Steps: ${p.steps}`) console.log(`Prompt: ${p.positive_prompt}`) } ``` -------------------------------- ### Initialize IndexedDB Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Initializes the IndexedDB database. Call this function to set up the database before performing other operations. ```typescript openDB() ``` -------------------------------- ### Database Initialization Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Opens the IndexedDB database with a specified schema version. ```typescript import Dexie from 'dexie'; export const db = new Dexie('PromptBaseDB'); db.version(1).stores({ prompts: '++id, remoteId, name, tags' }); export async function openDB() { await db.open(); } ``` -------------------------------- ### openDB Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Opens and initializes the IndexedDB database with the schema definition for the prompts table. This function sets up the global database instance and defines the structure for storing prompt data. ```APIDOC ## openDB ### Description Opens and initializes the IndexedDB database with the schema definition for prompts table. Creates a Dexie database named `PromptBaseDB` with version 1 and defines the `prompts` table schema with indices on `id`, `remoteId`, `name`, and `tags` (array index). ### Method `void` ### Parameters None ### Returns `void` ### Example ```typescript import * as DB from './data/db' await DB.openDB() // Database is now ready for queries ``` ``` -------------------------------- ### IMGMetadata Constructor Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/image-metadata.md Creates a new IMGMetadata instance and immediately analyzes the image. It automatically detects the image format, reads dimensions and text chunks/metadata, and parses generation parameters. Throws an error if the file format is unrecognized. ```APIDOC ## Constructor IMGMetadata ### Description Creates a new metadata parser and immediately analyzes the image. Automatically detects image format (PNG, JPEG, or WebP), reads dimensions and text chunks/metadata, and parses generation parameters. ### Method ```typescript constructor(data: Uint8Array) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (Uint8Array) - Required - Binary image file data ### Request Example ```typescript import IMGMetadata from './util/img_metadata' const fileData = new Uint8Array([...]) // Binary image data const metadata = new IMGMetadata(fileData) console.log(metadata.width, metadata.height) console.log(metadata.text) // { parameters: "...", prompt: "..." } ``` ### Response #### Success Response (200) - **IMGMetadata instance** - An instance of the IMGMetadata class. #### Response Example ```typescript // Example of metadata object properties { width: 1024, height: 1024, text: { parameters: "...", prompt: "..." } } ``` ### Errors - **Error** - with message "The file is neither a PNG, JPEG nor a WEBP" if format is unrecognized. ``` -------------------------------- ### Search with Dependencies Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Demonstrates using `useDexieLiveQueryWithDeps` to create a reactive query that depends on multiple reactive sources. The query automatically re-runs when any of its dependencies change. ```typescript import { ref } from 'vue' import { useDexieLiveQueryWithDeps } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' export default { setup() { const searchString = ref('') const filterTags = ref([]) const prompts = useDexieLiveQueryWithDeps( [searchString, filterTags], async (search: string, tags: string[]) => { return await DB.getPrompts(search, tags) }, { initialValue: new Map() } ) function updateSearch(text: string) { searchString.value = text // prompts automatically updates } function addFilter(tag: string) { filterTags.value.push(tag) // prompts automatically updates } return { prompts, searchString, filterTags, updateSearch, addFilter } } } ``` -------------------------------- ### Static Data with Reactive Display Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Shows how to use `useDexieLiveQuery` to fetch static data, such as tags, and display it reactively in a Vue template. The data is automatically updated if the underlying database changes. ```typescript export default { setup() { const tags = useDexieLiveQuery( async () => await DB.getTags(), { initialValue: new Set() } ) return { tags } } } // In template: //
{{ tag }}
``` -------------------------------- ### Run Default Importer on App Startup Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Integrates the Default Importer into the application's startup sequence. The importer runs asynchronously without awaiting, allowing the UI to mount while imports continue in the background. ```typescript async function startApp(): Promise { await DB.openDB() DefaultImporter.run() // Fire and forget createApp(App).use(router).mount('#app') } ``` -------------------------------- ### Instantiate IMGMetadata Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/image-metadata.md Create a new IMGMetadata instance by passing binary image data. The constructor automatically analyzes the image format, dimensions, and metadata. ```typescript import IMGMetadata from './util/img_metadata' const fileData = new Uint8Array([...]) // Binary image data const metadata = new IMGMetadata(fileData) console.log(metadata.width, metadata.height) console.log(metadata.text) // { parameters: "...", prompt: "..." } ``` -------------------------------- ### Load IMGMetadata using Static Method Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/image-metadata.md Use the static `load` method as a factory to create an IMGMetadata instance with the provided binary image data. ```typescript const metadata = IMGMetadata.load(fileData) ``` -------------------------------- ### Error Handling in Fetch and Import Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Demonstrates how to catch errors during the fetch and import process, logging them without throwing. ```typescript try { const resp = await fetch(REMOTE_DB_URL) // ... process } catch (err) { console.log(err) // Logs but does not throw } ``` -------------------------------- ### Usage with Multiple Dependencies Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Shows how to use useDexieLiveQueryWithDeps with multiple reactive dependencies by passing an object. The querier function receives all unpacked dependencies as arguments. ```typescript const deps = { searchString: ref('sunset'), filterTags: ref(['styles', 'lighting']) } const results = useDexieLiveQueryWithDeps( deps, async (deps: any) => { return await DB.getPrompts(deps.searchString, deps.filterTags) } ) ``` -------------------------------- ### getPrompts Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Queries prompts with optional search string and tag filtering. Results are grouped by the first tag and sorted alphabetically. ```APIDOC ## getPrompts ### Description Queries prompts with optional search string and tag filtering. Performs advanced query with dual search modes. If `filterTags` is provided, searches within those tags and then filters by name. Otherwise, searches both tags and names. Results are grouped by the first tag of each prompt and sorted alphabetically by name within each group. ### Method `async` ### Parameters #### Query Parameters - **searchString** (`string`) - Optional - Text to search in prompt names and tags - **filterTags** (`string[]`) - Optional - Array of tags to filter results (Default: `[]`) ### Returns `Promise` — A `Map` where keys are first tags and values are sorted prompt arrays. ### Example ```typescript // Get all prompts grouped by first tag const allPrompts = await DB.getPrompts() // Returns: Map { // 'styles' => [Prompt, Prompt, ...], // 'lighting' => [Prompt, ...] // } // Search by name const sunset = await DB.getPrompts('sunset') // Filter by tags and search by name const stylePrompts = await DB.getPrompts('warm', ['styles']) ``` ``` -------------------------------- ### IMGMetadata.load Static Method Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/image-metadata.md A convenience factory method to create a new IMGMetadata instance with the provided image data. ```APIDOC ## Static load IMGMetadata ### Description Factory method to create an IMGMetadata instance. ### Method ```typescript static load = (data: Uint8Array): IMGMetadata ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (Uint8Array) - Required - Binary image file data ### Request Example ```typescript const metadata = IMGMetadata.load(fileData) ``` ### Response #### Success Response (200) - **IMGMetadata instance** - A new instance of the IMGMetadata class. #### Response Example ```typescript // Example of metadata object properties { width: 1024, height: 1024, text: { parameters: "...", prompt: "..." } } ``` ``` -------------------------------- ### Build Only Script Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Command to build the project for production without performing type checking. ```bash vite build ``` -------------------------------- ### useDexieLiveQuery Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Creates a reactive database query that runs once on mount and continues to subscribe to database changes, updating the returned ref whenever the underlying data changes. It cleans up the subscription on component unmount. ```APIDOC ## useDexieLiveQuery Creates a simple reactive query without external dependencies. ```typescript export function useDexieLiveQuery( querier: () => T | Promise, options: UseDexieLiveQueryOptions = {}, ): ShallowRef> ``` **Generic Parameters:** | Parameter | Description | |-----------|-------------| | T | The result type of the query | | I | The initial value type (defaults to undefined) | **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | querier | `() => T \| Promise` | Yes | — | Async query function with no parameters | | options | `UseDexieLiveQueryOptions` | No | `{}` | Configuration object | **Returns:** `ShallowRef>` — Shallow ref containing the latest query result **Description:** Creates a static database query that runs once on mount. Useful for fetching data that doesn't need to be re-queried based on reactive changes. The query runs immediately and updates the returned ref whenever the database changes. **Behavior:** - Runs immediately on composable mount - Continues to subscribe to database changes - Updates ref whenever underlying data changes - Cleans up subscription on component unmount - Single subscription lifetime, no re-subscribes **Example:** ```typescript import { useDexieLiveQuery } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' export default { setup() { const allTags = useDexieLiveQuery( async () => { return await DB.getTags() }, { initialValue: new Set(), onError: (error) => console.error('Failed to load tags:', error) } ) return { allTags } } } ``` The `allTags` ref will be updated automatically whenever tags are added or removed from the database. ``` -------------------------------- ### Run Full Database Synchronization Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Executes the complete database synchronization process. Fetches the remote manifest, imports new prompts, and removes excluded ones. Errors are logged and suppressed. ```typescript export const run = async (): Promise ``` -------------------------------- ### Database Module API Summary Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/00_START_HERE.md Lists the available functions for interacting with the database, including opening the DB, managing prompts and tags, and handling remote synchronization versions. ```typescript openDB() getPrompts(searchString?, filterTags?) getTags() addPrompt(prompt) putPrompt(prompt) removePrompt(toRemove) purgeOutdated(ids) setRemoteDBVersion(version) getRemoteDBVersion() ``` -------------------------------- ### Basic Usage with Single Dependency Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Demonstrates how to use useDexieLiveQueryWithDeps with a single reactive dependency (searchQuery). The database query automatically re-executes when searchQuery is updated. ```typescript import { ref } from 'vue' import { useDexieLiveQueryWithDeps } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' export default { setup() { const searchQuery = ref('sunset') const prompts = useDexieLiveQueryWithDeps( searchQuery, async (query: string) => { return await DB.getPrompts(query) }, { initialValue: new Map(), onError: (error) => console.error('Search failed:', error) } ) return { prompts, searchQuery } } } ``` -------------------------------- ### Default Importer Configuration Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Defines URLs for fetching remote database manifests and prompt data. ```typescript const BASE_URL = 'https://example.com/api'; // Replace with your actual base URL export const REMOTE_DB_CONFIG = { manifest: `${BASE_URL}/db.json`, prompt: (id: string) => `${BASE_URL}/db/${id}.json` }; ``` -------------------------------- ### Per-Prompt JSON Structure Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Expected structure for individual prompt JSON files fetched from the remote database. ```json { "name": "Prompt Name", "tags": ["category", "subcategory"], "image": "base64-encoded-image", "prompt": { "variant1": "prompt text", "variant2": "variant prompt text" } } ``` -------------------------------- ### Vite Build Configuration Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Configuration for the Vite build process, including base path and path aliases. ```typescript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'path' // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue(), VueDevTools()], base: '/prompt-base/', resolve: { alias: { '@': path.resolve(__dirname, './src') } } }) ``` -------------------------------- ### Format Code Script Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Command to format the source code using Prettier. ```bash prettier --write --experimental-cli src/ ``` -------------------------------- ### Using Dexie liveQuery for Reactive Queries Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md This snippet demonstrates how to use Dexie's `liveQuery` function to create an observable query. The query automatically re-executes when relevant database tables change, enabling automatic dependency tracking. ```typescript const observable = liveQuery(() => querier(...data)) subscription = observable.subscribe({ next: (result) => { value.value = result }, error: (error) => { onError?.(error) } }) ``` -------------------------------- ### Open IndexedDB Database Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Initializes the global database instance and defines the schema for the prompts table. This function must be called before any other database operations. ```typescript import type { Prompt, PromptGroup } from '../types/Prompt' import { Dexie, type EntityTable } from 'dexie' ``` ```typescript export const openDB = (): void ``` ```typescript import * as DB from './data/db' await DB.openDB() // Database is now ready for queries ``` -------------------------------- ### Use Reactive Queries in Components Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Shows how to integrate Dexie live queries into Vue components for real-time data updates. Requires `useDexieLiveQuery` hook and database access. ```typescript import { useDexieLiveQuery } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' export default { setup() { const prompts = useDexieLiveQuery( () => DB.getPrompts(), { initialValue: new Map() } ) return { prompts } } } ``` -------------------------------- ### useDexieLiveQueryWithDeps Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Creates a reactive query that depends on external reactive dependencies. It watches a reactive dependency and automatically re-runs the database query whenever the dependency changes. The query function receives the unwrapped dependency value(s). Results are wrapped in a shallow ref for performance. ```APIDOC ## useDexieLiveQueryWithDeps ### Description Creates a reactive query that depends on external reactive dependencies. Watches a reactive dependency and automatically re-runs the database query whenever the dependency changes. The query function receives the unwrapped dependency value(s). Results are wrapped in a shallow ref for performance (inner objects aren't deeply reactive). ### Signature ```typescript export function useDexieLiveQueryWithDeps = true>( deps: any, querier: (...data: any) => T | Promise, options: UseDexieLiveQueryWithDepsOptions = {} ): ShallowRef> ``` ### Parameters #### `deps` - **Type**: `any` - **Required**: Yes - **Description**: Reactive dependency (primitive, ref, array, or object) to watch. #### `querier` - **Type**: `(...data: any) => T | Promise` - **Required**: Yes - **Description**: Async query function that receives unpacked deps as arguments. #### `options` - **Type**: `UseDexieLiveQueryWithDepsOptions` - **Required**: No - **Default**: `{}` - **Description**: Configuration object. ### Returns - **Type**: `ShallowRef>` - **Description**: Shallow ref containing the latest query result. ### Behavior - Automatically unsubscribes from previous subscription when dependency changes. - Re-subscribes immediately with new dependency value. - Cleans up subscription when component unmounts. - By default, runs immediately (`immediate: true`). ### Example ```typescript import { ref } from 'vue' import { useDexieLiveQueryWithDeps } from '@/hooks/useDexieLiveQuery' import * as DB from '@/data/db' export default { setup() { const searchQuery = ref('sunset') const prompts = useDexieLiveQueryWithDeps( searchQuery, async (query: string) => { return await DB.getPrompts(query) }, { initialValue: new Map(), onError: (error) => console.error('Search failed:', error) } ) return { prompts, searchQuery } } } ``` ### Multiple Dependencies Example ```typescript const deps = { searchString: ref('sunset'), filterTags: ref(['styles', 'lighting']) } const results = useDexieLiveQueryWithDeps( deps, async (deps: any) => { return await DB.getPrompts(deps.searchString, deps.filterTags) } ) ``` ``` -------------------------------- ### Configure Default Importer URLs Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Configures the remote URLs for the database manifest and individual prompts using Vite environment variables. These URLs are typically base paths for fetching data. ```typescript const REMOTE_DB_URL = import.meta.env.BASE_URL + '/db.json' const PROMPTS_URL = import.meta.env.BASE_URL + '/db/' ``` -------------------------------- ### putPrompt Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Adds or updates a prompt in the database. This is an upsert operation useful for syncing remote data with local storage. ```APIDOC ## putPrompt ### Description Adds or updates a prompt in the database. ### Method `putPrompt(prompt: Prompt): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prompt** (Prompt) - Required - The prompt object to add or update ### Request Example ```typescript const updatedPrompt: Prompt = { id: 5, remoteId: 42, name: 'Updated Name', prompts: { default: 'new prompt text' }, notes: 'Updated notes', tags: ['updated'], image: new Uint8Array([...]) } await DB.putPrompt(updatedPrompt) ``` ### Response #### Success Response (200) - **void** - Resolves when the operation completes #### Response Example None provided. ``` -------------------------------- ### Vue Router Configuration Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Sets up the Vue Router for the application using hash-based history. Defines the routes for different views within the application, including home, about, metadata viewer, and add prompt forms. ```typescript const router = createRouter({ history: createWebHashHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: HomeView }, { path: '/about', name: 'about', component: AboutView }, { path: '/metadata-viewer', name: 'metadata-viewer', component: MetadataViewer }, { path: '/add-prompt', name: 'add-prompt', component: AddPromptView }, ], }) ``` -------------------------------- ### Data Import Logic Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Fetches remote data, adds new prompts to the database, and purges outdated entries. ```typescript import { db, openDB } from './db'; import { REMOTE_DB_CONFIG } from './default_importer'; export class DefaultImporter { static async run() { await openDB(); const lastVersion = localStorage.getItem('dbVersion') || '0'; const manifest = await fetch(REMOTE_DB_CONFIG.manifest).then(res => res.json()); if (manifest.version > lastVersion) { // Download new prompts for (const promptMeta of manifest.prompts) { if (promptMeta.id > lastVersion) { const promptData = await fetch(REMOTE_DB_CONFIG.prompt(promptMeta.id)).then(res => res.json()); await db.prompts.add(promptData); } } localStorage.setItem('dbVersion', manifest.version); } // Purge outdated prompts await db.prompts.where('id').noneOf(manifest.prompts.map((p: any) => p.id)); } } ``` -------------------------------- ### Live Query Hook Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/README.md Composable hook for creating live queries to the IndexedDB using Dexie. ```typescript import { db } from '@/data/db'; import { liveQuery } from 'dexie'; import { useObservable } from '@vueuse/rxjs'; import { shallowRef, computed } from 'vue'; export function useDexieLiveQuery(query: () => Promise) { const observable = liveQuery(query); const data = useObservable(observable); const error = shallowRef(null); observable.catch(err => { error.value = err; return false; // Suppress error }); const result = computed(() => data.value); return { result, error }; } export function useDexieLiveQueryWithDeps(query: () => Promise, dependencies: Ref) { const observable = liveQuery(() => { // Re-run query when dependencies change dependencies.value; return query(); }); // ... rest of the hook similar to useDexieLiveQuery ``` -------------------------------- ### Remote DB Manifest Structure Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Expected structure for the remote database manifest JSON file, including version and excluded IDs. ```json { "version": 42, "exclude": [1, 5, 10] } ``` -------------------------------- ### Add New Prompt Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Adds a new prompt to the database. This operation is asynchronous and returns a Promise. ```typescript addPrompt(p) ``` -------------------------------- ### Define Search Parameters Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Defines the structure for searching and filtering prompts. Use this to parameterize database queries. ```typescript export interface SearchParams { searchString: string filterTags: string[] } ``` -------------------------------- ### addPrompt Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Adds a new prompt to the database. This function is used to insert new prompt objects into the `prompts` table, ensuring that each prompt has a unique `remoteId`. ```APIDOC ## addPrompt ### Description Adds a new prompt to the database. Inserts a new prompt into the `prompts` table. The prompt must have a unique `remoteId`. If a prompt with the same ID already exists, this operation will fail. ### Method `async (prompt: Prompt): Promise` ### Parameters #### Request Body - **prompt** (`Prompt`) - Required - The prompt object to add to the database ### Returns `Promise` — Resolves when the prompt is added ### Example ```typescript import * as DB from './data/db' const newPrompt: Prompt = { remoteId: 101, name: 'Sunset Effect', prompts: { default: 'orange sky, warm lighting' }, notes: 'Creates warm sunset atmosphere', tags: ['styles', 'lighting'], image: new Uint8Array([...]) } await DB.addPrompt(newPrompt) ``` ``` -------------------------------- ### Data Transformation to Local Prompt Format Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/default-importer.md Transforms remote prompt JSON data into the local Prompt format for IndexedDB storage. ```typescript { remoteId: i, name: prompt.name, prompts: prompt.prompt, notes: '', tags: prompt.tags, image: Uint8Array.from(atob(prompt.image), c => c.charCodeAt(0)) } ``` -------------------------------- ### Default Importer Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Handles remote database synchronization and incremental import processes. ```APIDOC ## Default Importer ### Description Manages the synchronization of the remote database and performs incremental imports. ### Function - `run()`: Executes the full database synchronization process. ``` -------------------------------- ### Add or Update Prompt Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Adds a new prompt or updates an existing one based on the provided prompt object. Returns a Promise. ```typescript putPrompt(p) ``` -------------------------------- ### Use Reactive Database Query in Vue Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Fetches prompts reactively, updating the UI when the database changes. Uses the useDexieLiveQuery hook. ```typescript import { useDexieLiveQuery } from '@/hooks/useDexieLiveQuery' const prompts = useDexieLiveQuery(() => DB.getPrompts()) ``` -------------------------------- ### Vite Build Configuration Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/configuration.md Configures the Vite build tool for the Vue 3 application. Sets the public base path, includes necessary plugins, and defines path aliases for source imports. ```typescript export default defineConfig({ base: '/prompt-base/', plugins: [vue(), vueDevTools()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)), }, }, }) ``` -------------------------------- ### Dexie Composables Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Vue 3 composition functions for creating reactive database queries, with RxJS integration. ```APIDOC ## Dexie Composables ### Description Provides Vue 3 composition functions for reactive database queries using Dexie, with RxJS support. ### Functions - `useDexieLiveQuery(querier, options)`: A static reactive query composable. - `useDexieLiveQueryWithDeps(deps, querier, options)`: A reactive query composable that depends on specified dependencies. ``` -------------------------------- ### Retrieve All Unique Tags Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Fetches all unique tags present in the prompt database. Returns a Promise that resolves to a Set of strings. ```typescript getTags() ``` -------------------------------- ### Error Handling in Live Query Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Demonstrates how to implement error handling for a Dexie live query using the `onError` callback. This allows for logging errors or dispatching them to an error tracking service. ```typescript const { value: data, value: error } = useDexieLiveQuery( async () => { return await DB.getPrompts() }, { initialValue: new Map(), onError: (error: any) => { console.error('Database query failed:', error) // Could dispatch to error tracking service } } ) ``` -------------------------------- ### Dependency-Driven Reactive Dexie Query Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md A composable hook for performing reactive queries on Dexie.js databases that are driven by a list of dependencies. It returns a ShallowRef containing the query result. ```typescript useDexieLiveQueryWithDeps(d, q, o) ``` -------------------------------- ### Query Prompts with Filtering Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Queries prompts with optional search string and tag filtering. Results are grouped by the first tag and sorted alphabetically. ```typescript export const getPrompts = async ( searchString?: string, filterTags: string[] = [] ): Promise ``` ```typescript // Get all prompts grouped by first tag const allPrompts = await DB.getPrompts() // Returns: Map { // 'styles' => [Prompt, Prompt, ...], // 'lighting' => [Prompt, ...] // } // Search by name const sunset = await DB.getPrompts('sunset') // Filter by tags and search by name const stylePrompts = await DB.getPrompts('warm', ['styles']) ``` -------------------------------- ### Type Definitions Summary Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/00_START_HERE.md Lists the primary TypeScript type definitions used within the project for prompts, search parameters, and generation configurations. ```typescript Prompt PromptVariant PromptGroup SearchParams GenerationParams ``` -------------------------------- ### Query the Database Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/00_START_HERE.md Retrieve all prompts or perform a filtered search. The search can be narrowed by keywords and specific categories. ```typescript const allPrompts = await DB.getPrompts() const searchResults = await DB.getPrompts('sunset', ['styles']) ``` -------------------------------- ### IMGMetadata.getWorkflow Method Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/image-metadata.md Retrieves the ComfyUI workflow as a JSON string if it is present in the image metadata. ```APIDOC ## public getWorkflow IMGMetadata ### Description Retrieves the ComfyUI workflow if present in the image metadata. ### Method ```typescript public getWorkflow = (): string | undefined ``` ### Parameters None ### Request Example ```typescript const metadata = new IMGMetadata(imageData) const workflow = metadata.getWorkflow() if (workflow) { const workflowObj = JSON.parse(workflow) console.log(Object.keys(workflowObj)) // Node IDs } ``` ### Response #### Success Response (200) - **string | undefined** - JSON string of the ComfyUI workflow, or undefined if not found. #### Response Example ```json { "1": { "inputs": { ... }, "class_type": "KSampler", "..." } } ``` ``` -------------------------------- ### Define PromptGroup Type Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/types.md Represents grouped prompts organized by tag. This is the return type for `DB.getPrompts()`, mapping tag strings to arrays of prompts. ```typescript export type PromptGroup = Map ``` -------------------------------- ### UseDexieLiveQueryOptions Type Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Defines options for the useDexieLiveQuery composable, including error handling and initial values. ```typescript type UseDexieLiveQueryOptions = { onError?: (error: any) => void initialValue?: I } ``` -------------------------------- ### Query Prompts with Filtering Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Queries the database for prompts, supporting optional search strings and tag filtering. Returns a Promise resolving to a PromptGroup. ```typescript getPrompts(search?, tags?) ``` -------------------------------- ### Static Reactive Dexie Query Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md A composable hook for performing static reactive queries on Dexie.js databases. It returns a ShallowRef containing the query result. ```typescript useDexieLiveQuery(q, opts) ``` -------------------------------- ### UseDexieLiveQueryWithDepsOptions Type Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/dexie-composables.md Defines options for the useDexieLiveQueryWithDeps composable, including error handling, initial values, and Vue watch options. ```typescript type UseDexieLiveQueryWithDepsOptions = { onError?: (error: any) => void initialValue?: I } & WatchOptions ``` -------------------------------- ### getTags Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Retrieves all unique tags from all prompts in the database. The result is cached for efficient repeated access. ```APIDOC ## getTags ### Description Retrieves all unique tags from all prompts in the database. ### Method `async` ### Parameters None ### Returns `Promise>` — A set of all unique tag strings. ### Example ```typescript const tags = await DB.getTags() // tags = Set { 'styles', 'lighting', 'effects', 'animals' } for (const tag of tags) { console.log(tag) } ``` ``` -------------------------------- ### Database Operations Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/DOCUMENTATION_INDEX.md Functions for interacting with the core data persistence layer, including database initialization, prompt management, tag retrieval, and querying. ```APIDOC ## Database Operations ### Description Provides functions to manage prompts and tags within the PromptBase database. ### Functions - `openDB()`: Initializes the database and its schema. - `addPrompt(prompt)`: Inserts a new prompt into the database. - `putPrompt(prompt)`: Adds or updates an existing prompt. - `removePrompt(toRemove)`: Deletes a prompt by its object or ID. - `getTags()`: Retrieves all unique tags as a Set. - `getPrompts(searchString?, filterTags?)`: Queries prompts with optional search and tag filtering. - `purgeOutdated(ids)`: Deletes prompts based on a provided list of remote IDs. - `setRemoteDBVersion(version)`: Stores the remote database version in localStorage. - `getRemoteDBVersion()`: Retrieves the stored remote database version from localStorage. ``` -------------------------------- ### Add New Prompt to Database Source: https://github.com/choppu/prompt-base/blob/master/_autodocs/api-reference/database.md Inserts a new prompt into the 'prompts' table. Ensure the prompt object has a unique 'remoteId' as duplicates will cause the operation to fail. ```typescript export const addPrompt = async (prompt: Prompt): Promise ``` ```typescript import * as DB from './data/db' const newPrompt: Prompt = { remoteId: 101, name: 'Sunset Effect', prompts: { default: 'orange sky, warm lighting' }, notes: 'Creates warm sunset atmosphere', tags: ['styles', 'lighting'], image: new Uint8Array([...]) } await DB.addPrompt(newPrompt) ```