/** * @file JSON type definitions and interfaces. */ import type { Schema } from '../schema/types.js'; /** * JSON primitive types: `null`, `boolean`, `number`, or `string`. * * @example * ;```ts * const primitives: JsonPrimitive[] = [null, true, 42, 'hello'] * ``` */ export type JsonPrimitive = null | boolean | number | string; /** * A JSON array containing JSON values. * * @example * ;```ts * const arr: JsonArray = [1, 'two', { three: 3 }, [4, 5]] * ``` */ export interface JsonArray extends Array { } /** * A JSON object with string keys and JSON values. * * @example * ;```ts * const obj: JsonObject = { * name: 'example', * count: 42, * active: true, * nested: { key: 'value' }, * } * ``` */ export interface JsonObject { [key: string]: JsonValue; } /** * Any valid JSON value: primitive, object, or array. * * @example * ;```ts * const values: JsonValue[] = [ * null, * true, * 42, * 'hello', * { key: 'value' }, * [1, 2, 3], * ] * ``` */ export type JsonValue = JsonPrimitive | JsonObject | JsonArray; /** * Reviver function for transforming parsed JSON values. Called for each * key-value pair during parsing. * * @example * ;```ts * // Convert date strings to Date objects * const reviver: JsonReviver = (key, value) => { * if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) { * return new Date(value) * } * return value * } * ``` * * @param key - The object key or array index being parsed. * @param value - The parsed value. * * @returns The transformed value, or the original when no transform is needed. */ export type JsonReviver = (key: string, value: unknown) => unknown; /** * Options for `parseJsonStrict`: security controls for untrusted JSON. * * Distinct from `ParseJsonOptions` (which is scoped to reviver / error-handling * for trusted-source fs reads). Use this type when parsing user input, network * payloads, or anything beyond a trust boundary. * * @example * ;```ts * const options: ParseJsonStrictOptions = { * maxSize: 1024 * 1024, // 1MB limit * allowPrototype: false, // Block prototype pollution * } * ``` */ export interface ParseJsonStrictOptions { /** * Zod-shaped schema validated against the parsed value, via * `@socketsecurity/lib/schema/validate`. */ schema?: Schema | undefined; /** * Allow dangerous prototype pollution keys (`__proto__`, `constructor`, * `prototype`). Set to `true` only if you trust the JSON source completely. * * @example * ;```ts * // Will throw error by default * parseJsonStrict('{"__proto__": {"polluted": true}}') * * // Allows the parse (dangerous!) * parseJsonStrict('{"__proto__": {"polluted": true}}', { * allowPrototype: true, * }) * ``` * * @default false */ allowPrototype?: boolean | undefined; /** * Maximum allowed size of JSON string in bytes. Prevents memory exhaustion * from extremely large payloads. * * @example * ;```ts * // Limit to 1KB * parseJsonStrict(jsonString, { maxSize: 1024 }) * ``` * * @default 10_485_760 (10 MB) */ maxSize?: number | undefined; } /** * Options for JSON parsing operations. */ export interface ParseJsonOptions { /** * Optional filepath for improved error messages. When provided, errors will * be prefixed with the filepath. * * @example * ;```ts * // Error message will be: "config.json: Unexpected token } in JSON" * parseJson('invalid', { filepath: 'config.json' }) * ``` */ filepath?: string | undefined; /** * Optional reviver function to transform parsed values. Called for each * key-value pair during parsing. * * @example * ;```ts * // Convert ISO date strings to Date objects * const options = { * reviver: (key, value) => { * if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) { * return new Date(value) * } * return value * }, * } * ``` */ reviver?: JsonReviver | undefined; /** * Whether to throw on parse errors. When `false`, returns `undefined` instead * of throwing. * * @example * ;```ts * // Throws error * parseJson('invalid', { throws: true }) * * // Returns undefined * const result = parseJson('invalid', { throws: false }) * ``` * * @default true */ throws?: boolean | undefined; } /** * Options for saving editable JSON files. */ export interface EditableJsonSaveOptions { /** * Whether to ignore whitespace-only changes when determining if save is * needed. * * @default false */ ignoreWhitespace?: boolean | undefined; /** * Whether to sort object keys alphabetically before saving. * * @default false */ sort?: boolean | undefined; } /** * Options for creating or loading editable JSON instances. */ export interface EditableJsonOptions> { /** * File path for the JSON file. Optional for in-memory instances. */ path?: string | undefined; /** * Whether to create the file if it doesn't exist during load. * * @default false */ create?: boolean | undefined; /** * Initial data to populate the instance with. */ data?: T | undefined; } /** * EditableJson instance interface for JSON file manipulation. Provides core * functionality for loading, editing, and saving JSON files while preserving * formatting: indentation and line endings. */ export interface EditableJsonInstance> { /** * The parsed JSON content as a readonly object. * * @readonly */ content: Readonly; /** * Create a new JSON file at the specified path. * * @param path - The file path where JSON will be created. */ create(path: string): this; /** * Initialize the instance from a content object. Note: Using this disables * saving, since no file path is associated. * * @param content - The JSON content object. */ fromContent(content: unknown): this; /** * Initialize the instance from a JSON string. * * @param json - The JSON content as a string. */ fromJSON(json: string): this; /** * Load a JSON file from the specified path. Throws on read or parse errors. * The static `EditableJson.load(path, { create: true })` surface handles * ENOENT recovery. * * @param path - The file path to load. */ load(path: string): Promise; /** * Update the JSON content with new values. * * @param content - Partial object with fields to update. */ update(content: Partial): this; /** * Save the JSON file to disk. * * @param options - Save options for formatting and sorting. */ save(options?: EditableJsonSaveOptions | undefined): Promise; /** * Synchronously save the JSON file to disk. * * @param options - Save options for formatting and sorting. */ saveSync(options?: EditableJsonSaveOptions | undefined): boolean; /** * Check if the JSON will be saved based on current changes. * * @param options - Save options to evaluate. */ willSave(options?: EditableJsonSaveOptions | undefined): boolean; /** * The full path to the JSON file. * * @readonly */ readonly filename: string; /** * The directory path containing the JSON file. * * @readonly */ readonly path: string | undefined; } /** * EditableJson constructor interface. */ export interface EditableJsonConstructor> { new (): EditableJsonInstance; create(path: string, opts?: EditableJsonOptions | undefined): Promise>; load(path: string, opts?: EditableJsonOptions | undefined): Promise>; }