### Basic Application Setup Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/application/README.md Demonstrates the basic setup for running an application with modules using `Application.run()`. This example shows how to start a `WebServerModule`. ```typescript import { Application } from '@tstdl/base/application'; import { WebServerModule } from '@tstdl/base/module'; // Example module // Run the WebServerModule Application.run(WebServerModule); ``` -------------------------------- ### Getting Started with Examples Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/README.md The recommended way to begin using the project is by exploring the `examples/` directory. This directory contains practical, runnable examples that demonstrate the functionality of core modules and their integration. ```English Getting Started: The best way to get started is to explore the `examples/` directory in the repository. It contains practical, runnable examples for many of the core modules, demonstrating how they work together to build a complete application. ``` -------------------------------- ### HttpServer Setup Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Shows the basic steps to set up and run an `HttpServer` using the provided library. It includes configuring the server implementation and starting it to listen on a specified port. ```typescript import { configureNodeHttpServer, HttpServer } from '@tstdl/base/http/server'; import { Injector } from '@tstdl/base/injector'; // Register the Node.js server implementation configureNodeHttpServer(); const httpServer = Injector.resolve(HttpServer); // Start listening on port 3000 httpServer.listen(3000); ``` -------------------------------- ### Install @tstdl/base Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/README.md This snippet shows the command to install the @tstdl/base library using npm. ```bash npm install @tstdl/base ``` -------------------------------- ### Basic Setup and Injection with @tstdl/injector Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/injector/README.md Demonstrates the fundamental usage of @tstdl/injector for setting up dependency injection and injecting dependencies into classes. It covers the basic setup of an injector and how to resolve dependencies. ```TypeScript import { Injectable, Injector, inject, singleton, injectionToken } from '@tstdl/injector'; // Define a token for a configuration object const CONFIG = injectionToken<{ apiUrl: string; }>('config'); // Define a service that depends on the config @Injectable() class ApiService { private apiUrl: string; constructor(@inject(CONFIG) config: { apiUrl: string; }) { this.apiUrl = config.apiUrl; } fetchData(): string { return `Fetching data from ${this.apiUrl}`; } } // Create a root injector const rootInjector = new Injector([ // Register ApiService as a singleton singleton(ApiService), // Register the config object using useValue { provide: CONFIG, useValue: { apiUrl: 'https://api.example.com' } }, ]); // Resolve an instance of ApiService const apiService = rootInjector.resolve(ApiService); console.log(apiService.fetchData()); // Output: Fetching data from https://api.example.com // Example of property injection (requires running within an injection context) @Injectable() class AnotherService { @inject(ApiService) private apiService!: ApiService; getServiceInfo(): string { return this.apiService.fetchData(); } } // To use property injection, you need to resolve a class that uses it within an injection context const anotherService = rootInjector.resolve(AnotherService); console.log(anotherService.getServiceInfo()); // Output: Fetching data from https://api.example.com ``` -------------------------------- ### Setup @tstdl/templates Module Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/templates/README.md Configures the @tstdl/templates module by registering template providers, resolvers, and renderers. This example demonstrates setting up with in-memory templates, string resolvers, and string renderers. ```typescript import { configureTemplates } from '@tstdl/templates'; import { MemoryTemplateProvider } from '@tstdl/templates/providers'; import { StringTemplateRenderer } from '@tstdl/templates/renderers'; import { StringTemplateResolver } from '@tstdl/templates/resolvers'; // In your application's bootstrap file configureTemplates({ templateProvider: MemoryTemplateProvider, templateResolvers: [StringTemplateResolver], templateRenderers: [StringTemplateRenderer], }); ``` -------------------------------- ### Install PDF Dependencies Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/pdf/README.md Installs the necessary command-line tools required for PDF manipulation utilities like merging, page counting, and image conversion. These tools include qpdf and poppler-utils. ```bash sudo apt-get update && sudo apt-get install -y qpdf poppler-utils ``` -------------------------------- ### Start REPL Session (Node.js) Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/utils/repl.md Starts an interactive REPL session within a Node.js environment. It allows setting custom context for the REPL. Requires Node.js. ```typescript import type { ReplOptions } from 'node:repl'; import type { Record } from '#/types/index.js'; /** * Starts an interactive (repl) session (node only) * @param context context to set the repl context to */ export declare function repl(options?: ReplOptions & { context?: Record; }): Promise; ``` -------------------------------- ### API Setup and S3 Configuration Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/object-storage/README.md Provides details on the `configureS3ObjectStorage` function for setting up the S3ObjectStorageProvider and the `S3ObjectStorageProviderConfig` interface for configuring S3 connection details. ```APIDOC Setup Function configureS3ObjectStorage(config: S3ObjectStorageProviderConfig, register?: boolean): void Configures and registers the S3ObjectStorageProvider with the dependency injector. S3 Configuration S3ObjectStorageProviderConfig Property | Type | Description -- | -- | -- endpoint | string | The S3 service endpoint URL (e.g., http://localhost:9000). accessKey | string | Your S3 access key. secretKey | string | Your S3 secret key. bucket | string (optional) | The name of a single, shared bucket for all modules. Mutually exclusive with bucketPerModule. bucketPerModule | boolean (optional) | If true, each module name maps to a dedicated bucket name. Mutually exclusive with bucket. ``` -------------------------------- ### Document Management Initialization Example Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/document-management/server/services/document-management.service.md Provides a detailed TypeScript example demonstrating the initialization of document categories, types, and properties using custom enums and type definitions. This includes setting labels, parent relationships, category assignments, and property configurations for different document types. ```TypeScript import { DocumentPropertyDataType } from '#/document-management/index.js'; import type { DocumentCategoryLabels, DocumentCategoryParents, DocumentPropertyConfigurations, DocumentTypeCategories, DocumentTypeLabels, DocumentTypeProperties } from '#/document-management/server/index.js'; import { defineEnum, type EnumType } from '#/enumeration/index.js'; export const MyDocumentCategory = defineEnum('MyDocumentCategory', { Administration: 'administration', Finance: 'finance', }); type MyDocumentCategory = EnumType; export const MyCategoryParents = { [MyDocumentCategory.Administration]: null, [MyDocumentCategory.Finance]: MyDocumentCategory.Administration, } as const satisfies DocumentCategoryParents; export const MyDocumentCategoryLabels = { [MyDocumentCategory.Administration]: 'Allgemeine Verwaltung', [MyDocumentCategory.Finance]: 'Finanzen', } as const satisfies DocumentCategoryLabels; export const MyDocumentType = defineEnum('MyDocumentType', { TerminationNotice: 'termination-notice', ComplaintLetter: 'complaint-letter', IncomingInvoice: 'incoming-invoice', OutgoingInvoice: 'outgoing-invoice', }); type MyDocumentType = EnumType; export const MyDocumentTypeLabels = { [MyDocumentType.TerminationNotice]: 'Kündigungsschreiben', [MyDocumentType.ComplaintLetter]: 'Beschwerdeschreiben', [MyDocumentType.IncomingInvoice]: 'Eingangsrechnung', [MyDocumentType.OutgoingInvoice]: 'Ausgangsrechnung', } as const satisfies DocumentTypeLabels; export const MyDocumentTypeCategories = { [MyDocumentType.TerminationNotice]: MyDocumentCategory.Administration, [MyDocumentType.ComplaintLetter]: MyDocumentCategory.Administration, [MyDocumentType.IncomingInvoice]: MyDocumentCategory.Finance, [MyDocumentType.OutgoingInvoice]: MyDocumentCategory.Finance, } as const satisfies DocumentTypeCategories; export const MyDocumentProperty = defineEnum('MyDocumentProperty', { Correspondent: 'correspondent', ContractNumber: 'contract-number', Amount: 'amount', }); export type MyDocumentProperty = EnumType; export const MyDocumentPropertyConfiguration = { [MyDocumentProperty.Correspondent]: [DocumentPropertyDataType.Text, 'Korrespondent'], [MyDocumentProperty.ContractNumber]: [DocumentPropertyDataType.Text, 'Vertragsnummer'], [MyDocumentProperty.Amount]: [DocumentPropertyDataType.Decimal, 'Betrag'], } as const satisfies DocumentPropertyConfigurations; export const MyDocumentTypeProperties = { [MyDocumentType.TerminationNotice]: [MyDocumentProperty.Correspondent, MyDocumentProperty.ContractNumber], [MyDocumentType.ComplaintLetter]: [MyDocumentProperty.Correspondent], [MyDocumentType.IncomingInvoice]: [MyDocumentProperty.Correspondent, MyDocumentProperty.Amount], [MyDocumentType.OutgoingInvoice]: [MyDocumentProperty.Correspondent, MyDocumentProperty.Amount], } as const satisfies DocumentTypeProperties; ``` -------------------------------- ### Bootstrap Application with Async Function Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/application/README.md Demonstrates how to pass a configuration object with an async bootstrap function to Application.run(). This function executes before any modules start and can utilize dependency injection. ```typescript import { Application } from '@tstdl/base/application'; import { inject } from '@tstdl/base/injector'; import { Database, migrate } from '@tstdl/base/orm/server'; import { WebServerModule } from '@tstdl/base/module'; async function bootstrap(): Promise { // Bootstrap functions can use dependency injection const database = inject(Database); console.log('Running database migrations...'); await migrate(database, { migrationsFolder: './migrations' }); console.log('Migrations complete.'); } Application.run({ bootstrap }, WebServerModule); ``` -------------------------------- ### Configure Templates Function Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/templates/module.md Initializes the template module with a provided configuration. Allows for partial configuration updates. ```TypeScript /** * configure mail module */ export declare function configureTemplates(config?: Partial): void; ``` -------------------------------- ### Async Hooks Example Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/utils/README.md Demonstrates creating and using asynchronous hooks for plugin-like architectures. It shows how to register multiple handlers for an event and trigger them with context. ```typescript import { asyncHook } from '@tstdl/base/utils'; interface User { id: number; name: string; } interface UserContext { actorId: string; } async function runHookExample() { // Create a hook that passes a User object and a UserContext const onUserCreated = asyncHook(); // Register a handler to log the event onUserCreated.register((user, context) => { console.log(`[Audit Log] User ${user.name} created by ${context.actorId}.`); }); // Register another handler to send a welcome email onUserCreated.register(async (user) => { console.log(`Sending welcome email to ${user.name}...`); await new Promise(resolve => setTimeout(resolve, 100)); // simulate async op console.log('Email sent.'); }); // Trigger the hook const newUser = { id: 1, name: 'Alice' }; await onUserCreated.trigger(newUser, { actorId: 'admin-01' }); } ``` -------------------------------- ### Backoff Helper Example Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/utils/README.md Shows how to implement retry logic with exponential or linear backoff strategies using the `backoffLoop` function. It includes an example of an unreliable operation that retries until success. ```typescript import { backoffLoop } from '@tstdl/base/utils'; let attempts = 0; async function unreliableOperation(): Promise { attempts++; console.log(`Attempt ${attempts}...`); return Math.random() > 0.8; // 20% success rate } await backoffLoop(async (controller) => { const success = await unreliableOperation(); if (success) { console.log(`Succeeded after ${attempts} attempts.`); controller.break(); } else { console.log('Failed, backing off...'); controller.backoff(); } }); ``` -------------------------------- ### Application Module Export Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/application/index.md Exports the main application functionality, including starting modules and handling application shutdown. ```typescript /** * Start application modules and shutting down the app * * @module Application */ export * from './application.js'; ``` -------------------------------- ### Asynchronous Initialization with `afterResolve` Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/injector/README.md Shows how to perform asynchronous setup tasks for dependencies using the `afterResolve` lifecycle hook in @tstdl/injector, ensuring dependencies are ready before use. ```TypeScript import { Injectable, Injector, inject, singleton, Provider } from '@tstdl/injector'; class Database { private isConnected: boolean = false; async connect(): Promise { console.log('Connecting to database...'); await new Promise(resolve => setTimeout(resolve, 100)); // Simulate async operation this.isConnected = true; console.log('Database connected.'); } isConnectedStatus(): boolean { return this.isConnected; } } @Injectable() class DataService { constructor(@inject(Database) private db: Database) {} async initialize(): Promise { console.log('DataService initializing...'); await this.db.connect(); // Ensure DB is connected console.log('DataService initialized.'); } getData(): string { if (!this.db.isConnectedStatus()) { throw new Error('Database not connected!'); } return 'Some data from service'; } } // Provider definition with afterResolve hook const dbProvider: Provider = { provide: Database, useClass: Database, // afterResolve hook to perform async initialization afterResolve: async (instance) => { await instance.connect(); } }; const dataServiceProvider: Provider = { provide: DataService, useClass: DataService, // afterResolve hook for DataService initialization afterResolve: async (instance) => { await instance.initialize(); } }; async function main() { const injector = new Injector([ dbProvider, dataServiceProvider ]); console.log('Resolving DataService...'); const dataService = injector.resolve(DataService); console.log('DataService resolved. Getting data...'); console.log(dataService.getData()); } main(); /* Expected Output: Resolving DataService... Connecting to database... Database connected. DataService initializing... DataService initialized. DataService resolved. Getting data... Some data from service */ ``` -------------------------------- ### MongoKeyValueStoreProvider Class Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/key-value-store/mongo/mongo-key-value-store.provider.md Provides a KeyValueStore implementation using MongoDB. The constructor initializes the provider with a MongoKeyValueRepository, and the get method returns a KeyValueStore instance for a given module. ```typescript import type { KeyValueStore, KeyValueStoreProvider } from '#/key-value-store/index.js'; import type { StringMap } from '#/types/index.js'; import { MongoKeyValueRepository } from './mongo-key-value.repository.js'; export declare class MongoKeyValueStoreProvider implements KeyValueStoreProvider { constructor(keyValueRepository: MongoKeyValueRepository); get(module: string): KeyValueStore; } ``` -------------------------------- ### Template Module Configuration Type Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/templates/module.md Defines the structure for configuring the template module, specifying the types for template providers, resolvers, and renderers. ```TypeScript import type { Type } from '#/types/index.js'; import { TemplateProvider } from './template.provider.js'; import { TemplateRenderer } from './template.renderer.js'; import { TemplateResolver } from './template.resolver.js'; export type TemplateModuleConfig = { templateProvider: Type | undefined; templateResolvers: Type[]; templateRenderers: Type[]; }; export declare const templateModuleConfig: TemplateModuleConfig; ``` -------------------------------- ### HttpServer Class Methods Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Details the HttpServer class, an async iterable server for handling HTTP requests. Includes methods for starting and stopping the server. ```APIDOC HttpServer: abstract class listen(port: number): Promise Starts listening on the given port. close(timeout: number): Promise Stops the server gracefully within a timeout. ``` -------------------------------- ### KeyValueStoreProvider Abstract Class Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/key-value-store/key-value-store.provider.md Defines the abstract method `get` for retrieving a KeyValueStore. This class serves as a base for concrete implementations that provide specific key-value store functionalities. ```TypeScript import type { Record } from '#/types/index.js'; import type { KeyValueStore } from './key-value.store.js'; export declare abstract class KeyValueStoreProvider { abstract get>(module: string): KeyValueStore; } ``` -------------------------------- ### Elasticsearch Index Setup and Usage Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/search-index/README.md Demonstrates setting up and using the ElasticSearchIndex to index and search for Product entities. This involves initializing the index with specific configurations and performing search operations. ```Python from tstdl_context7.search_index import ElasticSearchIndex from typing import List, Optional class Product: def __init__(self, id: str, name: str, description: str): self.id = id self.name = name self.description = description # Example Usage: # Assuming Elasticsearch is running and accessible # es_index = ElasticSearchIndex[Product]( # index_name="products", # url="http://localhost:9200", # mapping={ # "properties": { # "id": {"type": "keyword"}, # "name": {"type": "text"}, # "description": {"type": "text"} # } # } # ) # async def main(): # # Index a product # product_to_index = Product(id="1", name="Laptop", description="A powerful computing device.") # await es_index.index(product_to_index) # # Search for products # results = await es_index.search(query_string="computing", fields=["name", "description"]) # print(f"Found {len(results.items)} products.") # for item in results.items: # print(f"- {item.name}: {item.description}") # import asyncio # asyncio.run(main()) ``` -------------------------------- ### Basic Browser Workflow Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/browser/README.md Demonstrates a complete browser automation workflow: launching a browser, creating a new context and page, navigating to a URL, interacting with elements using locators, and cleaning up resources. ```typescript import { BrowserService, type BrowserController } from '@tstdl/base/browser'; import { disposeAsync } from '@tstdl/base/disposable'; import { Injector } from '@tstdl/base/injector'; // Assume DI container is configured const browserService = Injector.resolve(BrowserService); // Launch a new browser instance const browser: BrowserController = await browserService.newBrowser(); try { // Create a new context and page const context = await browser.newContext(); const page = await context.newPage(); // Navigate to a website await page.navigate('https://playwright.dev/'); // Use locators to find elements const docsLink = page.getByRole('link', { name: 'Docs' }); await docsLink.click(); // Wait for the new URL await page.waitForUrl('**/docs/intro'); console.log('Navigated to docs page:', page.url()); // Find an element and get its text const title = page.getByText('Why Playwright?'); if (await title.isVisible()) { console.log('Found title element.'); } // Interact with a form element const searchInput = page.getByLabel('Search'); await searchInput.fill('locators'); await searchInput.press('Enter'); } finally { // Clean up the browser instance and all its contexts/pages await browser[Symbol.asyncDispose](); } ``` -------------------------------- ### Elasticsearch Client Setup and Index Configuration Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/search-index/README.md Configures the Elasticsearch client, defines index settings, and maps document properties for the 'products' index. It includes setting up analyzers, property types, and fields for exact matching. ```typescript import { configureElasticsearch, ElasticIndexMapping, ElasticSearchIndex, ElasticSearchIndexConfig, IndicesIndexSettings, KeywordRewriter } from '@tstdl/base/search-index/elastic'; import { Client } from '@elastic/elasticsearch'; import { Injector } from '@tstdl/base/injector'; import { Logger } from '@tstdl/base/logger'; // Entity definition class Product { id: string; name: string; description: string; price: number; inStock: boolean; } // Configure the Elasticsearch connection configureElasticsearch({ defaultOptions: { node: 'http://localhost:9200' } }); // Define index settings and mapping const productIndexSettings: IndicesIndexSettings = { analysis: { analyzer: { default: { tokenizer: 'standard', filter: ['lowercase'] } } } }; const productIndexMapping: ElasticIndexMapping = { properties: { name: { type: 'text', fields: { keyword: { type: 'keyword' } } }, description: { type: 'text' }, price: { type: 'double' }, inStock: { type: 'boolean' } } }; // Create a configuration class for your index class ProductIndexConfig extends ElasticSearchIndexConfig { constructor() { super('products'); // The name of the index in Elasticsearch } } // Create the Search Index instance const client = Injector.resolve(Client); const logger = Injector.resolve(Logger); const productSearchIndex = new ElasticSearchIndex( client, new ProductIndexConfig(), productIndexSettings, productIndexMapping, ['name'], // Fields to rewrite with ".keyword" for exact sorting/matching logger ); // Creates the index if it doesn't exist await productSearchIndex.initialize(); ``` -------------------------------- ### Example Document Management Ancillary Service Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/examples/document-management/main.md Extends the base DocumentManagementAncillaryService to provide an example implementation for resolving document collection metadata. ```ts import '#/polyfills.js'; import { DocumentManagementAuthorizationService, type DocumentCollection, type DocumentCollectionMetadata } from '#/document-management/index.js'; import { DocumentManagementAncillaryService } from '#/document-management/server/index.js'; export declare class ExampleDocumentManagementAncillaryService extends DocumentManagementAncillaryService { resolveMetadata(collections: DocumentCollection[]): DocumentCollectionMetadata[]; } ``` -------------------------------- ### Get Key-Value Pair Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/key-value-store/README.md Demonstrates the `get()` method of the `KeyValueStore` for retrieving a value associated with a given key. If the key does not exist, it returns `undefined`. The operation is asynchronous. ```typescript const theme = await userSettingsStore.get('theme'); // 'dark' | 'light' | undefined console.log(theme); // "dark" const nonExistent = await userSettingsStore.get('nonExistentKey'); console.log(nonExistent); // undefined ``` -------------------------------- ### Initialize WebServerModule Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/module/README.md Demonstrates how to import, configure, and resolve the WebServerModule from the dependency injector. Configuration is optional and can be done once at application startup. ```typescript import { WebServerModule, configureWebServerModule } from '@tstdl/base/module'; import { Injector } from '@tstdl/base/injector'; // Configure the module (optional, can be done once at application startup) configureWebServerModule({ port: 3000 }); // Resolve from injector const injector = new Injector(); const webServerModule = injector.resolve(WebServerModule); // webServerModule can now be run like any other module. ``` -------------------------------- ### spawnCommand API Summary Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/process/README.md Provides a summary of the spawnCommand function, detailing its arguments and return type. ```APIDOC spawnCommand: Arguments: command: string - The command to execute. args?: string[] - Optional array of arguments for the command. Returns: Promise - A promise that resolves with the result of the spawned command. ``` -------------------------------- ### Browser Service API Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/browser/README.md Provides an overview of the BrowserService, including configuration, launching new browsers, creating persistent contexts, and disposing of all browser resources. It also details methods for managing browser instances and contexts. ```APIDOC Configuration: configureBrowser(): void Sets up global default options for the BrowserService. Arguments: options: BrowserModuleOptions BrowserService: newBrowser(options?: NewBrowserOptions): Promise Launches a new browser instance. newPersistentContext(dataDirectory: string, browserOptions?: NewBrowserOptions, contextOptions?: NewBrowserContextOptions): Promise Launches a browser with a persistent context for saving session data. dispose(): Promise Closes all browsers and contexts created by this service. BrowserController: newContext(options?: NewBrowserContextOptions): Promise Creates a new, isolated browser context. close(): Promise Closes the browser and all its contexts. BrowserContextController: newPage(options?: NewPageOptions): Promise Creates a new page (tab) within the context. getState(): Promise Gets the storage state (cookies, localStorage). pages(): PageController[] Returns a list of all pages in the context. attachLogger(logger: Logger): void Attaches a logger to log console messages and requests. close(): Promise Closes the browser context and all its pages. ``` -------------------------------- ### Simple GET Request Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Demonstrates how to perform a simple GET request to fetch data from a specified endpoint using the HttpClient. It shows how to retrieve the response and read its body as JSON. ```typescript const response = await httpClient.get('/users'); const users = await response.body.readAsJson(); ``` -------------------------------- ### HTTP Server Request Handling Example Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Demonstrates how to set up an HTTP server and handle incoming requests asynchronously. It iterates over requests, routes them based on URL and method, and sends appropriate responses. Includes error handling for request processing. ```typescript import { HttpServer, HttpServerResponse, type HttpServerRequestContext } from '@tstdl/base/http/server'; import { Injector } from '@tstdl/base/injector'; const httpServer = Injector.resolve(HttpServer); async function main(): Promise { console.log('Server starting...'); await httpServer.listen(3000); for await (const context of httpServer) { handleRequest(context).catch((error) => { console.error('Failed to handle request', error); context.close(); }); } } async function handleRequest(context: HttpServerRequestContext): Promise { const { request, respond } = context; const { url, method } = request; if (url.pathname == '/users' && method == 'GET') { const users = [{ id: 1, name: 'John Doe' }]; await respond(new HttpServerResponse({ statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: { json: users } })); } else if (url.pathname == '/users' && method == 'POST') { const newUser = await request.body.readAsJson(); console.log('New user:', newUser); await respond(new HttpServerResponse({ statusCode: 201 })); } else if (url.pathname == '/redirect') { await respond(HttpServerResponse.redirect('/users')); } else { await respond(new HttpServerResponse({ statusCode: 404, body: { text: 'Not Found' } })); } } main(); ``` -------------------------------- ### GET Request with URL Path Parameters Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Shows how to use URL path parameters in a GET request. The `parameters` object is used to map dynamic values to placeholders in the URL, such as `:userId`. ```typescript // Maps `userId` to the URL path segment. const user = await httpClient.getJson('/users/:userId', { parameters: { userId: 'abc-123' } }); // Resulting URL: /users/abc-123 ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Illustrates two methods for adding query parameters to a GET request: using the `query` object for explicit parameter passing and the `parameters` object for automatic mapping to the URL. ```typescript // Using the `query` object const user = await httpClient.getJson('/users', { query: { id: 123 } }); // Using automatic parameter mapping const products = await httpClient.getJson('/products', { parameters: { category: 'electronics', inStock: true } }); // Resulting URL: /products?category=electronics&inStock=true ``` -------------------------------- ### Observe Touch Events with RxJS Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/dom/observation/touch-observer.md Creates an observable that emits an object containing the latest state of all touch events (start, move, end, cancel) on a specified HTML element. The emitted values are reset upon each new 'start' event. ```typescript import { type Observable } from 'rxjs'; import type { EventListenerOptions } from 'rxjs/internal/observable/fromEvent'; export type TouchEvents = { start: TouchEvent | undefined; move: TouchEvent | undefined; end: TouchEvent | undefined; cancel: TouchEvent | undefined; }; /** * Creates an observable that emits object with the latest state from all touch events. Values are reset on every new start event * @param element element to observe touches on */ export declare function observeTouch$(element: HTMLElement, options?: EventListenerOptions): Observable; ``` -------------------------------- ### Basic Process Spawning and Output Reading Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/process/README.md Demonstrates the fundamental usage of `spawnCommand` to execute a command, capture its standard output, and wait for its completion. It shows how to get the exit code after the process finishes. ```typescript import { spawnCommand } from '@tstdl/base/process'; // Spawn 'ls -la' and read its output const command = await spawnCommand('ls', ['-la']); const output = await command.readOutput(); console.log(output); // Wait for the process to finish and get its exit code const { code } = await command.wait(); console.log(`Process exited with code ${code}`); ``` -------------------------------- ### WeakRefMap Class Definition Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/data-structures/weak-ref-map.md Defines the WeakRefMap class, which extends Dictionary and implements the Map interface. It supports operations like getting the real size, checking for support, setting, getting, deleting, and iterating over entries, keys, and values. It also includes a cleanup method to remove garbage-collected entries. ```typescript import { Dictionary } from './dictionary.js'; export declare class WeakRefMap extends Dictionary> implements Map { readonly [Symbol.toStringTag] = "WeakRefMap"; /** * Provides the real size. This is slow because it requires a cleanup iteration */ get realSize(): number; static get supported(): boolean; constructor(backingMapProvider?: () => Map>); includes([key, value]: [K, V]): boolean; has(key: K): boolean; get(key: K): V | undefined; add(value: [K, V]): void; addMany(values: Iterable<[K, V]>): void; set(key: K, value: V): this; delete(key: K): boolean; /** Prune garbage collected entries */ cleanup(): void; clone(): WeakRefMap; forEach(callback: (value: V, key: K, map: WeakRefMap) => void, thisArg?: any): void; entries(): MapIterator<[K, V]>; keys(): MapIterator; values(): MapIterator; items(): MapIterator<[K, V]>; protected _clear(): void; } ``` -------------------------------- ### Context7 SDK API Documentation Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/ai/ai.service.md API reference for the Context7 SDK, detailing methods for function calls and content generation. ```APIDOC Context7Client: callFunctionsStream(options: CallFunctionsOptions): SpecializedGenerationResultGenerator> - If function declarations include handlers, they are executed as soon as a complete function call is parsed. - @param options The options for the function call request. - @returns A {@link SpecializedGenerationResultGenerator} that yields function call results. generate(request: GenerationRequest): Promise> - Generates content from the model based on a request. - This method waits for the full response from the model. For streaming, use {@link generateStream}. - @param request The generation request. - @returns A promise that resolves to the complete {@link GenerationResult}. generateStream(request: GenerationRequest): AsyncGenerator> - Generates content as a stream. - Yields partial generation results as they are received from the model. - @param request The generation request. - @returns An `AsyncGenerator` that yields {@link GenerationResult} chunks. mergeGenerationStreamItems(items: GenerationResult[], schema?: SchemaTestable): GenerationResult - Merges an array of streaming generation results into a single, consolidated result. - This is useful for combining the chunks from a streaming response into a final object. - @param items The array of {@link GenerationResult} items from a stream. - @param schema An optional schema to parse the merged JSON output. - @returns A single, merged {@link GenerationResult}. ``` -------------------------------- ### MongoQueueProvider Class Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/queue/mongo/queue.provider.md Provides a way to get a MongoQueue instance for a given name and configuration. It implements the Resolvable interface for CollectionArgument. ```typescript import type { CollectionArgument, MongoRepositoryConfig } from '#/database/mongo/index.js'; import { resolveArgumentType, type Resolvable } from '#/injector/index.js'; import { QueueProvider, type QueueConfig } from '#/queue/index.js'; import type { MongoJob } from './job.js'; import { MongoQueue } from './queue.js'; export declare class MongoQueueProvider extends QueueProvider implements Resolvable> { readonly [resolveArgumentType]: CollectionArgument; get(name: string, config?: QueueConfig): MongoQueue; } ``` -------------------------------- ### Inject and Use ObjectStorage Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/object-storage/README.md Demonstrates how to inject an ObjectStorage instance for a specific module ('product-images') and use it to upload, get, and delete objects. ```typescript import { inject } from '@tstdl/base/injector'; import { ObjectStorage } from '@tstdl/base/object-storage'; class ProductImageService { // Inject an ObjectStorage instance for the 'product-images' module. readonly #imageStorage = inject(ObjectStorage, 'product-images'); async uploadImage(productId: string, content: Uint8Array): Promise { const key = `${productId}.webp`; await this.#imageStorage.uploadObject(key, content, { contentType: 'image/webp', }); } async getImageContent(productId: string): Promise { const key = `${productId}.webp`; return this.#imageStorage.getContent(key); } async deleteImage(productId: string): Promise { const key = `${productId}.webp`; await this.#imageStorage.deleteObject(key); } } ``` -------------------------------- ### Upload Document: Initiate, Upload File, Create Record Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/document-management/README.md A three-step process to upload a document: initiate the upload to get a URL, upload the file content to that URL, and then create the document record, optionally assigning it to collections or requests. ```typescript const file = new File(['...'], 'invoice.pdf', { type: 'application/pdf' }); // 1. Initiate the upload const { uploadId, uploadUrl } = await documentManagementApi.initiateDocumentUpload({ contentLength: file.size }); // 2. Upload the file to the provided URL await fetch(uploadUrl, { method: 'PUT', body: file }); // 3. Create the document record and start the workflow // Example 1: Assign to a specific collection const document = await documentManagementApi.createDocument({ uploadId, originalFileName: file.name, assignment: { collections: 'user-collection-id-123' } }); // Example 2: Fulfill a specific document request const documentForRequest = await documentManagementApi.createDocument({ uploadId, originalFileName: file.name, assignment: { request: 'request-id-456' } }); // Example 3: Automatic assignment (AI will determine the best collection/request) const documentForAutoAssignment = await documentManagementApi.createDocument({ uploadId, originalFileName: file.name, assignment: { automatic: { target: 'request', // or 'collection' scope: ['user-collection-id-123', 'car-collection-id-789'] // collections to search within } } }); console.log('Document created:', document.id); ``` -------------------------------- ### Get Value with Default Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/key-value-store/README.md Retrieves a value from the store. If the key is not found, a specified default value is returned instead. ```typescript const language = await userSettingsStore.get('language', 'en'); console.log(language); // "en" (if 'language' was not previously set) ``` -------------------------------- ### Tstdl Core Initialization and Configuration Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/core.md Provides functions to configure the Tstdl core, including setting the production mode, defining logger configurations, and managing log levels. ```typescript import type { CancellationSignal } from './cancellation/token.js'; import { Injector } from './injector/injector.js'; import { type InjectionToken } from './injector/token.js'; import { LogLevel, Logger, type LoggerArgument } from './logger/index.js'; declare global { var tstdlLoaded: boolean | undefined; } export declare const CORE_LOGGER: InjectionToken; /** * @deprecated Usage of `getGlobalInjector` should be avoided. Use `Application` scoped injector instead. */ export declare function getGlobalInjector(): Injector; export declare function isDevMode(): boolean; export declare function isProdMode(): boolean; export declare function enableProdMode(): void; export declare function connect(name: string, connectFunction: (() => Promise), logger: Logger, cancellationSignal: CancellationSignal, maxTries?: number): Promise; export type CoreConfiguration = { production?: boolean; logger?: InjectionToken; logLevel?: LogLevel; coreLogPrefix?: string; }; export declare function configureTstdl(config?: CoreConfiguration): void; ``` -------------------------------- ### WebLockProvider Class Definition Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/lock/web/web-lock.provider.md Defines the WebLockProvider class, inheriting from LockProvider. It includes a constructor and methods for setting a prefix and getting a lock resource. ```TypeScript import type { Lock } from '#/lock/index.js'; import { LockProvider } from '#/lock/index.js'; export declare class WebLockProvider extends LockProvider { constructor(prefix?: string); prefix(prefix: string): LockProvider; get(resource: string): Lock; } ``` -------------------------------- ### Render Page as PDF Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/browser/README.md Demonstrates how to render a web page as a PDF with customizable options like format, orientation, background rendering, and margins. It uses Node.js file system promises to save the generated PDF buffer. ```typescript import { writeFile } from 'node:fs/promises'; import type { PageController } from '@tstdl/base/browser'; async function savePageAsPdf(page: PageController) { await page.navigate('https://example.com'); const pdfBuffer = await page.renderPdf({ format: 'A4', landscape: false, renderBackground: true, margin: { top: '20px', bottom: '20px' }, }); await writeFile('example.pdf', pdfBuffer); console.log('PDF saved successfully.'); } ``` -------------------------------- ### API Summary: Configuration and Client Classes Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/http/README.md Provides an overview of the API for configuring HTTP clients and servers, as well as details on client classes for making requests and handling responses. Includes methods for GET, POST, and general requests, along with response body reading capabilities. ```APIDOC ### Configuration | Function | | :--- | | **`configureHttpClient`** | `(config: HttpClientModuleConfig) => void` | Configures the global `HttpClient`, its adapter, and middleware. | | **`configureUndiciHttpClientAdapter`** | `(options?: UndiciHttpClientAdapterOptions & { register?: boolean }) => void` | Configures and optionally registers the `UndiciHttpClientAdapter`. | | **`configureNodeHttpServer`** | `(configuration?: Partial) => void` | Registers the `NodeHttpServer` as the default `HttpServer`. | ### Client Classes | Class / Method / Property | | :--- | | `HttpClient` | `class` | The main entry point for making HTTP requests. | | **`getJson`** | `(url: string, options?: HttpClientRequestOptions) => Promise` | Performs a GET request and parses the response body as JSON. | | **`postJson`** | `(url: string, options?: HttpClientRequestOptions) => Promise` | Performs a POST request and parses the response body as JSON. | | **`request`** | `(method: HttpMethod, url: string, options?: HttpClientRequestOptions) => Promise` | Performs a request with the specified method. | | `HttpClientRequest` | `class` | Represents an outgoing HTTP request. | | **`url`** | `string` | The full request URL. | | **`method`** | `HttpMethod` | The HTTP method (e.g., 'GET', 'POST'). | | **`headers`** | `HttpHeaders` | A map-like object for request headers. | | **`body`** | `HttpRequestBody | undefined` | The request body, supporting various types. | | **`abort()`** | `() => void` | Aborts the request. | | `HttpClientResponse` | `class` | Represents an incoming HTTP response. | | **`statusCode`** | `number` | The HTTP status code. | | **`headers`** | `HttpHeaders` | A map-like object for response headers. | | **`body`** | `HttpBody` | The response body handler. | | **`close()`** | `() => void` | Closes the response and releases resources. | | `HttpBody` | `class` | Provides methods to read the response body in various formats. | | **`readAsBuffer()`** | `() => Promise` | Reads the body as a buffer. | | **`readAsText()`** | `() => Promise` | Reads the body as a string. | | **`readAsJson()`** | `() => Promise` | Reads and parses the body as JSON. | | **`readAsBinaryStream()`** | `() => ReadableStream` | Reads the body as a binary stream. | ``` -------------------------------- ### ImgproxyImageService Configuration and Usage Source: https://github.com/bagbag/tstdl-context7-docs/blob/main/base/image-service/imgproxy/imgproxy-image-service.md Defines the configuration interface for the ImgproxyImageService and provides the service class for generating image URLs. It includes the service's constructor and a method to get image URLs. ```typescript import { resolveArgumentType } from '#/injector/index.js'; import type { Resolvable } from '#/injector/interfaces.js'; import { ImageService, type ImageOptions } from '../image-service.js'; export type ImgproxyImageServiceConfig = { endpoint: string; key: string; salt: string; signatureSize: number; }; export declare const IMGPROXY_IMAGE_SERVICE_CONFIG: import("#/injector/index.js").InjectionToken; export declare class ImgproxyImageService extends ImageService implements Resolvable { readonly endpoint: string; readonly [resolveArgumentType]: ImgproxyImageServiceConfig; constructor(endpoint: string, key: string, salt: string, signatureSize: number); getUrl(resourceUri: string, options?: ImageOptions): Promise; } ```