@polarityio/integration-types 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ import type { SelectTypeOptionValue } from './user-options';
2
+ import type { ThrottleSettings } from './limiter';
3
+ /**
4
+ * Base properties shared by all integration option types.
5
+ */
6
+ interface IntegrationOptionBase {
7
+ /** Unique key used to reference this option's value at runtime. */
8
+ key: string;
9
+ /** Human-readable name displayed in the UI. */
10
+ name: string;
11
+ /** Description text shown to the user. */
12
+ description?: string;
13
+ /** Whether only admins can view/edit this option. */
14
+ adminOnly?: boolean;
15
+ /** Whether non-admin users can edit this option. */
16
+ userCanEdit?: boolean;
17
+ }
18
+ /**
19
+ * A text or password option in `config.json`.
20
+ */
21
+ export interface TextOption extends IntegrationOptionBase {
22
+ type: 'text' | 'password';
23
+ default: string | null;
24
+ }
25
+ /**
26
+ * A boolean (checkbox) option in `config.json`.
27
+ */
28
+ export interface BooleanOption extends IntegrationOptionBase {
29
+ type: 'boolean';
30
+ default: boolean | null;
31
+ }
32
+ /**
33
+ * A numeric option in `config.json`.
34
+ */
35
+ export interface NumberOption extends IntegrationOptionBase {
36
+ type: 'number';
37
+ default: number | null;
38
+ }
39
+ /**
40
+ * A select (dropdown) option in `config.json`.
41
+ */
42
+ export interface SelectOption extends IntegrationOptionBase {
43
+ type: 'select';
44
+ /** Available choices for the dropdown. */
45
+ options: SelectTypeOptionValue[];
46
+ /** Default selection — a single item, multiple items, a string value, or null. */
47
+ default: SelectTypeOptionValue | SelectTypeOptionValue[] | string | null;
48
+ /** Whether multiple values can be selected. */
49
+ multiple?: boolean;
50
+ adminOnly: boolean;
51
+ userCanEdit: boolean;
52
+ }
53
+ /**
54
+ * Union of all integration option types that can appear in `config.json`.
55
+ */
56
+ export type IntegrationOption = TextOption | BooleanOption | NumberOption | SelectOption;
57
+ /**
58
+ * Log level configuration for the integration.
59
+ */
60
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
61
+ /**
62
+ * TLS/proxy request settings for the integration's HTTP client.
63
+ */
64
+ export interface RequestConfig {
65
+ /** Custom certificate authority (PEM-encoded or file path). */
66
+ ca?: string;
67
+ /** Client certificate (PEM-encoded or file path). */
68
+ cert?: string;
69
+ /** Client private key (PEM-encoded or file path). */
70
+ key?: string;
71
+ /** Passphrase for the client key. */
72
+ passphrase?: string;
73
+ /** HTTP/HTTPS proxy URL. */
74
+ proxy?: string;
75
+ /** Whether to reject connections with invalid TLS certificates. */
76
+ rejectUnauthorized?: boolean;
77
+ }
78
+ /**
79
+ * The structure of an integration's `config.json` file.
80
+ *
81
+ * This is the main manifest that defines an integration's metadata,
82
+ * data types, user-configurable options, and runtime settings.
83
+ *
84
+ * @example
85
+ * ```json
86
+ * {
87
+ * "polarityIntegrationUuid": "a1b2c3d4-...",
88
+ * "name": "My Integration",
89
+ * "acronym": "MI",
90
+ * "dataTypes": ["IPv4", "domain"],
91
+ * "options": [
92
+ * { "key": "apiKey", "name": "API Key", "type": "password", "default": "" }
93
+ * ]
94
+ * }
95
+ * ```
96
+ */
97
+ export interface IntegrationConfig {
98
+ /** Unique UUID assigned to this integration by Polarity. */
99
+ polarityIntegrationUuid: string;
100
+ /** Human-readable name of the integration. */
101
+ name: string;
102
+ /** Short acronym displayed in the UI (typically 2–4 characters). */
103
+ acronym: string;
104
+ /** Description of the integration's purpose. */
105
+ description?: string;
106
+ /** Default tag color (hex string, e.g. `"#1E90FF"`). */
107
+ defaultColor?: string;
108
+ /**
109
+ * Data types this integration subscribes to.
110
+ * Examples: `"IPv4"`, `"domain"`, `"hash"`, `"email"`, `"url"`.
111
+ */
112
+ dataTypes?: string[];
113
+ /** Whether the integration supports user-added custom types at runtime. */
114
+ supportsAdditionalCustomTypes?: boolean;
115
+ /** Whether the integration only runs on-demand (not on passive lookups). */
116
+ onDemandOnly?: boolean;
117
+ /** Whether to copy entity data to the clipboard on demand lookups. */
118
+ copyOnDemand?: boolean;
119
+ /** User-configurable options displayed in the integration settings UI. */
120
+ options?: IntegrationOption[];
121
+ /** Additional CSS stylesheet file paths to load. */
122
+ styles?: string[];
123
+ /** Logging configuration. */
124
+ logging?: {
125
+ level: LogLevel;
126
+ };
127
+ /** TLS and proxy settings for the integration's HTTP client. */
128
+ request?: RequestConfig;
129
+ /**
130
+ * Initial throttle/rate-limit settings for the integration's limiter.
131
+ * These are merged over platform defaults and passed to the throttle manager
132
+ * on startup. Accepts the same properties as {@link ThrottleSettings}.
133
+ *
134
+ * Platform-owned keys (`id`, `datastore`, `clearDatastore`, `clientOptions`,
135
+ * `connection`) are stripped during sanitization and must not be specified.
136
+ *
137
+ * @example
138
+ * ```json
139
+ * {
140
+ * "throttle": {
141
+ * "maxConcurrent": 5,
142
+ * "minTime": 200
143
+ * }
144
+ * }
145
+ * ```
146
+ */
147
+ throttle?: ThrottleSettings;
148
+ }
149
+ export {};
package/dist/context.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { Limiter } from './limiter';
1
2
  import type { Logger } from './logger';
