@henriquecosta/chaos-api 1.0.0 → 1.0.2

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.
package/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # @henriquecosta/chaos-api
2
+
3
+ Middleware pra simular falhas de produção — delay, erros, timeout, indisponibilidade, respostas malformadas/obsoletas — em APIs Express/Fastify/NestJS/Koa durante desenvolvimento.
4
+
5
+ Vem com control API + dashboard UI pra ligar/desligar cenários em tempo real, e um wrapper de `fetch` outbound pra injetar caos em chamadas que sua aplicação faz pra APIs de terceiros.
6
+
7
+ ## Instalação
8
+
9
+ ```bash
10
+ npm install @henriquecosta/chaos-api
11
+ ```
12
+
13
+ ## Início rápido (Express)
14
+
15
+ ```ts
16
+ import express from "express";
17
+ import { chaos } from "@henriquecosta/chaos-api";
18
+
19
+ const app = express();
20
+ const chaosMiddleware = chaos({ controlPort: 51820 });
21
+
22
+ app.use(chaosMiddleware);
23
+
24
+ app.get("/orders/:id", (req, res) => {
25
+ res.json({ id: req.params.id });
26
+ });
27
+
28
+ app.listen(3000);
29
+ ```
30
+
31
+ Registre um cenário no store exposto pelo middleware:
32
+
33
+ ```ts
34
+ chaosMiddleware.store.register({
35
+ type: "delay",
36
+ scope: { pattern: "/orders/*" },
37
+ rate: 0.5, // aplica em 50% das requisições que casam com o scope
38
+ options: { minMs: 300, maxMs: 1500 },
39
+ });
40
+ ```
41
+
42
+ Rode `npx chaos-api dashboard` e abra `http://localhost:4000/dashboard` pra alternar cenários visualmente em vez disso (ele fala com a `controlPort` acima).
43
+
44
+ ## Adapters de framework
45
+
46
+ ### Fastify
47
+
48
+ ```ts
49
+ import Fastify from "fastify";
50
+ import { chaosFastifyPlugin } from "@henriquecosta/chaos-api";
51
+
52
+ const fastify = Fastify();
53
+ const chaosPlugin = chaosFastifyPlugin({ controlPort: 51820 });
54
+
55
+ await fastify.register(chaosPlugin);
56
+ ```
57
+
58
+ ### NestJS
59
+
60
+ ```ts
61
+ // main.ts
62
+ import { createChaosNestMiddleware } from "@henriquecosta/chaos-api";
63
+
64
+ app.use(createChaosNestMiddleware({ controlPort: 51820 }));
65
+ ```
66
+
67
+ Ou registre por módulo via `NestModule.configure()`:
68
+
69
+ ```ts
70
+ consumer.apply(createChaosNestMiddleware()).forRoutes("*");
71
+ ```
72
+
73
+ ### Koa
74
+
75
+ ```ts
76
+ import Koa from "koa";
77
+ import { chaosKoaMiddleware } from "@henriquecosta/chaos-api";
78
+
79
+ const app = new Koa();
80
+ app.use(chaosKoaMiddleware({ controlPort: 51820 }));
81
+ ```
82
+
83
+ ## Tipos de cenário
84
+
85
+ Seis primitivos, casados por caminho da requisição (`scope`) e probabilidade (`rate`):
86
+
87
+ | type | efeito |
88
+ | -------------------- | ----------------------------------------------------------------- |
89
+ | `delay` | Adiciona latência antes de continuar a requisição (`minMs`/`maxMs`). |
90
+ | `error-response` | Interrompe com status/body (`statusCodes`, `body`, `headers`, `methods`). |
91
+ | `connection-reset` | Derruba a conexão — nenhuma resposta é escrita. |
92
+ | `unavailable` | Retorna um status fixo de indisponibilidade (`statusCode`, padrão 503). |
93
+ | `malformed-response` | Retorna um body de resposta estruturalmente quebrado. |
94
+ | `stale-response` | Retorna um body de resposta em cache/desatualizado. |
95
+
96
+ ```ts
97
+ chaosMiddleware.store.register({
98
+ type: "error-response",
99
+ scope: { pattern: "/payments/*" },
100
+ direction: "inbound", // padrão; "outbound" escopa pelo host de destino em vez do path
101
+ rate: 0.2,
102
+ options: { statusCodes: [500, 502], body: { error: "payment provider unavailable" } },
103
+ });
104
+ ```
105
+
106
+ Use `scope: "global"` (padrão) pra aplicar um cenário em todas as rotas.
107
+
108
+ ## Presets
109
+
110
+ Catálogo com ~85 itens de cenários nomeados e pré-configurados (queda de auth, timeout de terceiros, erro de config etc.) mapeados sobre os seis primitivos acima:
111
+
112
+ ```ts
113
+ import { applyPreset, listPresets } from "@henriquecosta/chaos-api";
114
+
115
+ listPresets("dependencias-externas"); // navega por categoria
116
+
117
+ applyPreset(chaosMiddleware.store, "third-party-rate-limit", {
118
+ scope: { pattern: "/checkout/*" },
119
+ rate: 0.3,
120
+ });
121
+ ```
122
+
123
+ ## Caos outbound (chamadas que sua aplicação faz)
124
+
125
+ Envolva o `fetch` pra que cenários registrados com `direction: "outbound"` intercepetem chamadas pra um host de destino:
126
+
127
+ ```ts
128
+ import { createChaosFetch } from "@henriquecosta/chaos-api";
129
+
130
+ const chaosFetch = createChaosFetch(chaosMiddleware.store);
131
+
132
+ chaosMiddleware.store.register({
133
+ type: "connection-reset",
134
+ direction: "outbound",
135
+ scope: { pattern: "api.stripe.com" },
136
+ rate: 0.1,
137
+ });
138
+
139
+ await chaosFetch("https://api.stripe.com/v1/charges"); // pode lançar uma falha de rede simulada
140
+ ```
141
+
142
+ ## Guardrail de produção
143
+
144
+ Cenários são desabilitados automaticamente quando `NODE_ENV=production`, pra evitar que um cenário ativo vaze pro tráfego real. Override (não recomendado) com:
145
+
146
+ ```ts
147
+ chaos({ allowInProduction: true });
148
+ ```
149
+
150
+ ## CLI do dashboard
151
+
152
+ ```bash
153
+ npx chaos-api dashboard [--port <n>] [--control-port <n>] [--no-control-api]
154
+ ```
155
+
156
+ Serve a UI do dashboard (padrão `http://localhost:4000/dashboard`). Por padrão também sobe uma control API standalone pra demo; passe `--no-control-api` quando sua aplicação já roda `chaos({ controlPort })` e você só quer a UI.
157
+
158
+ ## Licença
159
+
160
+ MIT
@@ -1,6 +1,7 @@
1
1
  import type { NextFunction, Request, Response } from "express";
