### Clone Repository and Setup Source: https://github.com/f88/promidas-utils/blob/main/CONTRIBUTING.md Steps to clone the repository, set up the upstream remote, and install project dependencies using npm. ```bash git clone https://github.com//promidas-utils.git cd promidas-utils git remote add upstream https://github.com/F88/promidas-utils.git npm install ``` -------------------------------- ### Start Documentation Server (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Starts a local development server for the VitePress documentation. This allows developers to preview documentation changes in real-time during development. The server typically runs on a local port. ```bash npm run docs:dev ``` -------------------------------- ### Clone and Install Dependencies (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Clones the promidas-utils repository and installs project dependencies using npm. Requires Git and Node.js/npm to be installed. ```bash git clone https://github.com/F88/promidas-utils.git cd promidas-utils npm install ``` -------------------------------- ### Install promidas-utils Source: https://context7.com/f88/promidas-utils/llms.txt Installs the promidas-utils npm package. This is the first step to using the library in your project. ```bash npm install promidas-utils ``` -------------------------------- ### Build the Package Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Compiles the project's code to prepare it for distribution. This command should be executed to ensure there are no build errors before a release. Run from the project's root directory. ```bash npm run build ``` -------------------------------- ### Vitest Example Test Structure (TypeScript) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md An example demonstrating the structure for writing tests using Vitest. It includes nested 'describe' blocks for organizing tests by functionality and method, with individual 'it' blocks for specific test cases, including normal, edge, and error scenarios. ```typescript describe('MyClass', () => { describe('methodName()', () => { it('should handle normal case', () => { // Test implementation }); it('should handle edge case', () => { // Test implementation }); it('should throw error for invalid input', () => { // Test implementation }); }); }); ``` -------------------------------- ### Build Documentation (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Builds the VitePress documentation for production deployment. This command generates static HTML, CSS, and JavaScript files for the documentation site, which can then be hosted on a web server. ```bash npm run docs:build ``` -------------------------------- ### Run Standard and Coverage Tests Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Executes standard npm tests and tests with code coverage. Ensure all tests pass before proceeding with a release. These commands are run from the project's root directory. ```bash # Standard tests npm test # Tests with coverage npm run test:coverage ``` -------------------------------- ### Manually Update Package Version Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Allows for manual editing of the `package.json` file to update the version. After manual editing, `npm install` is required to synchronize the `package-lock.json` file. ```json { "version": "0.6.0" // Example: 0.5.0 → 0.6.0 } ``` ```bash npm install ``` -------------------------------- ### Update Package Version with npm Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Automatically updates the version in `package.json` and `package-lock.json` using `npm version`. This is the recommended method for updating versions according to Semantic Versioning. After updating, `npm install` synchronizes `package-lock.json`. ```bash # Update version automatically npm version patch --no-git-tag-version # or minor, major # This updates package.json and package-lock.json # Ensure package-lock.json is synchronized npm install ``` -------------------------------- ### Run Project Scripts (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Executes various development scripts for the Promidas-Utils project, including building, testing, formatting, linting, and documentation tasks. These commands leverage npm scripts defined in package.json. ```bash npm run build npm run typecheck npm test npm run test:coverage npm run test:watch npm run test:ui npm run format npm run format:check npm run lint npm run lint:fix npm run clean npm run docs:dev npm run docs:build npm run docs:preview ``` -------------------------------- ### Run Test Coverage with Detailed Output (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Executes tests with coverage reporting to identify uncovered lines of code. The detailed output is accessible via an HTML report. ```bash npm run test:coverage ``` -------------------------------- ### Run Tests with Vitest (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Commands to execute tests using Vitest, including running all tests, running in watch mode for development, launching the Vitest UI, and generating test coverage reports. Coverage reports are saved in the 'coverage/' directory. ```bash npm test npm run test:watch npm run test:ui npm run test:coverage ``` -------------------------------- ### Recreate Git Tag Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Provides commands to delete an existing local and remote Git tag, then create a new tag with the same name. This is useful if a tag was created incorrectly or needs to be updated. ```bash # Delete local tag git tag -d vx.y.z # Delete remote tag git push origin :refs/tags/vx.y.z # Create new tag git tag -a vx.y.z -m "Release vx.y.z" git push origin vx.y.z ``` -------------------------------- ### Commit Changes and Create Git Tag Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Stages and commits changes to `package.json`, `package-lock.json`, and `CHANGELOG.md`, then creates a signed Git tag for the release. Finally, it pushes the commits and tags to the remote repository. ```bash # Commit changes (package.json, package-lock.json, CHANGELOG.md) git add package.json package-lock.json CHANGELOG.md git commit -m "chore(release): x.y.z" # Create tag (signed, using .npmrc configuration) git tag -a vx.y.z -m "Release vx.y.z" # Push commits and tags git push origin main git push origin vx.y.z ``` -------------------------------- ### Clear Build Cache and Rebuild (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Resolves TypeScript errors after dependency updates by clearing the build cache and reinstalling dependencies. This process ensures a clean build environment. ```bash rm -rf dist node_modules npm install npm run build ``` -------------------------------- ### Perform Code Quality Checks Source: https://github.com/f88/promidas-utils/blob/main/RELEASE.md Runs linter, formatting checks, and type checking to ensure code quality. All checks must pass to maintain code standards. These commands are executed from the project's root directory. ```bash # Linter npm run lint # Formatting npm run format:check # Type checking npm run typecheck ``` -------------------------------- ### Type Checking with TypeScript (Bash) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Performs TypeScript type checking across the entire project, including source and test files, using the configuration specified in 'tsconfig.dev.json'. This command does not emit any compiled files. ```bash npm run typecheck ``` -------------------------------- ### Conventional Commits Message Format (Text) Source: https://github.com/f88/promidas-utils/blob/main/DEVELOPMENT.md Illustrates the format for commit messages following the Conventional Commits specification. It includes a mandatory type and scope, an optional subject, and optional body and footer sections for more detailed information. ```text type(scope): subject body (optional) footer (optional) ``` -------------------------------- ### Get Store State with Promidas Utils Source: https://context7.com/f88/promidas-utils/llms.txt The `getStoreState` function determines the current state of cached data based on PROMIDAS `PrototypeInMemoryStats`. It returns one of three states: 'not-stored', 'stored', or 'expired'. It handles null stats and stats with null `cachedAt` as 'not-stored'. ```typescript import { getStoreState, StoreState } from 'promidas-utils/store'; import type { PrototypeInMemoryStats } from 'promidas'; // Example stats object from PROMIDAS repository const stats: PrototypeInMemoryStats = { cachedAt: new Date('2024-01-15T10:00:00Z'), isExpired: false, count: 100, dataSizeBytes: 50000 }; const state: StoreState = getStoreState(stats); console.log(state); // Returns: 'stored' // Handle different states switch (getStoreState(stats)) { case 'not-stored': console.log('No data cached, fetching from API...'); break; case 'stored': console.log('Data is cached and valid'); break; case 'expired': console.log('Cache expired, refreshing data...'); break; } // Null stats returns 'not-stored' const emptyState = getStoreState(null); console.log(emptyState); // Returns: 'not-stored' // Stats with null cachedAt returns 'not-stored' const uncachedStats = { cachedAt: null, isExpired: false, count: 0, dataSizeBytes: 0 }; console.log(getStoreState(uncachedStats)); // Returns: 'not-stored' // Expired stats const expiredStats = { cachedAt: new Date(), isExpired: true, count: 100, dataSizeBytes: 50000 }; console.log(getStoreState(expiredStats)); // Returns: 'expired' ``` -------------------------------- ### Parse and Localize Repository Operation Failures (TypeScript) Source: https://context7.com/f88/promidas-utils/llms.txt Parses detailed snapshot operation failures and converts them into localized Japanese messages. It handles various error origins like fetcher, store, and repository, providing specific codes and HTTP statuses when available. The 'toLocalizedMessage' function offers a more efficient way to get just the localized string. ```typescript import { parseSnapshotOperationFailure, toLocalizedMessage, ParsedSnapshotOperationFailure } from 'promidas-utils/repository'; // Using parseSnapshotOperationFailure (returns full object with localizedMessage) const result = await repository.getSnapshot(prototypeId); if (!result.ok) { const parsed: ParsedSnapshotOperationFailure | null = parseSnapshotOperationFailure(result.failure); if (parsed) { console.error(parsed.localizedMessage); console.log('Error origin:', parsed.origin); // 'fetcher', 'store', 'repository', or 'unknown' console.log('Error code:', parsed.code); // Specific error code console.log('HTTP status:', parsed.status); // HTTP status code (if applicable) } } // Using toLocalizedMessage (returns only the message string, more efficient) const refreshResult = await repository.refreshSnapshot(); if (!refreshResult.ok) { const message = toLocalizedMessage(refreshResult.failure); alert(message); // Example outputs based on error type: // HTTP 401: "APIトークンが無効です。設定を確認してください。" // HTTP 404: "データが見つかりません。" // HTTP 429: "リクエスト数が制限を超えました。しばらく待ってから再試行してください。" // HTTP 500: "サーバーエラーが発生しました。" // Network error: "ネットワークエラーが発生しました。\n次のような原因が考えられます:\n- ネットワークがオフライン..." // Store capacity: "データサイズが制限を超えました。\n既存のスナップショットは保持されます。..." // Validation: "データの検証に失敗しました。データ形式が正しくありません。" } // Handling null failures const nullMessage = toLocalizedMessage(null); console.log(nullMessage); // Returns: "不明なエラーが発生しました。" // Full error handling example with UI feedback async function fetchPrototypeData(id: number): Promise { const result = await repository.getSnapshot(id); if (result.ok) { displayData(result.snapshot); } else { const parsed = parseSnapshotOperationFailure(result.failure); if (parsed?.origin === 'fetcher' && parsed.status === 401) { showTokenConfigurationDialog(); } else if (parsed?.origin === 'store' && parsed.code === 'STORE_CAPACITY_EXCEEDED') { showStorageWarning(parsed.localizedMessage); } else { showErrorToast(parsed?.localizedMessage || 'Unknown error'); } } } ``` -------------------------------- ### Configuration Management with ConfigManager Source: https://context7.com/f88/promidas-utils/llms.txt Illustrates how to use the ConfigManager to save, retrieve, and remove configuration values using local storage and environment variables. Supports saving JSON strings and includes error handling. ```typescript import { ConfigManager, EnvironmentUnavailableError } from 'promidas-utils/config'; // Using local storage for configuration const configStorage = ConfigManager.forLocalStorage('API_BASE_URL'); await configStorage.save('https://api.example.com'); if (await configStorage.has()) { const baseUrl = await configStorage.get(); // Returns: 'https://api.example.com' console.log(`API Base URL: ${baseUrl}`); } await configStorage.remove(); // Store JSON configuration const prefsStorage = ConfigManager.forLocalStorage('USER_PREFERENCES'); await prefsStorage.save(JSON.stringify({ theme: 'dark', language: 'ja' })); const prefs = JSON.parse(await prefsStorage.get() || '{}'); console.log(prefs.theme); // Returns: 'dark' // Using environment variables (read-only) const envConfig = ConfigManager.forEnv('NODE_ENV'); const environment = await envConfig.get(); if (environment === 'production') { console.log('Running in production mode'); } // Error handling try { const storage = ConfigManager.forEnv('MY_CONFIG'); } catch (error) { if (error instanceof EnvironmentUnavailableError) { console.error('Environment variables are not available'); } } ``` -------------------------------- ### Token Management with TokenManager Source: https://context7.com/f88/promidas-utils/llms.txt Demonstrates how to use the TokenManager to save, retrieve, and remove API tokens using session storage, local storage, and environment variables. Includes error handling for unavailable environments. ```typescript import { TokenManager, TOKEN_KEYS, EnvironmentUnavailableError } from 'promidas-utils/token'; // Using session storage (cleared when browser tab closes) const sessionStorage = TokenManager.forSessionStorage(TOKEN_KEYS.PROTOPEDIA_API_V2_TOKEN); await sessionStorage.save('my-secret-token'); if (await sessionStorage.has()) { const token = await sessionStorage.get(); // Returns: 'my-secret-token' console.log(`Token retrieved: ${token}`); } await sessionStorage.remove(); console.log(await sessionStorage.has()); // Returns: false // Using local storage (persists after browser closes) const localStorage = TokenManager.forLocalStorage(TOKEN_KEYS.PROTOPEDIA_API_V2_TOKEN); await localStorage.save('persistent-token'); const persistentToken = await localStorage.get(); // Returns: 'persistent-token' // Using environment variables (read-only) // Requires: PROTOPEDIA_API_V2_TOKEN environment variable to be set const envStorage = TokenManager.forEnv(TOKEN_KEYS.PROTOPEDIA_API_V2_TOKEN); const envToken = await envStorage.get(); // Returns token from process.env or null // Error handling for unavailable environments try { const storage = TokenManager.forLocalStorage(TOKEN_KEYS.PROTOPEDIA_API_V2_TOKEN); } catch (error) { if (error instanceof EnvironmentUnavailableError) { console.error('Web Storage API is not available in this environment'); } } ``` -------------------------------- ### Development Commands Source: https://github.com/f88/promidas-utils/blob/main/CONTRIBUTING.md Common npm scripts for running tests, including watch mode and coverage, and performing type checking, formatting checks, and linting. ```bash npm test npm run test:watch npm run test:coverage npm run typecheck npm run format:check npm run lint ``` -------------------------------- ### Create Feature Branch Source: https://github.com/f88/promidas-utils/blob/main/CONTRIBUTING.md Command to create a new branch for developing a feature or fix. ```bash git checkout -b feat/your-change ``` -------------------------------- ### Convert Builder Errors to Messages with Promidas Utils Source: https://context7.com/f88/promidas-utils/llms.txt The `toErrorMessage` function converts PROMIDAS builder errors into user-friendly localized Japanese messages with troubleshooting guidance. It handles `ConfigurationError`, `DataSizeExceededError`, `SizeEstimationError`, `StoreError`, and generic `Error` types. ```typescript import { PromidasRepositoryBuilder } from 'promidas'; import { toErrorMessage } from 'promidas-utils/builder'; // Handle configuration errors try { const repo = new PromidasRepositoryBuilder() .setStoreConfig({ maxDataSizeBytes: 50 * 1024 * 1024 }) // Invalid: exceeds 30 MiB limit .build(); } catch (error) { const message = toErrorMessage(error); console.error(message); // Output: // ストアの設定が無効です。 // 次を確認してください: // - maxDataSizeBytesが30 MiBを超えていないか // - 設定値の型や範囲が正しいか // // [参考情報] // エラー種別: ConfigurationError // 詳細: maxDataSizeBytes must not exceed 30 MiB } // Handle data size exceeded errors try { await repository.refreshSnapshot({ limit: 10000 }); } catch (error) { const message = toErrorMessage(error); console.error(message); // Output: // データサイズが制限を超えました。 // 既存のスナップショットは保持されます。 // 次を試してください: // - limitパラメータを減らす // - ストアのmaxDataSizeBytesを増やす // // [参考情報] // エラー種別: DataSizeExceededError // データサイズ: 2000000 バイト // 最大サイズ: 1000000 バイト // dataState: UNCHANGED } // Handle missing API token try { const repo = new PromidasRepositoryBuilder().build(); } catch (error) { console.error(toErrorMessage(error)); // Output: APIトークンが設定されていません } ``` -------------------------------- ### Standard Checks for Pull Requests Source: https://github.com/f88/promidas-utils/blob/main/CONTRIBUTING.md Executes the standard checks locally before submitting a pull request to ensure code quality and test coverage. ```bash npm run typecheck npm run format:check npm run lint npm test ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.