@checkstack/healthcheck-frontend 0.19.3 → 0.19.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,85 @@
1
1
  # @checkstack/healthcheck-frontend
2
2
 
3
+ ## 0.19.4
4
+
5
+ ### Patch Changes
6
+
7
+ - a06b899: Fix stale healthcheck editor on reopen after save.
8
+
9
+ Deleting a collector from a healthcheck, saving, then reopening the
10
+ editor used to show the deleted collector reappear — only a full page
11
+ refresh cleared it. The editor's `getConfiguration` query was being
12
+ served stale-while-revalidate on remount, and `useInitOnceForKey`
13
+ fired with that stale value before the background refetch landed.
14
+
15
+ Setting `gcTime: 0` on the loader query drops the cached entry on
16
+ unmount, so the next mount has nothing stale to serve and the form
17
+ seeds from fresh data.
18
+
19
+ The wider rule has been written up at
20
+ `docs/src/content/docs/frontend/query-invalidation.md` (Pillar 3) and
21
+ a pointer added to `.agent/rules/code-style-guide.md`. tl;dr:
22
+ within-plugin mutations are auto-invalidated by the oRPC client (no
23
+ manual `refetch()` needed); cross-plugin mutations must invalidate
24
+ explicitly; one-shot editor forms must use `gcTime: 0` on their loader.
25
+
26
+ - a06b899: Overhaul shell + inline-script health checks with real shell semantics, real ESM execution, and upstream Node/Bun IntelliSense.
27
+
28
+ **BREAKING CHANGES**
29
+
30
+ - **Shell collector** — the `Execute Script` collector now takes a single `script` string instead of `{ command, args }`. Existing configs are auto-migrated to v2: `command` + `args` are joined with POSIX single-quote escaping into the new `script` field, so behaviour is preserved. Custom UIs that hard-coded `command`/`args` field names need to switch to `script`.
31
+ - **Inline collector** — scripts are now executed as real ES modules in a Bun subprocess (was: `new Function()` inside a Web Worker). The legacy `return X;` style still works (it's auto-wrapped in an async IIFE), but mixed scripts that `import` _and_ `return` at the top level need to use `export default` for their result.
32
+
33
+ **FIXES**
34
+
35
+ - Shell scripts containing pipes, redirects, `awk`, command substitution, conditionals etc. no longer fail with `ENOENT`. The collector now runs through `sh -c <script>` instead of passing the full expression as `Bun.spawn`'s argv[0]. This was the original `awk … failed with ENOENT` regression.
36
+ - Inline scripts can now `import { loadavg } from "node:os"` (and any other `node:*` or `bun` import). They could not before, because the executor wrapped user code inside `new Function(...)` and ran it in a Web Worker that had no Node module access; the wrapper also made top-level `import` syntactically invalid (`Unexpected token '{'`).
37
+ - Healthcheck editor fields no longer reset while you're editing. The page was re-running its form-state init `useEffect` on every refetch of the configuration query — and that query is invalidated on every realtime `HEALTH_CHECK_RUN_COMPLETED` signal across the platform, so in-progress edits got wiped within seconds. Replaced the naive `useEffect([existingConfig])` with a new `useInitOnceForKey` hook from `@checkstack/ui` that initialises the form only on first load per healthcheck id and ignores background refetches. The hook's decision logic is a pure function (`shouldInitForKey`) and is unit-tested in `useInitOnceForKey.test.ts`.
38
+ - Switching between healthcheck collectors no longer mis-applies the previous collector's tokenizer / language service to the new editor. `MultiTypeEditorField` was reusing the same React instance across collector switches (same `key="script"` in both `DynamicForm` renders) and `selectedType` was initialised from `useState` only once on first mount. After a shell→typescript switch the new collector's TS content rendered through the shell branch (no TS highlighting, no IntelliSense); the reverse direction tokenised shell content through TS and surfaced nonsense errors like `2304 "Cannot find name 'and'"` on shell comments. Now a `useEffect` re-derives `selectedType` whenever `editorTypes` changes to a set that doesn't contain the current selection.
39
+ - Monaco workers are now bundled locally via Vite `?worker` imports and wired up through `MonacoEnvironment.getWorker` in a new `monacoWorkers.ts` module. The default `@monaco-editor/loader` CDN path silently failed CORS on worker scripts in some browsers, leaving Monaco's TS service with only the generic `editorWorkerService` — which is enough for tokenizer-only languages like shell but breaks TypeScript's semantic features entirely. Same module configures the TS service singleton (compiler options, eager-model-sync, diagnostics-options-ignore-1108) at module load instead of inside per-editor `onMount`, so the service starts pre-configured regardless of which language opens first. Migrated from the deprecated `monaco.languages.typescript.*` path to `monaco.typescript.*` (the old path is marked `{ deprecated: true }` in monaco-editor 0.55).
40
+ - `defineIntegration` / `defineHealthCheck` callback parameters are now typed against the schema. Previously the virtual module declared them as `(ctx: unknown) => …`, so writing `defineIntegration(async (context) => { console.log(context.event.eventId) })` produced `'context' is of type 'unknown'. (18046)`. The result type and the shared `IntegrationScriptContext` / `HealthCheckScriptContext` interfaces are now generated together in `scriptContext.ts`, so both the function-arg form and the ambient `declare const context` reference the same schema-typed shape.
41
+ - The shell starter template no longer uses Linux-only `/proc/loadavg` (which fails on macOS satellites with `awk: can't open file /proc/loadavg`). It now reads the 1-minute load average via `uptime` and parses both the Linux (`load average: 0.00, 0.01, 0.05`) and macOS (`load averages: 0.45 0.55 0.65`) output formats with a portable `sed`/`awk`/`tr` pipeline.
42
+ - Starter-template seeding is now self-healing. `DynamicForm`'s schema-defaults `useEffect` fires AFTER child seed effects in React's child-before-parent order, so the previous one-shot seed got clobbered back to `""` by the defaults call on first mount and never re-fired. Replaced the `[]`-deps effect with a two-effect pattern: an observer that latches `hasSeededRef = true` the first time `value` is observed non-empty, and a seed effect that keeps re-installing the starter while the latch is open. Once the seed sticks the latch closes; subsequent edits and realtime refetches don't re-trigger.
43
+
44
+ **NEW**
45
+
46
+ - The Monaco editor for inline scripts now mounts the real upstream `@types/node` + `bun-types` declarations as a virtual filesystem (lazy-loaded as its own JS chunk), so IntelliSense covers the full Node/Bun stdlib, the `Bun` global, `process.env`, `Buffer`, etc. DOM types are deliberately excluded so suggestions stay focused on the backend surface. `context.config` is typed from the collector's own JSON Schema.
47
+ - New `healthcheckScriptContext` / `integrationScriptContext` helpers (exported from `@checkstack/ui`) build a complete editor bundle in one call: TS declarations (`context.config` / `context.event.payload` + the virtual `@checkstack/healthcheck` / `@checkstack/integration` result-type modules), starter templates per language, and the shell env-var list (with platform-injected `EVENT_ID` / `DELIVERY_ID` / `PAYLOAD_*` for integrations). Both call sites — `CollectorSection.tsx` and `CreateSubscriptionDialog.tsx` — were rewired to use them, fixing a long-standing wiring gap where IntelliSense for injected values silently never reached the editor.
48
+ - Inline scripts can now `import { defineHealthCheck } from "@checkstack/healthcheck"` (or `defineIntegration` for integrations) for a typed return-shape assertion. The editor catches `{ success: "yes" }` as a type error against `HealthCheckScriptResult`. The runtime is just an identity function — the collector rewrites the import to a sibling helper file in the temp dir before executing.
49
+ - Shell editors now autocomplete env-vars after `$` and `${`. The completion list is supplied by `healthcheckScriptContext` (safe-vars whitelist) and `integrationScriptContext` (whitelist + `EVENT_ID` etc. + `PAYLOAD_*` flattened from the event's payload schema). The matcher is pure and unit-tested in `shellEnvVarMatcher.test.ts` so regex regressions are caught locally.
50
+ - Empty editor fields are now seeded with a working starter template per language (inline TS uses `defineHealthCheck`, inline shell does the `awk` load-average check, integration TS shows `defineIntegration` with `context.event`, integration shell lists the `$EVENT_ID` / `$PAYLOAD_*` env vars). Users see a runnable example instead of a blank canvas; once they edit, we leave their content alone.
51
+ - Hardened concurrency + cleanup model documented and tested: each invocation gets its own `mkdtemp` directory + UUID result marker; the `finally` block clears the timeout handle, kills any surviving subprocess (idempotent), and removes the temp directory on success, throw, _and_ timeout. New `concurrency.test.ts` proves 20 parallel inline scripts don't cross wires and that the temp-dir count returns to baseline after throws and timeouts.
52
+
53
+ **TESTING**
54
+
55
+ Tight unit tests added so changes to the editor surface don't need smoke testing:
56
+
57
+ - `scriptContext.test.ts` — 18 tests covering the generated type declarations (including explicit regression guards for `defineIntegration` / `defineHealthCheck` callback params being typed against the shared context interface rather than `unknown`), starter templates (including a guard that the shell starter doesn't depend on Linux-only `/proc/loadavg`), shell env-vars for both healthcheck + integration flavours, plus the schema-flattening utility.
58
+ - `shellEnvVarMatcher.test.ts` — 12 tests covering the bare `$` / braced `${` / partial-name / case-insensitive matching logic that powers Monaco's shell completion.
59
+ - `inline-script-normaliser.test.ts` — 13 tests covering the legacy `return X;` → IIFE wrap path, the ESM-passthrough path, and the `@checkstack/healthcheck` import rewriter.
60
+ - `inline-script-collector.test.ts` — 18 tests including ones that actually execute a script importing `defineHealthCheck` (named-import form) AND using the global `defineHealthCheck` (no import) to prove both code paths resolve at runtime.
61
+ - `concurrency.test.ts` — 4 tests proving 20 parallel runs don't collide and that the temp-dir count returns to baseline after success, throw, and timeout.
62
+ - `useInitOnceForKey.test.ts` — 10 tests proving the healthcheck-editor form state isn't reset when react-query refetches in the background (the original "fields reset while I'm typing" regression).
63
+ - `starterTemplateSelector.test.ts` — 7 tests for the pure decision function powering empty-field seeding.
64
+ - `security.test.ts` — added an integration test that actually executes the portable load-average pipeline through `Bun.spawn` on the current OS, catching `/proc/loadavg`-style regressions at CI time on macOS runners.
65
+
66
+ **SECURITY**
67
+
68
+ - Same env-var whitelist as before (`PATH`, `HOME`, `USER`, `LANG`, `LC_ALL`, `LC_CTYPE`, `TZ`, `TMPDIR`, `HOSTNAME`, `SHELL`). Backend secrets in the satellite process's environment remain invisible to user scripts.
69
+
70
+ See `docs/src/content/docs/backend/script-healthchecks.md` for the full user-facing guide.
71
+
72
+ - Updated dependencies [a06b899]
73
+ - @checkstack/ui@1.9.0
74
+ - @checkstack/anomaly-common@1.2.1
75
+ - @checkstack/catalog-common@2.2.1
76
+ - @checkstack/dashboard-frontend@0.7.4
77
+ - @checkstack/healthcheck-common@1.1.1
78
+ - @checkstack/auth-frontend@0.6.4
79
+ - @checkstack/gitops-frontend@0.4.4
80
+ - @checkstack/tips-frontend@0.2.4
81
+ - @checkstack/satellite-common@0.5.1
82
+
3
83
  ## 0.19.3
4
84
 
5
85
  ### Patch Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/healthcheck-frontend",
3
- "version": "0.19.3",
3
+ "version": "0.19.4",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "main": "src/index.tsx",
@@ -14,17 +14,17 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@checkstack/anomaly-common": "1.2.0",
17
- "@checkstack/auth-frontend": "0.6.2",
17
+ "@checkstack/auth-frontend": "0.6.3",
18
18
  "@checkstack/catalog-common": "2.2.0",
19
19
  "@checkstack/common": "0.10.0",
20
- "@checkstack/dashboard-frontend": "0.7.2",
20
+ "@checkstack/dashboard-frontend": "0.7.3",
21
21
  "@checkstack/frontend-api": "0.5.1",
22
- "@checkstack/gitops-frontend": "0.4.2",
22
+ "@checkstack/gitops-frontend": "0.4.3",
23
23
  "@checkstack/healthcheck-common": "1.1.0",
24
24
  "@checkstack/satellite-common": "0.5.0",
25
25
  "@checkstack/signal-frontend": "0.1.3",
26
- "@checkstack/tips-frontend": "0.2.2",
27
- "@checkstack/ui": "1.8.2",
26
+ "@checkstack/tips-frontend": "0.2.3",
27
+ "@checkstack/ui": "1.8.3",
28
28
  "ajv": "^8.18.0",
29
29
  "ajv-formats": "^3.0.1",
30
30
  "date-fns": "^4.1.0",
@@ -3,7 +3,12 @@ import type {
3
3
  CollectorConfigEntry,
4
4
  CollectorDto,
5
5
  } from "@checkstack/healthcheck-common";
6
- import { Button, DynamicForm, Label } from "@checkstack/ui";
6
+ import {
7
+ Button,
8
+ DynamicForm,
9
+ Label,
10
+ healthcheckScriptContext,
11
+ } from "@checkstack/ui";
7
12
  import { Trash2 } from "lucide-react";
8
13
  import { AssertionBuilder, type Assertion } from "../AssertionBuilder";
9
14
 
@@ -63,6 +68,9 @@ export const CollectorSection: React.FC<CollectorSectionProps> = ({
63
68
  value={entry.config}
64
69
  onChange={onConfigChange}
65
70
  onValidChange={onValidChange}
71
+ {...healthcheckScriptContext({
72
+ collectorConfigSchema: collectorDef.configSchema,
73
+ })}
66
74
  />
67
75
  </div>
68
76
  )}
@@ -13,7 +13,7 @@ import {
13
13
  DEFAULT_STATE_THRESHOLDS,
14
14
  } from "@checkstack/healthcheck-common";
15
15
  import { CatalogApi } from "@checkstack/catalog-common";
16
- import { PageLayout, Button, useToast, IDELayout, type ValidationIssue } from "@checkstack/ui";
16
+ import { PageLayout, Button, useToast, IDELayout, useInitOnceForKey, type ValidationIssue } from "@checkstack/ui";
17
17
  import { Save, Settings } from "lucide-react";
18
18
  import { resolveRoute, extractErrorMessage} from "@checkstack/common";
19
19
  import { useCollectors } from "../hooks/useCollectors";
@@ -62,11 +62,19 @@ const HealthCheckIDEPageContent = () => {
62
62
  {},
63
63
  );
64
64
 
65
- // Fetch single configuration for edit mode
65
+ // Fetch single configuration for edit mode.
66
+ //
67
+ // `gcTime: 0` is load-bearing: the form is seeded from this query
68
+ // exactly once via `useInitOnceForKey` below. Without it, reopening
69
+ // the editor after a save would synchronously serve the pre-save
70
+ // cached value (stale-while-revalidate) and the one-shot init would
71
+ // race the background refetch — deleted collectors would reappear
72
+ // until a hard refresh. See
73
+ // `docs/src/content/docs/frontend/query-invalidation.md` (Pillar 3).
66
74
  const { data: existingConfig, isLoading: configLoading } =
67
75
  healthCheckClient.getConfiguration.useQuery(
68
76
  { id: configId ?? "" },
69
- { enabled: isEditMode },
77
+ { enabled: isEditMode, gcTime: 0 },
70
78
  );
71
79
 
72
80
  // Determine the active strategy ID
@@ -115,17 +123,23 @@ const HealthCheckIDEPageContent = () => {
115
123
  systemIdFromUrl ? [systemIdFromUrl] : [],
116
124
  );
117
125
 
118
- // Initialize form from existing configuration (edit mode)
119
- useEffect(() => {
120
- if (existingConfig) {
121
- setFormState({
122
- name: existingConfig.name,
123
- intervalSeconds: existingConfig.intervalSeconds,
124
- strategyConfig: existingConfig.config,
125
- collectors: existingConfig.collectors ?? [],
126
- });
127
- }
128
- }, [existingConfig]);
126
+ // Initialize form from existing configuration (edit mode).
127
+ //
128
+ // CRITICAL: only ever runs once per healthcheck id. The configuration
129
+ // query is invalidated on every realtime `HEALTH_CHECK_RUN_COMPLETED`
130
+ // signal (see `SignalAutoInvalidator`), which would otherwise refetch
131
+ // and wipe the user's in-progress edits via a naive `[existingConfig]`
132
+ // dependency. Keying by `existingConfig.id` means the form only
133
+ // re-initialises when the user actually navigates to a different
134
+ // healthcheck — not on a background refetch of the same one.
135
+ useInitOnceForKey(existingConfig, existingConfig?.id, (config) => {
136
+ setFormState({
137
+ name: config.name,
138
+ intervalSeconds: config.intervalSeconds,
139
+ strategyConfig: config.config,
140
+ collectors: config.collectors ?? [],
141
+ });
142
+ });
129
143
 
130
144
  // Unsaved changes guard
131
145
  useEffect(() => {