/** * Logger interface for GLPI client operations. */ interface ILogger { debug(message: string, ...meta: unknown[]): void; info(message: string, ...meta: unknown[]): void; warn(message: string, ...meta: unknown[]): void; error(message: string, ...meta: unknown[]): void; } /** * No-operation logger implementation that silently discards all logs. * Used as the default logger when none is provided. */ declare class NoopLogger implements ILogger { debug(_message: string, ..._meta: unknown[]): void; info(_message: string, ..._meta: unknown[]): void; warn(_message: string, ..._meta: unknown[]): void; error(_message: string, ..._meta: unknown[]): void; } /** * Standard console logger implementation with customizable prefix. */ declare class ConsoleLogger implements ILogger { private readonly prefix; constructor(prefix?: string); debug(message: string, ...meta: unknown[]): void; info(message: string, ...meta: unknown[]): void; warn(message: string, ...meta: unknown[]): void; error(message: string, ...meta: unknown[]): void; } type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | (string & {}); /** * Options for individual HTTP requests. */ interface HttpRequestOptions { method: HttpMethod; path: string; headers?: Record | Headers | [string, string][]; params?: Record; body?: unknown; timeout?: number; signal?: AbortSignal; rawResponse?: boolean; dispatcher?: unknown; } /** * Standardized HTTP response wrapper. */ interface HttpResponse { status: number; statusText: string; headers: Headers; data: T; } /** * Request interceptor function or object. */ type RequestInterceptorFn = (options: HttpRequestOptions) => HttpRequestOptions | Promise; interface RequestInterceptorObj { onFulfilled?: RequestInterceptorFn; onRejected?: (error: unknown) => unknown | Promise; } type RequestInterceptor = RequestInterceptorFn | RequestInterceptorObj; /** * Response interceptor function or object. */ type ResponseInterceptorFn = (response: HttpResponse) => HttpResponse | Promise>; interface ResponseInterceptorObj { onFulfilled?: ResponseInterceptorFn; onRejected?: (error: unknown, options?: HttpRequestOptions) => unknown | Promise; } type ResponseInterceptor = ResponseInterceptorFn | ResponseInterceptorObj; /** * Configuration options for HTTP proxy routing. */ interface ProxyOptions { url: string; auth?: string | { username?: string; password?: string; }; headers?: Record; noProxy?: string | string[]; [key: string]: unknown; } /** * Configuration passed to FetchHttpClient initialization. */ interface HttpClientConfig { baseUrl?: string; headers?: Record | Headers | [string, string][]; timeout?: number; fetch?: typeof fetch; proxy?: string | ProxyOptions; useEnvProxy?: boolean; noProxy?: string | string[]; dispatcher?: unknown; logger?: ILogger; } /** * Abstract HTTP client contract. */ interface IHttpClient { request(options: HttpRequestOptions): Promise>; useRequestInterceptor(interceptor: RequestInterceptor): () => void; useResponseInterceptor(interceptor: ResponseInterceptor): () => void; setHeader(name: string, value: string): void; removeHeader(name: string): void; shouldBypassProxy?(url: string | URL): boolean; getProxyOptions?(targetUrl?: string): ProxyOptions | undefined; getBaseUrl?(): string; } /** * Native fetch-based implementation of IHttpClient with proxy, interceptors, and error mapping. */ declare class FetchHttpClient implements IHttpClient { private readonly baseUrl; private readonly fetchFn; private readonly timeout?; private readonly proxy?; private readonly useEnvProxy; private readonly noProxy?; private dispatcher?; private readonly logger; private readonly defaultHeaders; private readonly requestInterceptors; private readonly responseInterceptors; constructor(config?: HttpClientConfig); /** * Registers a request interceptor. Returns an unsubscribe function. */ useRequestInterceptor(interceptor: RequestInterceptor): () => void; /** * Registers a response interceptor. Returns an unsubscribe function. */ useResponseInterceptor(interceptor: ResponseInterceptor): () => void; /** * Sets a persistent header applied to all subsequent requests. */ setHeader(name: string, value: string): void; /** * Removes a persistent header. */ removeHeader(name: string): void; /** * Retrieves the value of a persistent header. */ getHeader(name: string): string | null; /** * Retrieves all active NO_PROXY bypass rules from configuration or environment. */ getNoProxyRules(): string[]; /** * Checks whether a target URL should bypass the configured proxy. */ shouldBypassProxy(urlInput: string | URL): boolean; /** * Returns normalized proxy options if configured via proxy property or environment. * If targetUrl is provided and matches NO_PROXY bypass rules, returns undefined. */ getProxyOptions(targetUrl?: string): ProxyOptions | undefined; /** * Returns base URL configured for this client instance. */ getBaseUrl(): string; /** * Returns current dispatcher instance if configured. */ getDispatcher(): unknown | undefined; /** * Sends an HTTP request through interceptor chain, proxy dispatcher, and error mapper. */ request(options: HttpRequestOptions): Promise>; get(path: string, options?: Omit): Promise>; post(path: string, body?: unknown, options?: Omit): Promise>; put(path: string, body?: unknown, options?: Omit): Promise>; patch(path: string, body?: unknown, options?: Omit): Promise>; delete(path: string, options?: Omit): Promise>; private executeRequest; private buildUrl; private buildHeaders; private resolveDispatcher; } /** * Standard contract for authentication providers in the GLPI API client. */ interface IAuthProvider { /** * Retrieves an active OAuth2 access token, transparently refreshing if needed. */ getAccessToken(): Promise; /** * Invalidates the current access token, forcing a refresh on the next request. */ invalidateToken(): Promise; /** * Clears all session tokens and authentication state. */ logout(): Promise; } /** * Stored token payload. */ interface TokenData { accessToken: string; expiresIn?: number; expiresAt?: number; refreshToken?: string; tokenType?: string; scope?: string; } /** * Result returned by a token fetch/refresh function. */ interface TokenFetchResult { accessToken: string; refreshToken?: string; expiresIn?: number; tokenType?: string; scope?: string; [key: string]: unknown; } /** * Function that executes token acquisition/refresh over HTTP. */ type TokenFetchFn = () => Promise; /** * Configuration options for TokenManager. */ interface TokenManagerOptions { /** * Seconds before actual expiration at which a token is proactively considered expired. * Defaults to 30 seconds. */ proactiveMarginSeconds?: number; } /** * Storage backend interface for persisting OAuth tokens. */ interface ITokenStorage { getToken(): Promise; setToken(token: TokenData): Promise; clearToken(): Promise; } /** * Options for PasswordAuthProvider. */ interface PasswordAuthOptions { httpClient: IHttpClient; clientId?: string; clientSecret?: string; username: string; password: string; tokenEndpoint?: string; scope?: string; storage?: ITokenStorage; proactiveMarginSeconds?: number; } /** * Options for AuthorizationCodeAuthProvider. */ interface AuthCodeOptions { httpClient: IHttpClient; clientId: string; clientSecret?: string; code?: string; redirectUri?: string; refreshToken?: string; tokenEndpoint?: string; scope?: string; storage?: ITokenStorage; proactiveMarginSeconds?: number; } /** * Options for ClientCredentialsAuthProvider. */ interface ClientCredentialsOptions { httpClient: IHttpClient; clientId: string; clientSecret: string; scope?: string; tokenEndpoint?: string; storage?: ITokenStorage; proactiveMarginSeconds?: number; } /** * Raw OAuth2 token endpoint response payload. */ interface OAuthTokenResponse { access_token?: string; accessToken?: string; token_type?: string; tokenType?: string; expires_in?: number; expiresIn?: number; refresh_token?: string; refreshToken?: string; scope?: string; error?: string; error_description?: string; [key: string]: unknown; } /** * Default core GLPI resource route mappings. */ declare const DEFAULT_CORE_ROUTES: Readonly>; /** * Registry mapping resource type names/aliases to GLPI URL endpoint paths. * Supports custom GLPI plugin route registration and direct path pass-through. */ declare class RouteRegistry { private routes; constructor(initialRoutes?: Record); /** * Registers a new alias or overrides an existing route. * * @param alias The resource short name or alias (e.g. 'Rack', 'MyPluginItem'). * @param path The GLPI API path (e.g. 'Assets/Rack', 'MyPlugin/Item'). */ register(alias: string, path: string): void; /** * Removes a registered alias. * * @param alias The alias to remove. * @returns True if the alias was found and removed, false otherwise. */ unregister(alias: string): boolean; /** * Checks if an alias is registered. * * @param alias The alias name. */ has(alias: string): boolean; /** * Resolves a resource identifier or alias to its GLPI URL path. * If the input is not registered, returns the input unchanged (direct pass-through). * * @param input Resource alias or path (e.g. 'Ticket', 'Assets/Computer', 'PluginNamespace/CustomItem'). * @returns Resolved GLPI path. */ resolve(input: string): string; /** * Returns a snapshot of all registered routes as a key-value object. */ getAll(): Record; /** * Clears all registered routes. */ clear(): void; } /** * Escapes and quotes values for RSQL query strings. * * Values containing special characters (;, ,, =, spaces, quotes, parentheses) * are enclosed in double quotes with inner double quotes escaped with a backslash. * Numbers and booleans are output without quotes. */ declare function escapeValue(val: unknown): string; type RsqlNested = RsqlBuilder | string | ((builder: RsqlBuilder) => RsqlBuilder); /** * Fluent builder for RSQL (REST Query Language / FIQL) expressions. */ declare class RsqlBuilder { private parts; private pendingConjunction?; constructor(initial?: string); private append; /** * Equality operator: `field==value` */ eq(field: string, val: unknown): this; /** * Inequality operator: `field!=value` */ neq(field: string, val: unknown): this; /** * Greater than operator: `field=gt=value` */ gt(field: string, val: unknown): this; /** * Greater than or equal operator: `field=ge=value` */ ge(field: string, val: unknown): this; /** * Less than operator: `field=lt=value` */ lt(field: string, val: unknown): this; /** * Less than or equal operator: `field=le=value` */ le(field: string, val: unknown): this; /** * Like (pattern matching) operator: `field=like=pattern` */ like(field: string, pattern: string): this; /** * Case-insensitive like operator: `field=ilike=pattern` */ ilike(field: string, pattern: string): this; /** * In-list operator: `field=in=(val1,val2,...)` */ in(field: string, values: unknown[]): this; /** * Not-in-list operator: `field=out=(val1,val2,...)` */ out(field: string, values: unknown[]): this; /** * Null check operator: `field=isnull=` */ isNull(field: string): this; /** * Not-null check operator: `field=isnotnull=` */ isNotNull(field: string): this; /** * Empty check operator: `field=empty=` */ empty(field: string): this; /** * Not-empty check operator: `field=notempty=` */ notEmpty(field: string): this; /** * Logical AND conjunction (`;`). * When called without arguments, marks the next condition to be joined by `;`. * When called with a nested builder or function, appends a parenthesized group with `;`. */ and(nested?: RsqlNested): this; /** * Logical OR conjunction (`,`). * When called without arguments, marks the next condition to be joined by `,`. * When called with a nested builder or function, appends a parenthesized group with `,`. */ or(nested?: RsqlNested): this; private isEnclosedInParens; private resolveNested; /** * Builds and returns the compiled RSQL query string. */ build(): string; /** * Returns the compiled RSQL query string. */ toString(): string; } /** * Creates a new fluent RSQL query builder. * * @param initial Optional initial RSQL query string or existing RsqlBuilder to clone. * @returns A new RsqlBuilder instance. */ declare function rsql(initial?: string | RsqlBuilder): RsqlBuilder; /** * Common request options for scoping and HTTP controls. */ interface RequestOptions { /** * Target GLPI entity ID (sets GLPI-Entity header). */ entity?: number | string; /** * Target GLPI profile ID (sets GLPI-Profile header). */ profile?: number | string; /** * Whether to include child entities recursively (sets GLPI-Entity-Recursive header). */ recursive?: boolean; /** * Response language code, e.g. 'en_GB' or 'fr_FR' (sets Accept-Language header). */ language?: string; /** * Additional custom HTTP headers to pass with the request. */ headers?: Record; /** * AbortSignal to cancel the request. */ signal?: AbortSignal; } /** * Parameters for paginated collection listing. */ interface ListParams extends RequestOptions { /** * RSQL query filter string or fluent RsqlBuilder instance. */ filter?: string | RsqlBuilder; /** * Zero-based offset for pagination (default: 0). */ start?: number; /** * Maximum number of items to return (default: 100). */ limit?: number; /** * Sort field or expression (e.g. 'id' or 'id:desc'). */ sort?: string; /** * Sort direction ('ASC' or 'DESC'). */ order?: 'ASC' | 'DESC' | (string & {}); /** * Arbitrary query parameters. */ params?: Record; [key: string]: unknown; } /** * Standardized paginated result wrapper. */ interface PaginatedResult { /** * Array of items returned in the current page. */ data: T[]; /** * Total count of items matching the query across all pages (from x-total-count header). */ total: number; /** * Number of items in this page (data.length). */ count: number; /** * The start offset used for this page, if specified. */ start?: number; /** * The page limit used for this query, if specified. */ limit?: number; } /** * Options for resource creation. */ interface CreateOptions extends RequestOptions { /** * If true, performs an immediate follow-up get() by id to retrieve and return the full entity. */ fetch?: boolean; } /** * Standard GLPI 2.x creation response payload. */ interface CreateResult { id: number | string; href: string; [key: string]: unknown; } /** * Options for resource updates. */ interface UpdateOptions extends RequestOptions { /** * HTTP method to use for updates (default: 'PATCH'). */ method?: 'PATCH' | 'PUT'; } /** * Options for resource deletion. */ interface DeleteOptions extends RequestOptions { /** * If true, permanently purges the item instead of moving it to the trash bin. */ force?: boolean; /** * Alias for permanent deletion in legacy or custom endpoints. */ purge?: boolean; /** * Additional query parameters for deletion. */ params?: Record; } /** * Generic contract for CRUD resource services. */ interface IResourceService { /** * Lists entities with optional filtering, sorting, and pagination. */ list(params?: ListParams): Promise>; /** * Retrieves a single entity by its identifier. */ get(id: number | string, options?: RequestOptions): Promise; /** * Creates a new entity. If options.fetch is true, returns the fully populated entity T. */ create(data: Partial | Record, options: CreateOptions & { fetch: true; }): Promise; create(data: Partial | Record, options?: CreateOptions & { fetch?: false; }): Promise; create(data: Partial | Record, options?: CreateOptions): Promise; /** * Updates an existing entity by ID. */ update(id: number | string, data: Partial | Record, options?: UpdateOptions): Promise; /** * Deletes an entity by ID with optional purge/force flags. */ delete(id: number | string, options?: DeleteOptions): Promise; } /** * Generic base service for GLPI REST resources implementing standard CRUD operations, * RSQL query filtering, pagination, and stateless session scoping headers. */ declare class ResourceService implements IResourceService { protected http: IHttpClient; protected basePath: string; protected registry?: RouteRegistry; /** * Initializes a new ResourceService instance. * * @param http The HTTP client to use for network transport. * @param endpoint The route path or registered alias (e.g. 'Ticket', 'Assistance/Ticket'). * @param registry Optional RouteRegistry for custom alias resolution. */ constructor(http: IHttpClient, endpoint: string, registry?: RouteRegistry); /** * Returns the normalized base path of this resource. */ getBasePath(): string; /** * Returns the underlying HTTP client. */ getHttpClient(): IHttpClient; /** * Builds the scoping and custom headers for a request. */ protected buildHeaders(options?: RequestOptions): Record | undefined; /** * Lists entities matching the query parameters with pagination. */ list(params?: ListParams): Promise>; /** * Retrieves an entity by its identifier. */ get(id: number | string, options?: RequestOptions): Promise; /** * Creates a new entity. If options.fetch is true, retrieves and returns the full entity. */ create(data: Partial | Record, options: CreateOptions & { fetch: true; }): Promise; create(data: Partial | Record, options?: CreateOptions & { fetch?: false; }): Promise; create(data: Partial | Record, options?: CreateOptions): Promise; /** * Updates an existing entity by ID. */ update(id: number | string, data: Partial | Record, options?: UpdateOptions): Promise; /** * Deletes an entity by ID with optional permanent purge/force flag. */ delete(id: number | string, options?: DeleteOptions): Promise; } /** * Strongly typed models for GLPI High-Level REST API domain entities. */ /** * GLPI Ticket status values according to GLPI specification. */ declare enum TicketStatus { NEW = 1, PROCESSING_ASSIGNED = 2, PROCESSING_PLANNED = 3, PENDING = 4, SOLVED = 5, CLOSED = 6, WAITING_VALIDATION = 10 } /** * Detailed ticket status object returned by GLPI REST API. */ interface TicketStatusInfo { id: TicketStatus | number; name?: string; [key: string]: unknown; } /** * Generic item reference object returned by GLPI REST API for dropdowns and linked entities. */ interface GlpiItemReference { id: number; name?: string; [key: string]: unknown; } /** * Entity reference object returned by GLPI REST API. */ interface GlpiEntityReference extends GlpiItemReference { completename?: string; } /** * GLPI Ticket type values. */ declare enum TicketType { INCIDENT = 1, REQUEST = 2 } /** * Ticket urgency / impact / priority levels (1: Very low, 2: Low, 3: Medium, 4: High, 5: Very high). */ type PriorityLevel = 1 | 2 | 3 | 4 | 5 | number; /** * Actor types that can be assigned or linked to a ticket. */ type TicketActorType = 'user' | 'group' | 'supplier' | 'User' | 'Group' | 'Supplier'; /** * Actor roles within a ticket. */ type TicketActorRole = 'requester' | 'assigned' | 'observer'; /** * Ticket entity model matching GLPI Assistance/Ticket representation. */ interface GlpiTicket { id: number; name?: string; content?: string; status?: TicketStatusInfo; urgency?: PriorityLevel; impact?: PriorityLevel; priority?: PriorityLevel; type?: TicketType | number; user_recipient?: GlpiItemReference; user_editor?: GlpiItemReference; category?: GlpiItemReference; location?: GlpiItemReference; entity?: GlpiEntityReference; is_deleted?: boolean | number; date_creation?: string; date_mod?: string; date?: string; date_solve?: string; date_close?: string; sla_ttr?: GlpiItemReference | number; sla_tto?: GlpiItemReference | number; ola_ttr?: GlpiItemReference | number; ola_tto?: GlpiItemReference | number; actiontime?: number; waiting_duration?: number; close_duration?: number; team?: Array<{ id: number; type: string; role: string; [key: string]: unknown; }>; costs?: unknown[]; [key: string]: unknown; } /** * Computer entity model matching GLPI Assets/Computer representation. */ interface GlpiComputer { id: number; name?: string; comment?: string; status?: GlpiItemReference; entity?: GlpiEntityReference; is_recursive?: boolean | number; manufacturer?: GlpiItemReference; user?: GlpiItemReference; user_tech?: GlpiItemReference; contact?: string; contact_num?: string; serial?: string; otherserial?: string; is_deleted?: boolean | number; date_creation?: string; date_mod?: string; location?: GlpiItemReference; type?: GlpiItemReference; model?: GlpiItemReference; group?: GlpiItemReference; group_tech?: GlpiItemReference; uuid?: string; network?: GlpiItemReference; autoupdatesystem?: GlpiItemReference; is_template?: boolean | number; template_name?: string; is_dynamic?: boolean | number; ticket_tco?: number | string; last_inventory_update?: string; last_boot?: string; [key: string]: unknown; } /** * User entity model matching GLPI Administration/User representation. */ interface GlpiUser { id: number; username?: string; realname?: string; firstname?: string; name?: string; phone?: string; phone2?: string; mobile?: string; emails?: Array<{ id: number; email: string; is_default?: boolean; [key: string]: unknown; }> | string; comment?: string; is_active?: boolean | number; is_deleted?: boolean | number; picture?: string; date_password_change?: string; location?: GlpiItemReference; authtype?: number; last_login?: string; default_profile?: GlpiItemReference; default_entity?: GlpiEntityReference; date_creation?: string; date_mod?: string; date_sync?: string; title?: GlpiItemReference; category?: GlpiItemReference; registration_number?: string; begin_date?: string; end_date?: string; nickname?: string; [key: string]: unknown; } /** * Document entity model matching GLPI Management/Document representation. */ interface GlpiDocument { id: number; name?: string; comment?: string; entity?: GlpiEntityReference; filename?: string; filepath?: string; download_url?: string; mime?: string; sha1sum?: string; checksum_sha1?: string; category?: GlpiItemReference; link?: string; user?: GlpiItemReference; is_deleted?: boolean | number; is_import_denied?: boolean | number; tag?: string; date_creation?: string; date_mod?: string; [key: string]: unknown; } /** * GLPI session information returned by GET /session. */ interface GlpiSessionInfo { glpiactiveprofile?: { id: number; name?: string; [key: string]: unknown; }; glpi_plugins?: unknown[]; active_profile?: { id: number; name?: string; interface?: string; rights?: Record; [key: string]: unknown; }; active_entity?: { id: number; short_name?: string; complete_name?: string; recursive?: number | boolean; [key: string]: unknown; }; user_id?: number; name?: string; friendly_name?: string; real_name?: string; first_name?: string; default_entity?: number; profiles?: unknown[]; active_entities?: unknown[]; groups?: number[]; current_time?: string; use_mode?: number; [key: string]: unknown; } /** * Timeline item structure for ticket interactions (followups, tasks, solutions, validations, documents). */ interface TicketTimelineItem { id: number | string; type?: string; itemtype?: string; date?: string; date_mod?: string; date_creation?: string; users_id?: number; content?: string; source?: string; is_private?: number | boolean; [key: string]: unknown; } /** * Input descriptor for uploading documents to GLPI. */ interface DocumentUploadFile { /** * The binary content or readable stream of the file. * Optional if filePath is provided. */ content?: Buffer | Uint8Array | ArrayBuffer | Blob | string | NodeJS.ReadableStream | ReadableStream | AsyncIterable; /** * Local file path to read content from automatically in Node.js environments. */ filePath?: string; /** * File name with extension (e.g. 'report.pdf'). * If omitted and filePath is provided, derived from the path basename. */ filename?: string; /** * MIME type of the file (e.g. 'application/pdf', 'text/plain'). * If omitted and filePath or filename is provided, inferred from the file extension. */ mimeType?: string; } /** * Metadata associated with an uploaded document. */ interface DocumentMetadata { /** * Human-readable document name. */ name?: string; /** * Description or comment for the document. */ comment?: string; /** * Desired filename on GLPI storage. */ filename?: string; /** * Target MIME type. */ mime?: string; /** * Target entity ID for the document. */ entities_id?: number; /** * Whether the document is visible recursively in child entities. */ is_recursive?: boolean | number; /** * Arbitrary JSON manifest payload. */ uploadManifest?: Record; [key: string]: unknown; } /** * Result returned from downloading a document binary. */ interface DocumentDownloadResult { /** * Binary contents of the downloaded file as ArrayBuffer. */ data: ArrayBuffer; /** * MIME content type extracted from response headers. */ contentType?: string; /** * File name extracted from the Content-Disposition header. */ filename?: string; /** * Raw response headers. */ headers?: Headers | Record; } /** * Specialized resource service for GLPI Tickets (/Assistance/Ticket). * Provides domain helper methods for managing followups, timelines, and actor assignments. */ declare class TicketResource extends ResourceService { /** * Initializes a new TicketResource instance. * * @param http The HTTP client to use for network transport. * @param endpoint The route path or registered alias (defaults to 'Assistance/Ticket'). * @param registry Optional RouteRegistry for custom alias resolution. */ constructor(http: IHttpClient, endpoint?: string, registry?: RouteRegistry); /** * Adds a new followup note to an existing ticket. * * @param ticketId The ID of the ticket. * @param content Plain text message string or a full followup payload object. * @param options Optional request options including entity/profile scoping. * @returns Creation result containing the new followup ID and URL. */ addFollowup(ticketId: number | string, content: string | Record, options?: RequestOptions): Promise; /** * Retrieves the complete timeline for a ticket, including followups, tasks, solutions, and validations. * * @param ticketId The ID of the ticket. * @param options Optional request options including entity/profile scoping. * @returns Array of timeline items. */ getTimeline(ticketId: number | string, options?: RequestOptions): Promise; /** * Assigns an actor (user, group, or supplier) to a ticket. * * @param ticketId The ID of the ticket. * @param actorId The identifier of the user, group, or supplier. * @param type The type of the actor: 'user', 'group', or 'supplier' (defaults to 'user'). * @param options Optional request options including entity/profile scoping. * @returns Creation result containing the new actor assignment ID and URL. */ assign(ticketId: number | string, actorId: number | string, type?: TicketActorType, options?: RequestOptions): Promise; /** * Associates or links a document to a ticket timeline. * * @param ticket Ticket ID or ticket resource object. * @param document Document ID or document resource object. * @param options Optional request options including entity/profile scoping. * @returns Creation result containing the new timeline item ID and URL. */ addDocument(ticket: number | string | { id: number | string; [key: string]: unknown; }, document: number | string | { id: number | string; [key: string]: unknown; }, options?: RequestOptions): Promise; } /** * Specialized resource service for GLPI Computers (/Assets/Computer). */ declare class ComputerResource extends ResourceService { /** * Initializes a new ComputerResource instance. * * @param http The HTTP client to use for network transport. * @param endpoint The route path or registered alias (defaults to 'Assets/Computer'). * @param registry Optional RouteRegistry for custom alias resolution. */ constructor(http: IHttpClient, endpoint?: string, registry?: RouteRegistry); } /** * Specialized resource service for GLPI Users (/Administration/User). * Provides helper methods for inspecting the current user identity and active session details. */ declare class UserResource extends ResourceService { /** * Initializes a new UserResource instance. * * @param http The HTTP client to use for network transport. * @param endpoint The route path or registered alias (defaults to 'Administration/User'). * @param registry Optional RouteRegistry for custom alias resolution. */ constructor(http: IHttpClient, endpoint?: string, registry?: RouteRegistry); /** * Retrieves profile information for the currently authenticated user (/Administration/User/Me). * * @param options Optional request options including entity/profile scoping. * @returns The authenticated user entity. */ me(options?: RequestOptions): Promise; /** * Retrieves current session information (/session) including active profiles, rights, and entities. * * @param options Optional request options including entity/profile scoping. * @returns The session metadata. */ getSession(options?: RequestOptions): Promise; } /** * Specialized resource service for GLPI Documents (/Management/Document). * Provides multi-type file upload via FormData and binary document downloading with metadata extraction. */ declare class DocumentResource extends ResourceService { /** * Initializes a new DocumentResource instance. * * @param http The HTTP client to use for network transport. * @param endpoint The route path or registered alias (defaults to 'Management/Document'). * @param registry Optional RouteRegistry for custom alias resolution. */ constructor(http: IHttpClient, endpoint?: string, registry?: RouteRegistry); /** * Uploads a file with metadata to GLPI using multipart/form-data. * * @param file Local file path string OR DocumentUploadFile (with content or filePath, filename, and mimeType). * @param metadata Optional metadata fields (name, comment, uploadManifest) to attach to the document. * @param options Optional request options including entity/profile scoping. * @returns Creation result containing the new document ID and URL. */ upload(file: string | DocumentUploadFile, metadata?: DocumentMetadata, options?: RequestOptions): Promise; /** * Downloads the binary content of a document and extracts filename and MIME type from response headers. * * @param id The ID of the document. * @param options Optional request options including entity/profile scoping. * @returns Download result with raw ArrayBuffer data, filename, and contentType. */ download(id: number | string, options?: RequestOptions): Promise; } /** * Base error class for all GLPI API client errors. */ declare class GlpiError extends Error { constructor(message: string, options?: ErrorOptions); } /** * Error thrown when an HTTP request fails. */ declare class GlpiHttpError extends GlpiError { readonly status: number; readonly statusText: string; readonly url: string; readonly body?: unknown; constructor(status: number, statusText: string, url: string, body?: unknown, message?: string); } /** * Error thrown when a requested GLPI resource is not found (HTTP 404). */ declare class GlpiNotFoundError extends GlpiHttpError { constructor(url: string, body?: unknown, message?: string); } /** * Error thrown when validation fails on a request payload (HTTP 400 / 422). */ declare class GlpiValidationError extends GlpiHttpError { readonly errors?: Record | unknown; constructor(url: string, errors?: Record | unknown, status?: number, statusText?: string, body?: unknown, message?: string); } /** * Error thrown when API rate limits are exceeded (HTTP 429). */ declare class GlpiRateLimitError extends GlpiHttpError { readonly retryAfter?: number; constructor(url: string, retryAfter?: number, body?: unknown, message?: string); } /** * Error thrown when an authentication or authorization failure occurs (e.g. OAuth2). */ declare class GlpiAuthenticationError extends GlpiError { readonly error?: string; readonly errorDescription?: string; constructor(error?: string, errorDescription?: string, message?: string); } /** * Location of a GraphQL error in the source document. */ interface GraphqlErrorLocation { line: number; column: number; } /** * Standard GraphQL error structure according to GraphQL specification. */ interface GraphqlError { message: string; locations?: GraphqlErrorLocation[]; path?: (string | number)[]; extensions?: Record; } /** * GraphQL execution result payload. */ interface GraphqlResponse { data?: T; errors?: GraphqlError[]; } /** * Options for GraphQL query execution. */ interface GraphqlRequestOptions { signal?: AbortSignal; headers?: Record; operationName?: string; } /** * Error thrown when a GraphQL response contains errors. */ declare class GlpiGraphqlError extends GlpiError { readonly errors: GraphqlError[]; constructor(message: string, errors?: GraphqlError[], options?: ErrorOptions); } /** * Interface contract for GraphQL client. */ interface IGraphqlClient { query(query: string, variables?: Record, options?: GraphqlRequestOptions): Promise; } /** * Client for interacting with the GLPI GraphQL API endpoint. */ declare class GraphqlClient implements IGraphqlClient { readonly path: string; private readonly http; /** * Initializes a new GraphqlClient. * * @param http - The HTTP client instance to use for network requests. * @param path - The GraphQL endpoint path (defaults to '/GraphQL'). */ constructor(http: IHttpClient, path?: string); /** * Executes a GraphQL query or mutation against the GLPI GraphQL endpoint. * * @typeParam T - The expected shape of the returned `data` object. * @param query - The GraphQL query or mutation document string. * @param variables - Optional variables to pass with the GraphQL operation. * @param options - Optional request options such as headers, abort signal, and operationName. * @returns The unwrapped `data` field of the GraphQL execution result. * @throws {GlpiGraphqlError} When the GraphQL server returns execution errors. * @throws {GlpiError} When the response structure is invalid or missing required data. */ query(query: string, variables?: Record, options?: GraphqlRequestOptions): Promise; } /** * Authentication configuration options for GlpiClient. */ type GlpiAuthOption = IAuthProvider | { type: 'password'; username: string; password: string; clientId?: string; clientSecret?: string; scope?: string; storage?: ITokenStorage; tokenEndpoint?: string; proactiveMarginSeconds?: number; } | { type: 'authorization_code'; clientId: string; clientSecret?: string; code?: string; redirectUri?: string; refreshToken?: string; scope?: string; storage?: ITokenStorage; tokenEndpoint?: string; proactiveMarginSeconds?: number; } | { type: 'client_credentials'; clientId: string; clientSecret: string; scope?: string; storage?: ITokenStorage; tokenEndpoint?: string; proactiveMarginSeconds?: number; }; /** * Configuration options for GlpiClient initialization. */ interface GlpiClientOptions { apiUrl: string; auth?: GlpiAuthOption; proxy?: string | ProxyOptions; useEnvProxy?: boolean; noProxy?: string | string[]; dispatcher?: unknown; fetch?: typeof fetch; timeout?: number; logger?: ILogger; restPath?: string; graphqlPath?: string; routes?: Record; headers?: Record | Headers | [string, string][]; } /** * Session entity scoping configuration. */ interface EntityScope { entityId: number | string; recursive: boolean; } /** * Main GLPI API client facade providing unified access to REST resources, * GraphQL querying, authentication management, and session scoping. */ declare class GlpiClient { readonly authProvider?: IAuthProvider; readonly tickets: TicketResource; readonly computers: ComputerResource; readonly users: UserResource; readonly documents: DocumentResource; readonly graphql: GraphqlClient; private readonly rootHttpClient; private readonly restHttpClient; private readonly registry; private entityScope?; private profileScope?; private languageScope?; /** * Initializes a new GlpiClient instance. * * @param options Configuration options for GLPI connection, authentication, and HTTP transport. */ constructor(options: GlpiClientOptions); /** * Retrieves the configured authentication provider. */ get auth(): IAuthProvider | undefined; /** * Retrieves the underlying REST HTTP client. */ get http(): IHttpClient; /** * Retrieves the underlying REST HTTP client. */ getHttpClient(): IHttpClient; /** * Retrieves the underlying root HTTP client (for /token and /GraphQL). */ getRootHttpClient(): IHttpClient; /** * Retrieves the route registry instance. */ getRegistry(): RouteRegistry; /** * Retrieves the underlying root HTTP client. */ get rootHttp(): FetchHttpClient; /** * Retrieves the underlying REST HTTP client. */ get restHttp(): FetchHttpClient; /** * Authenticates against the GLPI API and returns the active access token. * * @throws {GlpiAuthenticationError} When no authentication provider is configured or authentication fails. */ login(): Promise; /** * Logs out from the current GLPI session, destroying server-side session and clearing cached credentials. */ logout(): Promise; /** * Obtains a generic resource service instance for the given resource name or alias. * * @typeParam T - Type representing the resource entity. * @param name - Resource alias (e.g. 'Ticket', 'Rack') or endpoint path. * @returns A new ResourceService instance configured with the client REST transport. */ resource(name: string): ResourceService; /** * Registers a new resource route alias or overrides an existing one. * * @param alias - Resource alias name (e.g. 'Rack', 'NetworkSwitch'). * @param path - GLPI REST API route path (e.g. 'Assets/Rack'). */ registerResource(alias: string, path: string): void; /** * Scopes subsequent REST API requests to an entity and optional sub-entities. * * @param entityId - GLPI entity identifier, or undefined to clear entity scoping. * @param recursive - Whether to include sub-entities (defaults to false). */ setEntity(entityId?: number | string, recursive?: boolean): this; /** * Returns current entity scoping settings, if active. */ getEntity(): EntityScope | undefined; /** * Scopes subsequent REST API requests to a specific profile. * * @param profileId - GLPI profile identifier, or undefined to clear profile scoping. */ setProfile(profileId?: number | string): this; /** * Returns current profile scoping setting, if active. */ getProfile(): number | string | undefined; /** * Sets preferred language header (Accept-Language) for subsequent REST API requests. * * @param language - Language tag (e.g. 'en_US', 'fr_FR'), or undefined to clear. */ setLanguage(language?: string): this; /** * Returns current language preference, if set. */ getLanguage(): string | undefined; /** * Configures bearer token injection and 401 transparent retry interceptors on an HTTP client. */ private setupInterceptors; } /** * In-memory implementation of ITokenStorage. */ declare class InMemoryTokenStorage implements ITokenStorage { private token; constructor(initialToken?: TokenData | null); getToken(): Promise; setToken(token: TokenData): Promise; clearToken(): Promise; } /** * Manages token lifetime, proactive expiry buffers, and single-flight * deduplication of concurrent token refresh calls. */ declare class TokenManager { private readonly storage; private fetchFn?; private readonly proactiveMarginSeconds; private refreshPromise; private cachedToken; constructor(storage?: ITokenStorage, fetchFn?: TokenFetchFn, options?: TokenManagerOptions); /** * Sets or updates the token fetch/refresh function. */ setFetchFn(fetchFn: TokenFetchFn): void; /** * Checks whether a token is expired or within the proactive refresh margin. */ isExpired(token: TokenData): boolean; /** * Retrieves an active access token, executing a single deduplicated refresh if expired. */ getToken(): Promise; private executeRefresh; /** * Explicitly sets token data in both memory cache and storage. */ setToken(token: TokenData): Promise; /** * Retrieves the currently stored token payload. */ getStoredToken(): Promise; /** * Marks the current token as expired, forcing a refresh on the next getToken call * while preserving metadata (such as refreshToken). */ invalidateToken(): Promise; /** * Completely clears all token data. */ clearToken(): Promise; } /** * OAuth2 Resource Owner Password Credentials Grant provider for GLPI v2. * * GLPI's password grant returns access_token and expires_in but does not issue * a refresh_token. This provider retains credentials in memory and automatically * re-authenticates when the token expires or is invalidated. */ declare class PasswordAuthProvider implements IAuthProvider { private readonly httpClient; private readonly tokenEndpoint; private readonly clientId?; private readonly clientSecret?; private username; private password; private readonly scope?; private readonly tokenManager; constructor(options: PasswordAuthOptions); getAccessToken(): Promise; invalidateToken(): Promise; logout(): Promise; private fetchToken; } /** * OAuth2 Authorization Code Grant provider with refresh token rotation support. * * Supports initial authorization code exchange as well as session restoration * via persisted refresh tokens. */ declare class AuthorizationCodeAuthProvider implements IAuthProvider { private readonly httpClient; private readonly tokenEndpoint; private readonly clientId; private readonly clientSecret?; private readonly redirectUri?; private readonly scope?; private readonly storage; private readonly tokenManager; private code?; private refreshToken?; constructor(options: AuthCodeOptions); getAccessToken(): Promise; invalidateToken(): Promise; logout(): Promise; private fetchToken; private executeRefresh; private executeCodeExchange; private postToken; } /** * OAuth2 Client Credentials Grant provider for GLPI v2 (e.g. inventory agent scope). */ declare class ClientCredentialsAuthProvider implements IAuthProvider { private readonly httpClient; private readonly tokenEndpoint; private readonly clientId; private readonly clientSecret; private readonly scope?; private readonly tokenManager; constructor(options: ClientCredentialsOptions); getAccessToken(): Promise; invalidateToken(): Promise; logout(): Promise; private fetchToken; } declare const VERSION = "2.0.1"; export { type AuthCodeOptions, AuthorizationCodeAuthProvider, ClientCredentialsAuthProvider, type ClientCredentialsOptions, ComputerResource, ConsoleLogger, type CreateOptions, type CreateResult, DEFAULT_CORE_ROUTES, type DeleteOptions, type DocumentDownloadResult, type DocumentMetadata, DocumentResource, type DocumentUploadFile, type EntityScope, FetchHttpClient, type GlpiAuthOption, GlpiAuthenticationError, GlpiClient, type GlpiClientOptions, type GlpiComputer, type GlpiDocument, type GlpiEntityReference, GlpiError, GlpiGraphqlError, GlpiHttpError, type GlpiItemReference, GlpiNotFoundError, GlpiRateLimitError, type GlpiSessionInfo, type GlpiTicket, type GlpiUser, GlpiValidationError, GraphqlClient, type GraphqlError, type GraphqlErrorLocation, type GraphqlRequestOptions, type GraphqlResponse, type HttpClientConfig, type HttpMethod, type HttpRequestOptions, type HttpResponse, type IAuthProvider, type IGraphqlClient, type IHttpClient, type ILogger, type IResourceService, type ITokenStorage, InMemoryTokenStorage, type ListParams, NoopLogger, type OAuthTokenResponse, type PaginatedResult, type PasswordAuthOptions, PasswordAuthProvider, type PriorityLevel, type ProxyOptions, type RequestInterceptor, type RequestInterceptorFn, type RequestInterceptorObj, type RequestOptions, ResourceService, type ResponseInterceptor, type ResponseInterceptorFn, type ResponseInterceptorObj, RouteRegistry, RsqlBuilder, type RsqlNested, type TicketActorRole, type TicketActorType, TicketResource, TicketStatus, type TicketStatusInfo, type TicketTimelineItem, TicketType, type TokenData, type TokenFetchFn, type TokenFetchResult, TokenManager, type TokenManagerOptions, type UpdateOptions, UserResource, VERSION, escapeValue, rsql };