2
3
  /**
3
4
  * Cache operation options.
@@ -126,6 +127,7 @@ export interface IntegrationContext {
126
127
  integrationId: string;
127
128
  userId: number;
128
129
  logger: Logger;
130
+ limiter: Limiter;
129
131
  startPolling: (pollName: string) => void;
130
132
  stopPolling: (pollName: string) => void;
131
133
  }
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export type { Channel, StandardEntityType, EntityType, EntityTypeIdentifier, Ent
2
2
  export type { SelectTypeOptionValue, PossibleUserOptionValue, DoLookupUserOptions, ValidateOptionsUserOption, ValidateOptionsUserOptions, ValidationError } from './user-options';
3
3
  export type { LookupResult, DoLookupResult } from './result';
4
4
  export type { CacheOptions, GlobalCache, IntegrationCache, UserCache, PolarityCache, IntegrationContext } from './context';
5
+ export type { ThrottleStrategy, ScheduleOptions, LimiterCounts, ThrottleSettings, ScopedLimiter, Limiter } from './limiter';
5
6
  export type { Logger } from './logger';
6
7
  export type { Integration } from './integration';
7
8
  export type { PollFunction, IntervalPollSpec, CronPollSpec, PollSpec, Poll } from './polling';
9
+ export type { TextOption, BooleanOption, NumberOption, SelectOption, IntegrationOption, LogLevel, RequestConfig, IntegrationConfig } from './config';
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Strategy for handling jobs when `highWater` is reached.
3
+ * - `1` (LEAK) — Drop the oldest job in the queue.
4
+ * - `2` (OVERFLOW_PRIORITY) — Drop the lowest-priority job.
5
+ * - `3` (OVERFLOW) — Drop the incoming job (reject it immediately).
6
+ * - `4` (BLOCK) — Block until a slot opens.
7
+ */
8
+ export type ThrottleStrategy = 1 | 2 | 3 | 4;
9
+ /**
10
+ * Options that can be passed to {@link Limiter.schedule} to control
11
+ * job priority and identification within the throttle queue.
12
+ */
13
+ export interface ScheduleOptions {
14
+ /** Priority of the job (1 = highest, 9 = lowest). Default is 5. */
15
+ priority?: number;
16
+ /** Optional identifier for the scheduled job (useful for debugging). */
17
+ id?: string;
18
+ /** Weight of the job against the `maxConcurrent` limit. Default is 1. */
19
+ weight?: number;
20
+ /** Maximum time (ms) a job can stay in the queue before being dropped. */
21
+ expiration?: number | null;
22
+ }
23
+ /**
24
+ * Current counts of jobs in various states within the limiter.
25
+ */
26
+ export interface LimiterCounts {
27
+ /** Number of jobs currently executing. */
28
+ EXECUTING: number;
29
+ /** Number of jobs waiting in the queue. */
30
+ QUEUED: number;
31
+ /** Number of jobs currently running (alias for EXECUTING in some contexts). */
32
+ RUNNING: number;
33
+ /** Number of jobs that have completed. */
34
+ DONE: number;
35
+ /** Number of jobs received but not yet queued or executing. */
36
+ RECEIVED: number;
37
+ }
38
+ /**
39
+ * Settings that can be dynamically updated on the limiter at runtime.
40
+ * All properties are optional — only provided values are changed.
41
+ */
42
+ export interface ThrottleSettings {
43
+ /**
44
+ * Maximum number of jobs that can execute concurrently.
45
+ * @default 10
46
+ */
47
+ maxConcurrent?: number;
48
+ /**
49
+ * Minimum time (in milliseconds) between job starts.
50
+ * @default 100
51
+ */
52
+ minTime?: number;
53
+ /**
54
+ * Maximum number of jobs allowed in the queue.
55
+ * Jobs submitted beyond this limit are handled according to `strategy`.
56
+ * @default 100
57
+ */
58
+ highWater?: number;
59
+ /**
60
+ * Strategy for handling jobs when `highWater` is reached.
61
+ * - `1` (LEAK): Drop the oldest job in the queue.
62
+ * - `2` (OVERFLOW_PRIORITY): Drop the lowest-priority job.
63
+ * - `3` (OVERFLOW): Drop the incoming job (reject it immediately).
64
+ * - `4` (BLOCK): Block until a slot opens.
65
+ * @default 3 (OVERFLOW)
66
+ */
67
+ strategy?: ThrottleStrategy;
68
+ /**
69
+ * Reservoir — the total number of jobs the limiter will execute before
70
+ * stopping. Useful for API rate limits (e.g., 100 requests per minute).
71
+ * Set to `null` to disable.
72
+ */
73
+ reservoir?: number | null;
74
+ /**
75
+ * Interval (ms) at which the reservoir is automatically refilled.
76
+ */
77
+ reservoirRefreshInterval?: number | null;
78
+ /**
79
+ * Value to reset the reservoir to on each refresh interval.
80
+ */
81
+ reservoirRefreshAmount?: number | null;
82
+ /**
83
+ * Maximum value the reservoir can reach when being incremented.
84
+ */
85
+ reservoirIncreaseMaximum?: number | null;
86
+ /**
87
+ * Amount to increase the reservoir by on each interval.
88
+ */
89
+ reservoirIncreaseAmount?: number | null;
90
+ /**
91
+ * Interval (ms) at which the reservoir is incremented.
92
+ */
93
+ reservoirIncreaseInterval?: number | null;
94
+ }
95
+ /**
96
+ * A scoped limiter instance bound to a specific key (e.g., a user or tenant).
97
+ * Scoped limiters share the same settings as the parent but maintain
98
+ * independent concurrency/rate state per scope key. Idle scopes are
99
+ * garbage-collected after 5 minutes of inactivity.
100
+ */
101
+ export interface ScopedLimiter {
102
+ /**
103
+ * Schedule an async job within this scope's rate limit.
104
+ *
105
+ * @param fn - The async function to execute when a slot is available.
106
+ * Any additional arguments after `fn` are passed through as arguments to `fn`.
107
+ * @param args - Optional arguments forwarded to `fn` when it is invoked.
108
+ * @returns A promise that resolves with the return value of `fn`.
109
+ *
110
+ * @example Closure style — capture variables from surrounding scope
111
+ * ```ts
112
+ * const scoped = context.limiter.scope(userId);
113
+ * const result = await scoped.schedule(async () => {
114
+ * return await fetchUserData(userId);
115
+ * });
116
+ * ```
117
+ *
118
+ * @example Function reference style — pass arguments through to fn
119
+ * ```ts
120
+ * async function fetchUserPage(id: string, page: number) {
121
+ * return await apiClient.get(`/users/${id}/page/${page}`);
122
+ * }
123
+ *
124
+ * const scoped = context.limiter.scope(userId);
125
+ * const result = await scoped.schedule(fetchUserPage, userId, 1);
126
+ * ```
127
+ */
128
+ schedule<T, A extends unknown[]>(fn: (...args: A) => PromiseLike<T>, ...args: A): Promise<T>;
129
+ /**
130
+ * Schedule an async job with explicit scheduling options.
131
+ *
132
+ * @param options - Priority, id, weight, and expiration settings.
133
+ * @param fn - The async function to execute when a slot is available.
134
+ * Any additional arguments after `fn` are passed through as arguments to `fn`.
135
+ * @param args - Optional arguments forwarded to `fn` when it is invoked.
136
+ * @returns A promise that resolves with the return value of `fn`.
137
+ *
138
+ * @example Closure style — capture variables from surrounding scope
139
+ * ```ts
140
+ * const scoped = context.limiter.scope(userId);
141
+ * const result = await scoped.schedule(
142
+ * { priority: 1 },
143
+ * async () => await fetchPriorityData(userId)
144
+ * );
145
+ * ```
146
+ *
147
+ * @example Function reference style — pass arguments through to fn
148
+ * ```ts
149
+ * async function fetchPriorityData(id: string) {
150
+ * return await apiClient.get(`/users/${id}/priority`);
151
+ * }
152
+ *
153
+ * const scoped = context.limiter.scope(userId);
154
+ * const result = await scoped.schedule(
155
+ * { priority: 1 },
156
+ * fetchPriorityData,
157
+ * userId
158
+ * );
159
+ * ```
160
+ */
161
+ schedule<T, A extends unknown[]>(options: ScheduleOptions, fn: (...args: A) => PromiseLike<T>, ...args: A): Promise<T>;
162
+ }
163
+ /**
164
+ * Distributed rate limiter available on the integration context as `context.limiter`.
165
+ *
166
+ * Backed by Redis (via Bottleneck) so all workers for an integration share
167
+ * rate-limit state. Supports global throttling, per-key scoped throttling,
168
+ * and dynamic settings updates at runtime.
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * // Basic usage — schedule work through the global limiter
173
+ * const result = await context.limiter.schedule(async () => {
174
+ * return await apiClient.get('/resource');
175
+ * });
176
+ *
177
+ * // Per-user scoped throttling
178
+ * const userResult = await context.limiter.scope(userId).schedule(async () => {
179
+ * return await apiClient.get(`/users/${userId}/data`);
180
+ * });
181
+ *
182
+ * // Dynamically tighten the rate limit
183
+ * await context.limiter.updateSettings({ minTime: 500, maxConcurrent: 5 });
184
+ * ```
185
+ */
186
+ export interface Limiter {
187
+ /**
188
+ * Schedule an async job to run within the integration's global rate limit.
189
+ * The job will execute once a concurrency slot is available and the
190
+ * minimum time between jobs has elapsed.
191
+ *
192
+ * @param fn - The async function to execute when a slot is available.
193
+ * Any additional arguments after `fn` are passed through as arguments to `fn`.
194
+ * @param args - Optional arguments forwarded to `fn` when it is invoked.
195
+ * @returns A promise that resolves with the return value of `fn`.
196
+ *
197
+ * @example Closure style — capture variables from surrounding scope
198
+ * ```ts
199
+ * const data = await context.limiter.schedule(async () => {
200
+ * return await fetch('https://api.example.com/data');
201
+ * });
202
+ * ```
203
+ *
204
+ * @example Function reference style — pass arguments through to fn
205
+ * ```ts
206
+ * async function fetchData(url: string, headers: Record<string, string>) {
207
+ * return await fetch(url, { headers });
208
+ * }
209
+ *
210
+ * const data = await context.limiter.schedule(
211
+ * fetchData,
212
+ * 'https://api.example.com/data',
213
+ * { Authorization: 'Bearer token' }
214
+ * );
215
+ * ```
216
+ */
217
+ schedule<T, A extends unknown[]>(fn: (...args: A) => PromiseLike<T>, ...args: A): Promise<T>;
218
+ /**
219
+ * Schedule an async job with explicit scheduling options (priority, id, etc.).
220
+ *
221
+ * @param options - Options controlling priority, weight, and expiration.
222
+ * @param fn - The async function to execute when a slot is available.
223
+ * Any additional arguments after `fn` are passed through as arguments to `fn`.
224
+ * @param args - Optional arguments forwarded to `fn` when it is invoked.
225
+ * @returns A promise that resolves with the return value of `fn`.
226
+ *
227
+ * @example Closure style — capture variables from surrounding scope
228
+ * ```ts
229
+ * const result = await context.limiter.schedule(
230
+ * { priority: 1, id: 'critical-job' },
231
+ * async () => await criticalApiCall()
232
+ * );
233
+ * ```
234
+ *
235
+ * @example Function reference style — pass arguments through to fn
236
+ * ```ts
237
+ * async function fetchEndpoint(endpoint: string) {
238
+ * return await apiClient.get(endpoint);
239
+ * }
240
+ *
241
+ * const result = await context.limiter.schedule(
242
+ * { priority: 1, id: 'critical-job' },
243
+ * fetchEndpoint,
244
+ * '/critical-resource'
245
+ * );
246
+ * ```
247
+ */
248
+ schedule<T, A extends unknown[]>(options: ScheduleOptions, fn: (...args: A) => PromiseLike<T>, ...args: A): Promise<T>;
249
+ /**
250
+ * Dynamically update the limiter's throttle settings at runtime.
251
+ * Updates propagate to all scoped (per-key) limiters as well.
252
+ *
253
+ * Only the provided properties are changed; omitted properties retain
254
+ * their current values.
255
+ *
256
+ * @param updates - Partial throttle settings to apply.
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * // Slow down after receiving a 429 response
261
+ * await context.limiter.updateSettings({ minTime: 1000, maxConcurrent: 2 });
262
+ * ```
263
+ */
264
+ updateSettings(updates: ThrottleSettings): Promise<void>;
265
+ /**
266
+ * Get current job counts (executing, queued, running, done, received).
267
+ *
268
+ * @returns An object with counts for each job state.
269
+ *
270
+ * @example
271
+ * ```ts
272
+ * const counts = context.limiter.counts();
273
+ * console.log(`${counts.EXECUTING} jobs running, ${counts.QUEUED} queued`);
274
+ * ```
275
+ */
276
+ counts(): LimiterCounts;
277
+ /**
278
+ * Get or create a scoped limiter for the given identifier.
279
+ * Scoped limiters are useful for per-user or per-tenant rate limiting.
280
+ * Each scope maintains independent concurrency and timing state but
281
+ * inherits settings from the parent. Idle scopes are garbage-collected
282
+ * after 5 minutes.
283
+ *
284
+ * @param identifier - A unique key for this scope (e.g., user ID, tenant ID).
285
+ * @returns A {@link ScopedLimiter} bound to the given key.
286
+ *
287
+ * @example
288
+ * ```ts
289
+ * const userLimiter = context.limiter.scope(userId);
290
+ * const result = await userLimiter.schedule(async () => {
291
+ * return await fetchUserSpecificData(userId);
292
+ * });
293
+ * ```
294
+ */
295
+ scope(identifier: string): ScopedLimiter;
296
+ /**
297
+ * Get a snapshot of the current throttle settings.
298
+ *
299
+ * @returns A copy of the active settings (maxConcurrent, minTime, etc.).
300
+ */
301
+ settings(): ThrottleSettings;
302
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polarityio/integration-types",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "TypeScript type definitions for Polarity Integrations",
5
5
  "types": "./dist/index.d.ts",
6
6
  "exports": {