2
2
  import type { Server } from "node:http";
3
3
  import { ActivityLog } from "../core/activity-log.js";
4
+ import { type IgnorePathPattern } from "../core/ignore-paths.js";
4
5
  import { StateStore } from "../core/state-store.js";
5
6
  export interface ChaosOptions {
6
7
  /** Bypass the NODE_ENV=production guardrail. Not recommended. */
@@ -9,8 +10,16 @@ export interface ChaosOptions {
9
10
  store?: StateStore;
10
11
  /** Reuse an existing ActivityLog (e.g. to share state across adapters in tests). */
11
12
  activityLog?: ActivityLog;
13
+ /** Max events kept by the activity feed (docs/PRD.md 6.5). Default 200. Ignored if `activityLog` is passed. */
14
+ activityLogCapacity?: number;
12
15
  /** If set, starts the local control API on this port for the dashboard UI to talk to. */
13
16
  controlPort?: number;
17
+ /** Bind address for the control API. Default `"127.0.0.1"` — keep it off the network unless you mean to expose it. */
18
+ controlHost?: string;
19
+ /** `Access-Control-Allow-Origin` for the control API. Default `"*"`. */
20
+ corsOrigin?: string;
21
+ /** Paths that always bypass chaos scenarios (glob strings like `"/health*"` or RegExp), e.g. health checks. */
22
+ ignorePaths?: IgnorePathPattern[];
14
23
  }
15
24
  export interface ChaosInstance {
16
25
  (req: Request, res: Response, next: NextFunction): void;
@@ -1,14 +1,15 @@
1
1
  import { ActivityLog } from "../core/activity-log.js";
2
+ import { isIgnoredPath } from "../core/ignore-paths.js";
2
3
  import { ScenarioEngine } from "../core/scenario-engine.js";
3
4
  import { StateStore } from "../core/state-store.js";
4
5
  import { createControlApi } from "../dashboard/server/control-api.js";
5
6
  import { isBlockedByGuardrail } from "../guardrail.js";
6
7
  export function chaos(options = {}) {
7
8
  const store = options.store ?? new StateStore();
8
- const activityLog = options.activityLog ?? new ActivityLog();
9
+ const activityLog = options.activityLog ?? new ActivityLog(options.activityLogCapacity);
9
10
  const engine = new ScenarioEngine(store, activityLog);
10
11
  const middleware = ((req, res, next) => {
11
- if (isBlockedByGuardrail(options)) {
12
+ if (isBlockedByGuardrail(options) || isIgnoredPath(req.path, options.ignorePaths)) {
12
13
  next();
13
14
  return;
14
15
  }
@@ -34,7 +35,7 @@ export function chaos(options = {}) {
34
35
  middleware.store = store;
35
36
  middleware.activityLog = activityLog;
36
37
  if (options.controlPort) {
37
- middleware.controlApi = createControlApi(store, activityLog).listen(options.controlPort);
38
+ middleware.controlApi = createControlApi(store, activityLog, { corsOrigin: options.corsOrigin }).listen(options.controlPort, options.controlHost ?? "127.0.0.1");
38
39
  }
39
40
  return middleware;
40
41
  }
@@ -1,15 +1,17 @@
1
1
  import { ActivityLog } from "../core/activity-log.js";
2
+ import { isIgnoredPath } from "../core/ignore-paths.js";
2
3
  import { ScenarioEngine } from "../core/scenario-engine.js";
3
4
  import { StateStore } from "../core/state-store.js";
4
5
  import { createControlApi } from "../dashboard/server/control-api.js";
5
6
  import { isBlockedByGuardrail } from "../guardrail.js";
6
7
  export function chaosFastifyPlugin(options = {}) {
7
8
  const store = options.store ?? new StateStore();
8
- const activityLog = options.activityLog ?? new ActivityLog();
9
+ const activityLog = options.activityLog ?? new ActivityLog(options.activityLogCapacity);
9
10
  const engine = new ScenarioEngine(store, activityLog);
10
11
  const plugin = (async (fastify) => {
11
12
  fastify.addHook("onRequest", async (request, reply) => {
12
- if (isBlockedByGuardrail(options))
13
+ const path = request.url.split("?")[0];
14
+ if (isBlockedByGuardrail(options) || isIgnoredPath(path, options.ignorePaths))
13
15
  return;
14
16
  const controller = {
15
17
  status: (code) => {
@@ -22,7 +24,6 @@ export function chaosFastifyPlugin(options = {}) {
22
24
  reply.send(body);
23
25
  },
24
26
  };
25
- const path = request.url.split("?")[0];
26
27
  const result = await engine.resolve({ method: request.method, path }, controller);
27
28
  if (result === "terminated" && !reply.sent) {
28
29
  // random-timeout: no response was written on purpose — take Fastify
@@ -38,7 +39,7 @@ export function chaosFastifyPlugin(options = {}) {
38
39
  plugin.store = store;
39
40
  plugin.activityLog = activityLog;
40
41
  if (options.controlPort) {
41
- plugin.controlApi = createControlApi(store, activityLog).listen(options.controlPort);
42
+ plugin.controlApi = createControlApi(store, activityLog, { corsOrigin: options.corsOrigin }).listen(options.controlPort, options.controlHost ?? "127.0.0.1");
42
43
  }
43
44
  return plugin;
44
45
  }
@@ -1,4 +1,5 @@
1
1
  import { ActivityLog } from "../core/activity-log.js";
2
+ import { isIgnoredPath } from "../core/ignore-paths.js";
2
3
  import { ScenarioEngine } from "../core/scenario-engine.js";
3
4
  import { StateStore } from "../core/state-store.js";
4
5
  import { createControlApi } from "../dashboard/server/control-api.js";
@@ -6,10 +7,10 @@ import { isBlockedByGuardrail } from "../guardrail.js";
6
7
  /** docs/PRD.md 6.6 — thin adapter over the shared core, same pattern as adapters/express.ts and adapters/fastify.ts. */
7
8
  export function chaosKoaMiddleware(options = {}) {
8
9
  const store = options.store ?? new StateStore();
9
- const activityLog = options.activityLog ?? new ActivityLog();
10
+ const activityLog = options.activityLog ?? new ActivityLog(options.activityLogCapacity);
10
11
  const engine = new ScenarioEngine(store, activityLog);
11
12
  const middleware = (async (ctx, next) => {
12
- if (isBlockedByGuardrail(options)) {
13
+ if (isBlockedByGuardrail(options) || isIgnoredPath(ctx.path, options.ignorePaths)) {
13
14
  await next();
14
15
  return;
15
16
  }
@@ -41,7 +42,7 @@ export function chaosKoaMiddleware(options = {}) {
41
42
  middleware.store = store;
42
43
  middleware.activityLog = activityLog;
43
44
  if (options.controlPort) {
44
- middleware.controlApi = createControlApi(store, activityLog).listen(options.controlPort);
45
+ middleware.controlApi = createControlApi(store, activityLog, { corsOrigin: options.corsOrigin }).listen(options.controlPort, options.controlHost ?? "127.0.0.1");
45
46
  }
46
47
  return middleware;
47
48
  }
@@ -1,4 +1,5 @@
1
1
  import { ActivityLog } from "../core/activity-log.js";
2
+ import { isIgnoredPath } from "../core/ignore-paths.js";
2
3
  import { ScenarioEngine } from "../core/scenario-engine.js";
3
4
  import { StateStore } from "../core/state-store.js";
4
5
  import { createControlApi } from "../dashboard/server/control-api.js";
@@ -10,10 +11,11 @@ import { isBlockedByGuardrail } from "../guardrail.js";
10
11
  */
11
12
  export function createChaosNestMiddleware(options = {}) {
12
13
  const store = options.store ?? new StateStore();
13
- const activityLog = options.activityLog ?? new ActivityLog();
14
+ const activityLog = options.activityLog ?? new ActivityLog(options.activityLogCapacity);
14
15
  const engine = new ScenarioEngine(store, activityLog);
15
16
  const middleware = ((req, res, next) => {
16
- if (isBlockedByGuardrail(options)) {
17
+ const path = (req.originalUrl ?? req.url).split("?")[0];
18
+ if (isBlockedByGuardrail(options) || isIgnoredPath(path, options.ignorePaths)) {
17
19
  next();
18
20
  return;
19
21
  }
@@ -34,7 +36,6 @@ export function createChaosNestMiddleware(options = {}) {
34
36
  res.end(typeof body === "string" ? body : JSON.stringify(body));
35
37
  },
36
38
  };
37
- const path = (req.originalUrl ?? req.url).split("?")[0];
38
39
  engine
39
40
  .resolve({ method: req.method, path }, controller)
40
41
  .then((result) => {
@@ -46,7 +47,7 @@ export function createChaosNestMiddleware(options = {}) {
46
47
  middleware.store = store;
47
48
  middleware.activityLog = activityLog;
48
49
  if (options.controlPort) {
49
- middleware.controlApi = createControlApi(store, activityLog).listen(options.controlPort);
50
+ middleware.controlApi = createControlApi(store, activityLog, { corsOrigin: options.corsOrigin }).listen(options.controlPort, options.controlHost ?? "127.0.0.1");
50
51
  }
51
52
  return middleware;
52
53
  }
@@ -14,20 +14,25 @@ function hasFlag(flag) {
14
14
  }
15
15
  if (command === "dashboard") {
16
16
  const portFlag = flagValue("--port");
17
- startDashboard({ port: portFlag ? Number(portFlag) : undefined });
17
+ const hostFlag = flagValue("--host");
18
+ startDashboard({ port: portFlag ? Number(portFlag) : undefined, host: hostFlag });
18
19
  if (!hasFlag("--no-control-api")) {
19
20
  const controlPortFlag = flagValue("--control-port");
21
+ const controlHostFlag = flagValue("--control-host");
22
+ const corsOriginFlag = flagValue("--cors-origin");
20
23
  const controlPort = controlPortFlag ? Number(controlPortFlag) : DEFAULT_CONTROL_PORT;
24
+ const controlHost = controlHostFlag ?? "127.0.0.1";
21
25
  const store = new StateStore();
22
26
  const activityLog = new ActivityLog();
23
- createControlApi(store, activityLog).listen(controlPort, () => {
24
- console.log(`[chaos-api] standalone control API running at http://localhost:${controlPort} ` +
27
+ createControlApi(store, activityLog, { corsOrigin: corsOriginFlag }).listen(controlPort, controlHost, () => {
28
+ console.log(`[chaos-api] standalone control API running at http://${controlHost}:${controlPort} ` +
25
29
  "(demo StateStore, not wired to a real app — pass --no-control-api if your app " +
26
30
  "already runs chaos({ controlPort }) itself)");
27
31
  });
28
32
  }
29
33
  }
30
34
  else {
31
- console.error(`Unknown command: ${command ?? "(none)"}. Usage: chaos-api dashboard [--port <n>] [--control-port <n>] [--no-control-api]`);
35
+ console.error(`Unknown command: ${command ?? "(none)"}. Usage: chaos-api dashboard ` +
36
+ "[--port <n>] [--host <addr>] [--control-port <n>] [--control-host <addr>] [--cors-origin <origin>] [--no-control-api]");
32
37
  process.exit(1);
33
38
  }
@@ -0,0 +1,7 @@
1
+ export type IgnorePathPattern = string | RegExp;
2
+ /**
3
+ * True if `path` matches one of the configured ignore patterns — those requests bypass chaos
4
+ * scenarios entirely (e.g. health checks, the control API's own routes when mounted on the same
5
+ * server as the host app). String patterns use the same glob syntax as scenario scopes (`*`).
6
+ */
7
+ export declare function isIgnoredPath(path: string, patterns?: IgnorePathPattern[]): boolean;
@@ -0,0 +1,11 @@
1
+ import { globToRegex } from "./state-store.js";
2
+ /**
3
+ * True if `path` matches one of the configured ignore patterns — those requests bypass chaos
4
+ * scenarios entirely (e.g. health checks, the control API's own routes when mounted on the same
5
+ * server as the host app). String patterns use the same glob syntax as scenario scopes (`*`).
6
+ */
7
+ export function isIgnoredPath(path, patterns) {
8
+ if (!patterns?.length)
9
+ return false;
10
+ return patterns.some((pattern) => (typeof pattern === "string" ? globToRegex(pattern) : pattern).test(path));
11
+ }
@@ -1,9 +1,13 @@
1
1
  import { type Server } from "node:http";
2
2
  import type { ActivityLog } from "../../core/activity-log.js";
3
3
  import type { StateStore } from "../../core/state-store.js";
4
+ export interface ControlApiOptions {
5
+ /** `Access-Control-Allow-Origin` value. Default `"*"` (dashboard-ui may run on any origin/port). */
6
+ corsOrigin?: string;
7
+ }
4
8
  /**
5
9
  * Local control API for the scenario StateStore living inside the user's app process.
6
10
  * dashboard-ui talks to this directly (CORS-open, localhost-only by convention) — the
7
11
  * dashboard-server process only serves static UI files, it does not proxy this API.
8
12
  */
9
- export declare function createControlApi(store: StateStore, activityLog?: ActivityLog): Server;
13
+ export declare function createControlApi(store: StateStore, activityLog?: ActivityLog, options?: ControlApiOptions): Server;
@@ -1,7 +1,6 @@
1
1
  import { createServer } from "node:http";
2
2
  import { applyPreset, findPreset, listPresets } from "../../presets/index.js";
3
3
  const CORS_HEADERS = {
4
- "Access-Control-Allow-Origin": "*",
5
4
  "Access-Control-Allow-Methods": "GET,POST,PATCH,DELETE,OPTIONS",
6
5
  "Access-Control-Allow-Headers": "Content-Type",
7
6
  };
@@ -10,12 +9,14 @@ const CORS_HEADERS = {
10
9
  * dashboard-ui talks to this directly (CORS-open, localhost-only by convention) — the
11
10
  * dashboard-server process only serves static UI files, it does not proxy this API.
12
11
  */
13
- export function createControlApi(store, activityLog) {
12
+ export function createControlApi(store, activityLog, options = {}) {
13
+ const corsOrigin = options.corsOrigin ?? "*";
14
14
  return createServer((req, res) => {
15
- void handleRequest(req, res, store, activityLog);
15
+ void handleRequest(req, res, store, activityLog, corsOrigin);
16
16
  });
17
17
  }
18
- async function handleRequest(req, res, store, activityLog) {
18
+ async function handleRequest(req, res, store, activityLog, corsOrigin) {
19
+ res.setHeader("Access-Control-Allow-Origin", corsOrigin);
19
20
  for (const [key, value] of Object.entries(CORS_HEADERS))
20
21
  res.setHeader(key, value);
21
22
  if (req.method === "OPTIONS") {
@@ -23,12 +24,19 @@ async function handleRequest(req, res, store, activityLog) {
23
24
  return;
24
25
  }
25
26
  const url = new URL(req.url ?? "/", "http://localhost");
26
- const segments = url.pathname.split("/").filter(Boolean);
27
+ const allSegments = url.pathname.split("/").filter(Boolean);
28
+ // Anchor on the *last* "api" segment, not position 0 — a host may mount this
29
+ // control API (or proxy requests to it) underneath its own base path (e.g.
30
+ // `/api/v1/notebooks/api/activity`). Anchoring on position 0 breaks in that
31
+ // case; anchoring on the last "api" keeps the package route-independent of
32
+ // wherever the host puts it.
33
+ const apiIndex = allSegments.lastIndexOf("api");
27
34
  try {
28
- if (segments[0] !== "api") {
35
+ if (apiIndex === -1) {
29
36
  notFound(res);
30
37
  return;
31
38
  }
39
+ const segments = allSegments.slice(apiIndex);
32
40
  if (segments[1] === "activity" && segments.length === 2 && req.method === "GET") {
33
41
  const limitParam = url.searchParams.get("limit");
34
42
  sendJson(res, 200, activityLog?.list(limitParam ? Number(limitParam) : undefined) ?? []);
@@ -1,6 +1,8 @@
1
1
  import { type Server } from "node:http";
2
2
  export interface StartDashboardOptions {
3
3
  port?: number;
4
+ /** Bind address. Default `"127.0.0.1"` — set to `"0.0.0.0"` to expose it beyond localhost. */
5
+ host?: string;
4
6
  }
5
7
  /**
6
8
  * Serves the static dashboard-ui. This process does not hold any scenario state —
@@ -16,11 +16,12 @@ const MIME = {
16
16
  */
17
17
  export function startDashboard(options = {}) {
18
18
  const port = options.port ?? 4000;
19
+ const host = options.host ?? "127.0.0.1";
19
20
  const server = createServer((req, res) => {
20
21
  void serveStatic(req.url ?? "/", res);
21
22
  });
22
- server.listen(port, () => {
23
- console.log(`[chaos-api] dashboard running at http://localhost:${port}/dashboard`);
23
+ server.listen(port, host, () => {
24
+ console.log(`[chaos-api] dashboard running at http://${host}:${port}/dashboard`);
24
25
  });
25
26
  return server;
26
27
  }
@@ -1,6 +1,8 @@
1
1
  const STORAGE_KEY = "chaos-api:control-url";
2
+ const POLL_STORAGE_KEY = "chaos-api:poll-interval";
2
3
 
3
4
  const controlUrlInput = document.getElementById("control-url");
5
+ const pollIntervalInput = document.getElementById("poll-interval");
4
6
  const connectButton = document.getElementById("connect");
5
7
  const listEl = document.getElementById("scenario-list");
6
8
  const bannerEl = document.getElementById("status-banner");
@@ -26,6 +28,7 @@ const PRESET_CATEGORIES = [
26
28
  let activePresetCategory = "";
27
29
 
28
30
  controlUrlInput.value = localStorage.getItem(STORAGE_KEY) || controlUrlInput.value;
31
+ pollIntervalInput.value = localStorage.getItem(POLL_STORAGE_KEY) || pollIntervalInput.value;
29
32
 
30
33
  function controlUrl() {
31
34
  return controlUrlInput.value.replace(/\/$/, "");
@@ -192,13 +195,28 @@ async function refreshPresets() {
192
195
  if (presets) renderPresets(presets);
193
196
  }
194
197
 
198
+ let pollTimer;
199
+
200
+ function restartPolling() {
201
+ clearInterval(pollTimer);
202
+ const ms = Number(pollIntervalInput.value) || 3000;
203
+ pollTimer = setInterval(refreshActivity, ms);
204
+ }
205
+
195
206
  connectButton.addEventListener("click", () => {
196
207
  localStorage.setItem(STORAGE_KEY, controlUrlInput.value);
208
+ localStorage.setItem(POLL_STORAGE_KEY, pollIntervalInput.value);
209
+ restartPolling();
197
210
  refresh();
198
211
  refreshActivity();
199
212
  refreshPresets();
200
213
  });
201
214
 
215
+ pollIntervalInput.addEventListener("change", () => {
216
+ localStorage.setItem(POLL_STORAGE_KEY, pollIntervalInput.value);
217
+ restartPolling();
218
+ });
219
+
202
220
  exportButton.addEventListener("click", async () => {
203
221
  const config = await withErrorHandling(() => api("/api/config"));
204
222
  if (!config) return;
@@ -299,7 +317,7 @@ function buildRunnerResult(ok, statusLine, headersText, bodyText) {
299
317
  return wrapper;
300
318
  }
301
319
 
302
- setInterval(refreshActivity, 3000);
320
+ restartPolling();
303
321
 
304
322
  addForm.addEventListener("submit", async (e) => {
305
323
  e.preventDefault();
@@ -157,6 +157,8 @@
157
157
  <div class="row">
158
158
  <span style="color: var(--text-muted)">control API:</span>
159
159
  <input id="control-url" type="text" value="http://localhost:51820" />
160
+ <span style="color: var(--text-muted)">polling (ms):</span>
161
+ <input id="poll-interval" type="number" min="500" step="500" value="3000" style="width: 80px" />
160
162
  <button id="connect">Conectar</button>
161
163
  </div>
162
164
  </header>
package/dist/index.d.ts CHANGED
@@ -10,6 +10,8 @@ export { StateStore, globToRegex } from "./core/state-store.js";
10
10
  export type { RegisterScenarioInput, UpdateScenarioInput } from "./core/state-store.js";
11
11
  export { ActivityLog } from "./core/activity-log.js";
12
12
  export type { ActivityEvent, RecordActivityInput } from "./core/activity-log.js";
13
+ export { isIgnoredPath } from "./core/ignore-paths.js";
14
+ export type { IgnorePathPattern } from "./core/ignore-paths.js";
13
15
  export { ScenarioEngine } from "./core/scenario-engine.js";
14
16
  export type { ChaosRequestInfo, ChaosResponseController, LegacyScenarioType, ScenarioConfig, ScenarioDirection, ScenarioHandler, ScenarioResult, ScenarioScope, ScenarioType, } from "./core/types.js";
15
17
  export * from "./scenarios/index.js";
@@ -18,5 +20,7 @@ export type { ApplyPresetOverrides, PresetCategory, PresetDefinition } from "./p
18
20
  export { createChaosFetch } from "./outbound/index.js";
19
21
  export type { ChaosFetchOptions } from "./outbound/index.js";
20
22
  export { createControlApi } from "./dashboard/server/control-api.js";
23
+ export type { ControlApiOptions } from "./dashboard/server/control-api.js";
21
24
  export { startDashboard } from "./dashboard/server/index.js";
25
+ export type { StartDashboardOptions } from "./dashboard/server/index.js";
22
26
  export { isBlockedByGuardrail, resetGuardrailWarning } from "./guardrail.js";
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ export { createChaosNestMiddleware } from "./adapters/nestjs.js";
4
4
  export { chaosKoaMiddleware } from "./adapters/koa.js";
5
5
  export { StateStore, globToRegex } from "./core/state-store.js";
6
6
  export { ActivityLog } from "./core/activity-log.js";
7
+ export { isIgnoredPath } from "./core/ignore-paths.js";
7
8
  export { ScenarioEngine } from "./core/scenario-engine.js";
8
9
  export * from "./scenarios/index.js";
9
10
  export { PRESET_CATALOG, applyPreset, findPreset, listPresets } from "./presets/index.js";
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@henriquecosta/chaos-api",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
+ "license": "MIT",
4
5
  "description": "Middleware pra simular falhas de producao (delay, erros, timeout, indisponibilidade, respostas malformadas/obsoletas) em APIs Express/Fastify/NestJS/Koa durante desenvolvimento.",
5
6
  "type": "module",
6
7
  "main": "./dist/index.js",
@@ -11,6 +12,9 @@
11
12
  "files": [
12
13
  "dist"
13
14
  ],
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
14
18
  "exports": {
15
19
  ".": {
16
20
  "types": "./dist/index.d.ts",