### Install process-warning Source: https://github.com/fastify/process-warning/blob/main/README.md Install the process-warning package using npm. ```bash npm i process-warning ``` -------------------------------- ### Set Multiple Node.js Options via NODE_OPTIONS Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md The NODE_OPTIONS environment variable allows setting multiple Node.js options. This example combines --throw-deprecation and --trace-deprecation. ```bash NODE_OPTIONS="--throw-deprecation --trace-deprecation" node app.js ``` -------------------------------- ### Node.js CLI Flag Interactions with Deprecation Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createDeprecation.md Illustrates how Node.js CLI flags modify the behavior of deprecation warnings. These examples show normal emission, throwing errors, suppressing warnings, and including stack traces. ```bash # Normal behavior - warning is emitted to stderr node app.js # Output: (node:12345) DeprecationWarning: Feature will be removed in version 2.0 # Throw instead of warn node --throw-deprecation app.js # Output: Error: Feature will be removed in version 2.0 # Suppress all deprecations node --no-deprecation app.js # Output: (no warning) # Include stack trace node --trace-deprecation app.js # Output: (node:12345) DeprecationWarning: Feature will be removed in version 2.0 # at DeprecationWarning [as constructor] (node:internal/...) ``` -------------------------------- ### Validate Configuration at Application Startup Source: https://github.com/fastify/process-warning/blob/main/_autodocs/errors.md Wrap warning creation in a startup validation step to ensure all configurations are valid before the application proceeds. This prevents runtime errors due to invalid warning definitions. ```javascript const { createWarning } = require('process-warning') function initializeWarnings(config) { const warnings = {} try { warnings.database = createWarning(config.database) warnings.api = createWarning(config.api) warnings.auth = createWarning(config.auth) } catch (error) { console.error('Invalid warning configuration:', error.message) process.exit(1) } return warnings } const warnings = initializeWarnings({ database: { name: 'DBWarning', code: 'DB_001', message: 'Connection timeout' }, api: { name: 'APIWarning', code: 'API_001', message: 'Rate limit exceeded' }, auth: { name: 'AuthWarning', code: 'AUTH_001', message: 'Invalid token' } }) ``` -------------------------------- ### Listening for Process Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md Demonstrates how to listen for generic 'warning' events emitted by Node.js's `process` object. This allows you to capture and handle custom warnings created with `createWarning`. ```javascript const { createWarning } = require('process-warning') const warn = createWarning({ name: 'AppWarning', code: 'APP_001', message: 'Application warning' }) // Listen for warnings process.on('warning', (warning) => { console.log('Warning:', warning.message) console.log('Code:', warning.code) console.log('Name:', warning.name) }) warn() // Logs: Warning: Application warning, Code: APP_001, Name: AppWarning ``` -------------------------------- ### Multi-parameter Interpolation for Warning Messages Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Demonstrates how to use the 'format' method with multiple parameters to construct complex warning messages. It shows how parameters are interpolated sequentially. ```javascript const warn = createWarning({ name: 'ValidationWarning', code: 'VAL_001', message: 'Field "%s" expected %s but got %s' }) // One parameter warn.format('age') // Output: 'Field "age" expected %s but got %s' // Two parameters warn.format('age', 'number') // Output: 'Field "age" expected number but got %s' // Three parameters warn.format('age', 'number', 'string') // Output: 'Field "age" expected number but got string' // Emit with parameters warn('age', 'number', 'string') ``` -------------------------------- ### Basic Warning Creation and Emission Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md Demonstrates how to create a basic warning, emit it, check its emitted status, and reset it for re-emission. By default, warnings are only emitted once. ```javascript const { createWarning } = require('process-warning') const myWarning = createWarning({ name: 'MyAppWarning', code: 'MYAPP_001', message: 'This is a deprecation notice' }) // Emit the warning myWarning() // Subsequent calls do nothing (by default) myWarning() // No effect - already emitted // Check if emitted console.log(myWarning.emitted) // true // Reset to allow re-emission myWarning.emitted = false myWarning() // Emits again ``` -------------------------------- ### Create Warning with Options Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md Use this to create a warning instance with required name, code, message, and optional unlimited flag. ```javascript const warn = createWarning({ name: 'MyWarning', code: 'APP_001', message: 'Hello %s', unlimited: false }) ``` -------------------------------- ### Create a Basic Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Use `createWarning` to define and instantiate a custom warning object. Call the returned function to emit the warning. ```javascript const { createWarning } = require('process-warning') const warn = createWarning({ name: 'MyWarning', code: 'MY_001', message: 'Something is deprecated' }) warn() // Emits once ``` -------------------------------- ### Listen for Deprecation Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createDeprecation.md Demonstrates how to listen for 'warning' events on the process object and filter for 'DeprecationWarning' instances. This allows for custom handling of deprecation notices. ```javascript const { createDeprecation } = require('process-warning') const warning = createDeprecation({ code: 'FEATURE_DEPRECATED', message: 'Feature will be removed in version 2.0' }) process.on('warning', (warning) => { if (warning.name === 'DeprecationWarning') { console.error('Deprecation detected:', warning.message) } }) warning() ``` -------------------------------- ### WarningOptions Source: https://github.com/fastify/process-warning/blob/main/_autodocs/types.md Configuration options for createWarning(). ```APIDOC ## WarningOptions ### Description Configuration options for the `createWarning()` function. ### Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | `name` | `string` | Yes | The warning name (e.g., `'MyAppWarning'`) | | `code` | `string` | Yes | The warning code identifier (e.g., `'APP_001'`) | | `message` | `string` | Yes | The warning message template with optional `%s` placeholders | | `unlimited` | `boolean` | No | If `true`, emit every time. Default is `false` (emit once). | ### Type Definition ```typescript type WarningOptions = { name: string; code: string; message: string; unlimited?: boolean; } ``` ``` -------------------------------- ### Handle Invalid Warning Configuration Source: https://github.com/fastify/process-warning/blob/main/_autodocs/INDEX.md Demonstrates how to catch errors that occur during the creation of a warning due to invalid parameter configurations. It checks for specific error messages. ```javascript const { createWarning } = require('process-warning') try { const warn = createWarning({ name: 'MyWarning', code: 'CODE', message: 'Hello' }) } catch (error) { if (error.message.includes('must not be empty')) { console.error('Invalid configuration:', error.message) } } ``` -------------------------------- ### Emit Process Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/INDEX.md Demonstrates the basic structure for emitting a warning using Node.js's process.emitWarning function with a formatted message, warning name, and warning code. ```javascript process.emitWarning( formattedMessage, // e.g., "Field email is invalid" warningName, // e.g., "MyWarning" warningCode // e.g., "MY_001" ) ``` -------------------------------- ### Create and Emit a Basic Warning Source: https://github.com/fastify/process-warning/blob/main/README.md Use `createWarning` to define a warning with a name, code, and message, then emit it with arguments for interpolation. ```javascript const { createWarning, createDeprecation } = require('process-warning') const warning = createWarning({ name: 'ExampleWarning', code: 'EXP_WRN_001', message: 'Hello %s', unlimited: true }) warning('world') ``` -------------------------------- ### Include Stack Trace with Deprecation Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Use the --trace-deprecation CLI flag to include a full stack trace with each DeprecationWarning emission. ```bash node --trace-deprecation app.js ``` -------------------------------- ### Warning Function Usage Source: https://github.com/fastify/process-warning/blob/main/README.md Demonstrates how to use the warning function returned by `createWarning` or `createDeprecation` to emit warnings and manage their state. ```APIDOC ## Warning Function Usage ### Description The function returned by `createWarning` or `createDeprecation` can be invoked to emit a warning. It also exposes properties for managing the warning's state, such as whether it has been emitted. ### Parameters #### Path Parameters - **[, a [, b [, c]]]`** (any) - Optional - Parameters for string interpolation in the warning message. ### Request Example ```javascript const { createWarning } = require('process-warning') const FST_ERROR_CODE = createWarning({ name: 'MyAppWarning', code: 'FST_ERROR_CODE', message: 'Hello %s' }) console.log(FST_ERROR_CODE.emitted) // false FST_ERROR_CODE('world') console.log(FST_ERROR_CODE.emitted) // true // Example of an unlimited warning const UNLIMITED_WARNING = createWarning({ name: 'UnlimitedWarning', code: 'UNL_WRN_001', message: 'This warning can be repeated: %s', unlimited: true }) UNLIMITED_WARNING('first time') // emitted UNLIMITED_WARNING('second time') // emitted again // Example of manually setting emitted state const FST_ERROR_CODE_2 = createWarning('MyAppWarning', 'FST_ERROR_CODE_2', 'Hello %s') FST_ERROR_CODE_2.emitted = true FST_ERROR_CODE_2('world') // will not be emitted because it is not unlimited and already marked as emitted ``` ### Response #### Success Response (200) - **emitted** (boolean) - A property indicating whether the warning has been emitted. Can be manually set to true to suppress future emissions of non-unlimited warnings. ``` -------------------------------- ### Import via Module Property Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Access the default export functionality through the `processWarning` property of the module. ```javascript // Module property const processWarning = require('process-warning').processWarning // Same as default export ``` -------------------------------- ### Formatting a Warning Message Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Demonstrates how to use the format method of a WarningItem to create a formatted message string with interpolation values. ```javascript const warn = createWarning({ name: 'TestWarning', code: 'TEST_001', message: 'Value is %s and timeout is %s' }) const formatted = warn.format('invalid', 5000) console.log(formatted) // Output: "Value is invalid and timeout is 5000" ``` -------------------------------- ### Import Core Functions Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Import the `createWarning` and `createDeprecation` functions from the `process-warning` library. These are the primary tools for generating warnings and deprecations. ```javascript const { createWarning, createDeprecation } = require('process-warning') ``` -------------------------------- ### Create and Emit a Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Demonstrates creating a WarningItem and emitting it. The warning is emitted only once by default. You can reset the 'emitted' property to emit again. ```javascript const warn = createWarning({ name: 'AppWarning', code: 'APP_001', message: 'Warning: %s' }) // First call - emits warn('first') // Emits "Warning: first", emitted = true // Second call - does nothing (already emitted) warn('second') // No effect, emitted is still true // Reset and re-emit warn.emitted = false warn('third') // Emits "Warning: third", emitted = true ``` -------------------------------- ### Configuration Object Pattern for Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Store warning configurations in an array of objects and dynamically create warning constructors. This pattern is effective for managing a large number of warnings with consistent structures. ```javascript const { createWarning } = require('process-warning') const warningConfigs = [ { name: 'CacheWarning', code: 'CACHE_MISS', message: 'Cache miss for key "%s"', unlimited: true }, { name: 'PerformanceWarning', code: 'SLOW_OPERATION', message: 'Operation took %s ms (threshold: %s ms)', unlimited: true }, { name: 'ValidationWarning', code: 'INVALID_INPUT', message: 'Invalid input: %s' } ] const warnings = {} warningConfigs.forEach(config => { const key = config.code.toLowerCase() warnings[key] = createWarning(config) }) module.exports = warnings ``` -------------------------------- ### Centralize Warning Definitions in a Module Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Create a dedicated module to define and export all warning constructors. This promotes reusability and organization across your project. ```javascript // warnings.js const { createWarning, createDeprecation } = require('process-warning') module.exports = { database: createWarning({ name: 'DatabaseWarning', code: 'DB_CONNECTION_TIMEOUT', message: 'Database connection timeout after %s ms' }), api: createWarning({ name: 'APIWarning', code: 'API_RATE_LIMIT', message: 'Rate limit exceeded: %s requests per minute', unlimited: true // Emit every time }), auth: createDeprecation({ code: 'AUTH_TOKEN_FORMAT', message: 'Token format "%s" is deprecated, use "%s" instead' }) } ``` ```javascript const warnings = require('./warnings') warnings.database('5000') warnings.api('100') warnings.auth('JWT', 'Bearer') ``` -------------------------------- ### Create and Emit a Warning with Code Source: https://github.com/fastify/process-warning/blob/main/README.md Define a warning with a specific name and code, then emit it without arguments. ```javascript const { createWarning } = require('process-warning') const FST_ERROR_CODE = createWarning({ name: 'MyAppWarning', code: 'FST_ERROR_CODE', message: 'message' }) FST_ERROR_CODE() ``` -------------------------------- ### Importing Default Export Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md Import the default export which contains both createWarning and createDeprecation functions. ```javascript const processWarning = require('process-warning') // or const processWarning = require('process-warning').default ``` -------------------------------- ### Emitting Warnings with process.emitWarning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Shows how WarningItem uses `process.emitWarning` to emit warnings with a formatted message, name, and code. This allows warnings to be captured by `process.on('warning', handler)` and controlled by Node.js flags. ```javascript process.emitWarning( formatted_message, // Result of format(a, b, c) name, // e.g., 'MyAppWarning' code // e.g., 'APP_001' ) ``` -------------------------------- ### Create Warnings at Module Load Time Source: https://github.com/fastify/process-warning/blob/main/_autodocs/errors.md Define warnings during module initialization to catch validation errors immediately. Creating warnings inside functions delays error detection. ```javascript const { createWarning } = require('process-warning') // Bad: Creating inside functions delays error detection function createMyWarning() { return createWarning({ name: 'MyWarning', code: 'CODE', message: 'Hello' }) } // Good: Create at module level to catch errors immediately const myWarning = createWarning({ name: 'MyWarning', code: 'CODE', message: 'Hello' }) ``` -------------------------------- ### Listen to Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Attach a listener to the `process.on('warning', ...)` event to capture and process all emitted warnings. This allows for centralized handling of warning events. ```javascript process.on('warning', (warning) => { console.log(warning.message) console.log(warning.code) console.log(warning.name) }) const warn = createWarning({ name: 'AppWarning', code: 'APP_001', message: 'Test' }) warn() // Triggers listener ``` -------------------------------- ### Import Named Exports Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Import the `createWarning` and `createDeprecation` functions directly from the 'process-warning' module. ```javascript // Named exports const { createWarning, createDeprecation } = require('process-warning') ``` -------------------------------- ### Testing Warning Emission with `emitted` Property Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Demonstrates how to use the `emitted` property of a WarningItem instance for testing. It shows how to check if a warning has been emitted, simulate the emission, and reset the `emitted` status for subsequent tests. ```javascript const warn = createWarning({ name: 'TestWarning', code: 'TEST_001', message: 'Test message' }) // Before test assert.strictEqual(warn.emitted, false) // Simulate warning warn() // Verify it was emitted assert.strictEqual(warn.emitted, true) // Reset for next test warn.emitted = false ``` -------------------------------- ### Emit Warnings Every Time (Unlimited Mode) Source: https://github.com/fastify/process-warning/blob/main/_autodocs/INDEX.md Set `unlimited: true` in the options to make warnings emit on every call, bypassing the default deduplication behavior. ```javascript const warn = createWarning({ message: 'Event: %s', unlimited: true }) warn('click') // Emits warn('hover') // Emits ``` -------------------------------- ### Create and Emit an Unlimited Warning Source: https://github.com/fastify/process-warning/blob/main/README.md Define a warning with the `unlimited: true` option to allow it to be emitted multiple times. ```javascript const { createWarning } = require('process-warning') const FST_ERROR_CODE = createWarning({ name: 'MyAppWarning', code: 'FST_ERROR_CODE', message: 'Hello %s', unlimited: true }) FST_ERROR_CODE('world') // will be emitted FST_ERROR_CODE('world') // will be emitted again ``` -------------------------------- ### Suppress Process Warnings in JavaScript Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Demonstrates how to create and emit a warning using the 'process-warning' library. If NODE_NO_WARNINGS is set, the warning will not be output. ```javascript const { createWarning } = require('process-warning') const warn = createWarning({ name: 'MyWarning', code: 'TEST_001', message: 'This is a test' }) // If NODE_NO_WARNINGS=1, this will not produce output warn() ``` -------------------------------- ### Warning with String Interpolation Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md Shows how to create a warning with a message that uses string interpolation. Parameters passed to the warning function will be used to format the message. It also demonstrates how to format the message without emitting it. ```javascript const { createWarning } = require('process-warning') const configWarning = createWarning({ name: 'ConfigWarning', code: 'CFG_INVALID', message: 'Configuration option "%s" with value "%s" is deprecated' }) // Emit with interpolation values configWarning('apiKey', 'secret123') // Message sent to process: 'Configuration option "apiKey" with value "secret123" is deprecated' // Format without emitting const formatted = configWarning.format('timeout', '5000') console.log(formatted) // Output: 'Configuration option "timeout" with value "5000" is deprecated' ``` -------------------------------- ### WarningItem Format Method Signature Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Shows the signature for the format method, which allows previewing a warning message without emitting it. ```javascript format(a?: any, b?: any, c?: any): string ``` -------------------------------- ### Create a Custom Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Use this snippet to create a custom warning with a specific name, code, message, and emission behavior. The 'unlimited' option controls whether the warning emits every time or only once. ```javascript const { createWarning } = require('process-warning') const config = { name: 'AppWarning', code: 'APP_DEPRECATED', message: 'This feature is deprecated and will be removed in v2.0', unlimited: false // Optional, default is false } const warn = createWarning(config) ``` -------------------------------- ### Environment-Specific Warning Configuration Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Configure warning behavior, such as unlimited emissions, based on the current environment. This is useful for enabling more verbose warnings during development. ```javascript const { createWarning } = require('process-warning') const isDevelopment = process.env.NODE_ENV === 'development' const warn = createWarning({ name: 'AppWarning', code: 'APP_DEBUG', message: 'Debug mode: %s', unlimited: isDevelopment // Unlimited in dev, once in prod }) ``` -------------------------------- ### Handle Missing Warning Name Source: https://github.com/fastify/process-warning/blob/main/_autodocs/errors.md Catch the error when the 'name' parameter is missing for createWarning. Ensure 'name' is provided to avoid this error. ```javascript const { createWarning } = require('process-warning') try { createWarning({ code: 'CODE', message: 'Hello' // name is missing }) } catch (error) { console.error(error.message) // "Warning name must not be empty" } ``` -------------------------------- ### Unlimited Warning Emission Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md Illustrates how to configure a warning to emit every time it is called by setting the `unlimited` option to `true`. This is useful for warnings that should be reported on each occurrence. ```javascript const { createWarning } = require('process-warning') const unlimited = createWarning({ name: 'EventWarning', code: 'EVENT_FIRED', message: 'Event "%s" triggered', unlimited: true }) unlimited('click') // Emits unlimited('click') // Emits again unlimited('click') // Emits again ``` -------------------------------- ### Formatting Message with `format` Method Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Use the `format` method to interpolate parameters into the warning message without actually emitting the warning. ```APIDOC ## WarningItem.format() ### Description Formats the warning message with the provided interpolation values without emitting the warning. ### Signature ```javascript (a?: any, b?: any, c?: any): string ``` ### Parameters #### Path Parameters - **a** (any) - Optional - First interpolation value for the message - **b** (any) - Optional - Second interpolation value for the message - **c** (any) - Optional - Third interpolation value for the message ### Return Type `string` - The formatted warning message. ### Usage Example ```javascript const warn = createWarning({ name: 'ConfigWarning', code: 'CFG_001', message: 'Invalid config: %s = %s' }) // Format the message without emitting const message = warn.format('timeout', '0') // Use the formatted message elsewhere console.log('Message:', message) // Output: Message: Invalid config: timeout = 0 // Emit later if needed warn('timeout', '0') ``` ### Multi-parameter interpolation Example ```javascript const warn = createWarning({ name: 'ValidationWarning', code: 'VAL_001', message: 'Field "%s" expected %s but got %s' }) // One parameter warn.format('age') // Output: 'Field "age" expected %s but got %s' // Two parameters warn.format('age', 'number') // Output: 'Field "age" expected number but got %s' // Three parameters warn.format('age', 'number', 'string') // Output: 'Field "age" expected number but got string' // Emit with parameters warn('age', 'number', 'string') ``` ``` -------------------------------- ### DeprecationOptions Source: https://github.com/fastify/process-warning/blob/main/_autodocs/types.md Configuration options for createDeprecation(). Identical to WarningOptions except name is omitted. ```APIDOC ## DeprecationOptions ### Description Configuration options for the `createDeprecation()` function. Identical to `WarningOptions` except `name` is omitted (always set to `'DeprecationWarning'`). ### Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | `code` | `string` | Yes | The deprecation code identifier (e.g., `'DEP_001'`) | | `message` | `string` | Yes | The deprecation message template with optional `%s` placeholders | | `unlimited` | `boolean` | No | If `true`, emit every time. Default is `false` (emit once). | ### Type Definition ```typescript type DeprecationOptions = Omit ``` ``` -------------------------------- ### String Interpolation in Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Use up to three `%s` placeholders in the warning message for dynamic parameter insertion. ```javascript const warn = createWarning({ message: 'Parameter %s is %s (expected %s)' }) warn('age', 'string', 'number') // Message: "Parameter age is string (expected number)" ``` -------------------------------- ### Create Simple Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/INDEX.md Use this snippet to create a reusable warning function for a specific warning name, code, and message. The warning will emit only once by default. ```javascript const { createWarning } = require('process-warning') const warn = createWarning({ name: 'MyAppWarning', code: 'MYAPP_001', message: 'This feature is deprecated' }) warn() // Emits once ``` -------------------------------- ### Importing Module Property Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md Import the module property for convenience, which is a re-export of the module. ```javascript const processWarning = require('process-warning').processWarning ``` -------------------------------- ### ProcessWarning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/types.md Describes the shape of the module's default export, containing both createWarning and createDeprecation functions. ```APIDOC ## ProcessWarning ### Description This type describes the shape of the module's default export, which includes the `createWarning` and `createDeprecation` functions. ### Methods - `createWarning(params: WarningOptions): WarningItem` - Creates a regular warning. - `createDeprecation(params: DeprecationOptions): WarningItem` - Creates a deprecation warning. ### Type Definition ```typescript type ProcessWarning = { createWarning(params: WarningOptions): WarningItem; createDeprecation(params: DeprecationOptions): WarningItem; } ``` ``` -------------------------------- ### createWarning() Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md Creates a regular warning. This function is part of the public API for emitting warnings. ```APIDOC ## createWarning() ### Description Creates a regular warning. This function is part of the public API for emitting warnings. ### Method Not applicable (SDK function) ### Endpoint Not applicable (SDK function) ### Parameters This function accepts parameters for message formatting, similar to `util.format()`. #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript createWarning('This is a regular warning message with %s parameter.', 'value'); ``` ### Response This function does not return a value directly but emits a warning via `process.emitWarning()`. ``` -------------------------------- ### Use String Interpolation in Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Define warning messages with placeholders (`%s`) that can be populated with arguments when the warning is emitted. ```javascript const warn = createWarning({ name: 'ValidationWarning', code: 'VAL_001', message: 'Field "%s" should be "%s" not "%s"' }) warn('email', 'string', 'number') ``` -------------------------------- ### WarningItem Interface Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md The WarningItem interface represents a warning that can be emitted. It can be called directly to emit the warning, and it has properties to track its state and configuration. The format method allows for message formatting without emission. ```APIDOC ## WarningItem Interface ### Description The WarningItem interface is the return type for `createWarning()` and `createDeprecation()`. It allows for emitting warnings with optional parameters and provides methods to format messages and manage emission state. ### Callable Signature ```javascript warningItem(a?, b?, c?) // Emits the warning with interpolation ``` ### Properties - `name` (string) - Warning name (immutable) - `code` (string) - Warning code in uppercase (immutable) - `message` (string) - Message template (immutable) - `emitted` (boolean) - Tracks emission state (mutable for testing) - `unlimited` (boolean) - Whether unlimited emissions are enabled (immutable) ### Methods - `format(a?, b?, c?): string` - Formats message without emitting ### Behavior - Non-unlimited warnings emit once, then ignore subsequent calls. - Unlimited warnings emit every time they're called. - The `emitted` property can be reset to `false` to re-emit in non-unlimited mode. - String interpolation supports up to three parameters with `%s` placeholders. ``` -------------------------------- ### Handle Missing Warning Code Source: https://github.com/fastify/process-warning/blob/main/_autodocs/errors.md Catch errors when the 'code' parameter is missing for both createWarning and createDeprecation. Ensure 'code' is provided. ```javascript const { createWarning, createDeprecation } = require('process-warning') // With createWarning try { createWarning({ name: 'MyWarning', message: 'Hello' // code is missing }) } catch (error) { console.error(error.message) // "Warning code must not be empty" } // With createDeprecation try { createDeprecation({ message: 'Hello' // code is missing }) } catch (error) { console.error(error.message) // "Warning code must not be empty" } ``` -------------------------------- ### createWarning Function Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md The createWarning function is used to create a callable warning object. It accepts an options object and returns a function that, when called, emits a warning via process.emitWarning(). ```APIDOC ## createWarning(params) ### Description Creates a callable warning object that can be used to emit custom warnings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (object) - Required - An object containing the warning configuration. - **name** (string) - Required - The name of the warning. - **code** (string) - Required - The error code for the warning. - **message** (string) - Required - The message content of the warning. Supports Node.js util.format() style interpolation. - **unlimited** (boolean) - Optional - If true, the warning will emit every time the returned function is called. Defaults to false. ### Returns A function that, when called, emits the configured warning. This function also has an `emitted` property (boolean) and a `format` method. ### Throws - **Error** - "Warning name must not be empty" if `params.name` is not provided or is falsy. - **Error** - "Warning code must not be empty" if `params.code` is not provided or is falsy. - **Error** - "Warning message must not be empty" if `params.message` is not provided or is falsy. - **Error** - "Warning opts.unlimited must be a boolean" if `params.unlimited` is provided but is not a boolean. ### Behavior - **Deduplication Mode** (unlimited === false): The warning emits exactly once. Subsequent calls have no effect unless `emitted` is manually reset to `false`. - **Unlimited Mode** (unlimited === true): The warning emits every time the returned function is called. - **String Interpolation**: Supports Node.js `util.format()` style interpolation for the message using up to three parameters (a, b, c). ### Request Example ```javascript const { createWarning } = require('process-warning'); const myWarning = createWarning({ name: 'MyAppWarning', code: 'MYAPP_001', message: 'This is a deprecation notice' }); // Emit the warning myWarning(); // Check if emitted console.log(myWarning.emitted); // true // Reset to allow re-emission myWarning.emitted = false; myWarning(); // Emits again ``` ### Response Example (The returned function does not have a direct response in terms of return value, but it triggers `process.emitWarning()`) #### Success Response (Implicit) - The primary effect is the emission of a warning via `process.emitWarning()`. #### Response Example (No direct response object is returned by the `createWarning` function itself, but the emitted warning object has properties like `name`, `code`, and `message`.) ``` -------------------------------- ### createWarning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md Creates a regular warning item that can be emitted to the Node.js process. It allows for custom names, codes, messages, and controls whether the warning can be emitted multiple times. ```APIDOC ## createWarning(params) ### Description Creates a warning item that emits to the Node.js process. ### Signature ```typescript function createWarning(params: WarningOptions): WarningItem ``` ### Parameters #### Path Parameters - **params.name** (string) - Required - Warning name identifier - **params.code** (string) - Required - Warning code identifier (auto-uppercased) - **params.message** (string) - Required - Warning message (supports `%s` interpolation) - **params.unlimited** (boolean) - Optional - Allow multiple emissions (default: false) ### Returns `WarningItem` — Callable warning object with properties and methods ### Throws `Error` if required parameters are missing or invalid ``` -------------------------------- ### Convert Deprecation Warnings to Errors in JavaScript Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Shows how to create a deprecation warning and emit it. When the --throw-deprecation flag is used, this call will throw an error instead of emitting a warning. ```javascript const { createDeprecation } = require('process-warning') const deprecation = createDeprecation({ code: 'OLD_API', message: 'The oldAPI() method is deprecated' }) // With --throw-deprecation flag: // This will throw an error instead of emitting a warning deprecation() ``` -------------------------------- ### createWarning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md Creates a warning item that can be emitted to the Node.js process with optional deduplication. ```APIDOC ## createWarning ### Description Creates a warning item that can be emitted to the Node.js process with optional deduplication. ### Signature ```javascript function createWarning(params: WarningOptions): WarningItem ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (WarningOptions) - Required - Configuration object for the warning - **params.name** (string) - Required - The name of the warning (e.g., `'MyAppWarning'`, `'ExampleWarning'`). Used to identify the warning type. - **params.code** (string) - Required - A unique code identifier for the warning (e.g., `'EXP_WRN_001'`, `'FST_ERR_001'`). The code is automatically converted to uppercase. Recommendation: prefix with a three-letter module abbreviation followed by underscore (e.g., `'FST_'` for Fastify). - **params.message** (string) - Required - The warning message. Supports string interpolation with `%s` placeholders for up to three values. - **params.unlimited** (boolean) - Optional - If `true`, the warning will emit every time the returned function is called. If `false` (default), the warning emits only once unless the `emitted` property is reset. ### Request Example ```json { "params": { "name": "ExampleWarning", "code": "EXP_WRN_001", "message": "This is an example warning with %s placeholder.", "unlimited": false } } ``` ### Response #### Success Response (200) **`WarningItem`** - A callable function with the following properties: - **`name`** (string) - The warning name as provided in options. - **`code`** (string) - The warning code in uppercase. - **`message`** (string) - The warning message template. - **`emitted`** (boolean) - Whether the warning has been emitted at least once. Initially `false`. Can be set to `true` or `false` to control re-emission behavior. - **`unlimited`** (boolean) - Whether the warning can be emitted multiple times. - **`format(a?, b?, c?)`** (function) - Formats the warning message with up to three interpolation values and returns the formatted string without emitting. #### Response Example ```json { "name": "ExampleWarning", "code": "EXP_WRN_001", "message": "This is an example warning with %s placeholder.", "emitted": false, "unlimited": false, "format": "function" } ``` ``` -------------------------------- ### Format Warning Message Without Emitting Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Illustrates formatting a warning message with parameters using the 'format' method without actually emitting the warning. The formatted string can then be used elsewhere. ```javascript const warn = createWarning({ name: 'ConfigWarning', code: 'CFG_001', message: 'Invalid config: %s = %s' }) // Format the message without emitting const message = warn.format('timeout', '0') // Use the formatted message elsewhere console.log('Message:', message) // Output: Message: Invalid config: timeout = 0 // Emit later if needed warn('timeout', '0') ``` -------------------------------- ### Handle Errors During Warning Creation Source: https://github.com/fastify/process-warning/blob/main/_autodocs/README.md Wrap the `createWarning` call in a try-catch block to handle potential errors during the creation of a warning object, such as missing required parameters. ```javascript const { createWarning } = require('process-warning') try { const warn = createWarning({ name: 'MyWarning', code: 'CODE', message: 'Hello' }) } catch (error) { if (error.message.includes('must not be empty')) { console.error('Missing required parameter') } } ``` -------------------------------- ### Node.js Deprecation Warning Flags Source: https://github.com/fastify/process-warning/blob/main/_autodocs/INDEX.md Use `createDeprecation()` for warnings that respect Node.js flags like `--throw-deprecation`, `--no-deprecation`, and `--trace-deprecation`. ```bash node --throw-deprecation app.js # Throws instead of warning node --no-deprecation app.js # Suppresses deprecations node --trace-deprecation app.js # Includes stack trace ``` -------------------------------- ### createWarning Source: https://github.com/fastify/process-warning/blob/main/README.md Creates a warning object builder. This function is used to define custom warnings with specific names, codes, and messages. It also allows for configuration of emission behavior, such as whether a warning can be emitted multiple times. ```APIDOC ## createWarning({ name, code, message[, unlimited] }) ### Description Creates a builder function for generating and emitting warnings. ### Parameters #### Path Parameters - **name** (string) - Required - The error name for the warning. - **code** (string) - Required - The warning code, recommended to be uppercase and prefixed. - **message** (string) - Required - The warning message, supports string interpolation. - **options** (object) - Optional - Configuration options for the warning. - **unlimited** (boolean) - Optional - If true, the warning can be emitted more than once. Defaults to false. ### Request Example ```javascript const { createWarning } = require('process-warning') const warning = createWarning({ name: 'ExampleWarning', code: 'EXP_WRN_001', message: 'Hello %s', unlimited: true }) warning('world') ``` ### Response #### Success Response (200) - **warning function** - A function that, when called, emits the warning. It accepts optional parameters for string interpolation. #### Response Example ```javascript const { createWarning } = require('process-warning') const FST_ERROR_CODE = createWarning({ name: 'MyAppWarning', code: 'FST_ERROR_CODE', message: 'message' }) FST_ERROR_CODE() ``` ``` -------------------------------- ### Create Deprecation Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/MODULE.md Use this to create a specific deprecation warning instance. ```javascript const { createDeprecation } = require('process-warning') const deprecation = createDeprecation({ code: 'API_V1_REMOVED', message: 'API v1 is deprecated, migrate to v2' }) deprecation() ``` -------------------------------- ### Create a Basic Deprecation Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createDeprecation.md Use this to create a reusable deprecation warning function. The warning will only be emitted once by default. ```javascript const { createDeprecation } = require('process-warning') const deprecation = createDeprecation({ code: 'API_VERSION_CHANGE', message: 'This API has been deprecated' }) deprecation() // Emits DeprecationWarning once deprecation() // No effect (already emitted) ``` -------------------------------- ### Create a Deprecation Warning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/configuration.md Use this snippet to create a deprecation warning. It requires a code and message, and optionally accepts an 'unlimited' flag to control emission frequency. The 'name' is automatically set to 'DeprecationWarning'. ```javascript const { createDeprecation } = require('process-warning') const config = { code: 'API_CHANGE', message: 'Method "%s" has been renamed to "%s"', unlimited: false // Optional, default is false } const deprecation = createDeprecation(config) ``` -------------------------------- ### JavaScript Signature for createWarning Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createWarning.md Defines the function signature for createWarning, indicating it accepts WarningOptions and returns a WarningItem. ```javascript function createWarning(params: WarningOptions): WarningItem ``` -------------------------------- ### Control Warning Emission with 'emitted' Property Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md Shows how to check and control the emission of a warning using the 'emitted' property. Initially false, it becomes true after emission and can be reset to allow re-emission. ```javascript const warn = createWarning({ name: 'TestWarning', code: 'TEST_001', message: 'This is a test' }) console.log(warn.emitted) // false (before emission) warn() // Emits the warning console.log(warn.emitted) // true (after emission) warn() // No effect // Reset for testing warn.emitted = false warn() // Emits again ``` -------------------------------- ### Create Warning with Interpolated Message Source: https://github.com/fastify/process-warning/blob/main/_autodocs/INDEX.md Create a warning function that accepts arguments to interpolate into its message string. This is useful for dynamic warning messages. ```javascript const warn = createWarning({ name: 'ValidationWarning', code: 'VAL_001', message: 'Field "%s" has invalid value "%s"' }) warn('email', 'not-an-email') ``` -------------------------------- ### Create Unlimited Deprecation Warnings Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/createDeprecation.md Use the 'unlimited: true' option to create a deprecation warning that emits every time it is called, rather than just once. This is useful for critical or frequently occurring issues. ```javascript const { createDeprecation } = require('process-warning') const repeatingDeprecation = createDeprecation({ code: 'CONFIG_CHANGE', message: 'Configuration method "%s" is deprecated', unlimited: true }) repeatingDeprecation('method1') // Emits repeatingDeprecation('method2') // Emits again repeatingDeprecation('method3') // Emits again ``` -------------------------------- ### WarningItem Interface Source: https://github.com/fastify/process-warning/blob/main/_autodocs/api-reference/WarningItem.md The WarningItem interface defines the structure and behavior of warning objects created by `createWarning()` and `createDeprecation()`. ```APIDOC ## Interface Definition ```typescript interface WarningItem { (a?: any, b?: any, c?: any): void; name: string; code: string; message: string; emitted: boolean; unlimited: boolean; format(a?: any, b?: any, c?: any): string; } ``` ## Properties | Property | Type | Mutable | Description | |----------|------|--------|-------------| | `name` | `string` | No | The warning name (e.g., `'MyAppWarning'`, `'DeprecationWarning'`). Set during creation and immutable. | | `code` | `string` | No | The warning code identifier in uppercase (e.g., `'EXP_WRN_001'`). Automatically uppercased during creation. | | `message` | `string` | No | The warning message template with optional `%s` placeholders. Set during creation and immutable. | | `emitted` | `boolean` | **Yes** | Tracks whether the warning has been emitted. Initially `false`. Can be set to `true` or `false` to control re-emission behavior in non-unlimited warnings. | | `unlimited` | `boolean` | No | Whether the warning can be emitted multiple times. Set during creation and immutable. | ## Methods ### format(a?, b?, c?) Formats the warning message with interpolation values without emitting the warning. #### Signature ```javascript format(a?: any, b?: any, c?: any): string ``` #### Parameters - `a` (optional) - First interpolation value - `b` (optional) - Second interpolation value - `c` (optional) - Third interpolation value #### Return Type `string` - The formatted message #### Behavior - Uses Node.js `util.format()` under the hood - Supports up to three parameters with `%s` placeholders - Returns the formatted message string without emitting to the process - If no parameters are provided, returns the original message #### Example ```javascript const warn = createWarning({ name: 'TestWarning', code: 'TEST_001', message: 'Value is %s and timeout is %s' }) const formatted = warn.format('invalid', 5000) console.log(formatted) // Output: "Value is invalid and timeout is 5000" ``` ``` -------------------------------- ### Create and Emit an Interpolated Warning Source: https://github.com/fastify/process-warning/blob/main/README.md Create a warning that accepts arguments for string interpolation in its message. ```javascript const { createWarning } = require('process-warning') const FST_ERROR_CODE = createWarning({ name: 'MyAppWarning', code: 'FST_ERROR_CODE', message: 'Hello %s'}) FST_ERROR_CODE('world') ``` -------------------------------- ### WarningOptions Type Definition Source: https://github.com/fastify/process-warning/blob/main/_autodocs/types.md Specifies the configuration options for creating a regular warning. It requires name, code, and message, with an optional unlimited flag to control emission frequency. ```typescript type WarningOptions = { name: string; code: string; message: string; unlimited?: boolean; } ```