@junoflow/eslint-plugin 0.10.0 → 0.12.0

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 CHANGED
@@ -17,21 +17,22 @@ These are about the replay contract: a Juno run re-executes your handler from
17
17
  the top after every suspension and every retry, replaying completed steps from a
18
18
  journal instead of re-running them. Everything below follows from that.
19
19
 
20
- | Rule | | Catches |
21
- | --------------------------------- | --- | ----------------------------------------------------------------------------------------------------------------------------------------- |
22
- | `juno/no-dynamic-step-id` | ⛔ | `step.run(id)` / `step.llm(id)` where `id` is not a static string literal, or contains the reserved `#` |
23
- | `juno/no-dynamic-scoped-name` | ⛔ | `state.scoped(name)` where `name` is not a static string literal |
24
- | `juno/no-journaled-in-step` | ⛔ | anything journaled inside a `step.run` callback — `sleep`, `waitForEvent`, `invoke`/`invokeAll`, `findings.*`, `state.scoped`, a step |
25
- | `juno/no-concurrent-capabilities` | ⛔ | `Promise.all([…])` over two suspending calls — `sleep`, `waitForEvent`, `invoke`/`invokeAll`. The first to fire exits; the rest never run |
26
- | `juno/no-nondeterminism` | ⛔ | `Date.now()`, `new Date()`, `Math.random()`, `crypto.randomUUID()` outside a step, and `process.env` anywhere |
27
- | `juno/no-floating-capability` | ⛔ | a capability call used as a statement without `await` |
28
- | `juno/no-credential-leak` | ⛔ | `ctx.credentials.*` passed to `log`/`console`, put in a finding, or returned directly from a step |
29
- | `juno/valid-duration` | ⛔ | a duration string that `time.ParseDuration` rejects — `'1d'`, `'10 minutes'`. Checks `sleep`, `timeout` and `ttl` arguments |
30
- | `juno/require-effects-in-step` | ⚠️ | a side effect outside a step, **in a handler that already takes a step or suspends**. Reads (`state.get`, `now`, `getState`) are exempt |
31
- | `juno/require-suspension-label` | ⚠️ | `sleep` / `waitForEvent` with no operator-facing label |
32
- | `juno/no-duplicate-step-id` | ⚠️ | the same literal step ID at two call sites in one handler |
33
- | `juno/prefer-step-for-clock` | ⚠️ | `now()` / `solar()` outside a step in a handler that suspends |
34
- | `juno/no-module-state` | ⚠️ | module-scope `let`/`var` written from a handler. It does not persist — the sandbox is a fresh process per dispatch |
20
+ | Rule | | Catches |
21
+ | --------------------------------- | --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | `juno/no-dynamic-step-id` | ⛔ | `step.run(id)` / `step.llm(id)` where `id` is not a static string literal, or contains the reserved `#` |
23
+ | `juno/no-dynamic-scoped-name` | ⛔ | `state.scoped(name)` where `name` is not a static string literal |
24
+ | `juno/no-journaled-in-step` | ⛔ | anything journaled inside a `step.run` callback — `wait`, a handle constructor (`ask` included) or `cancel()`, `sleep`, `invoke`/`invokeAll`, `findings.*`, `state.scoped`, `notify`, a step |
25
+ | `juno/no-concurrent-capabilities` | ⛔ | `Promise.all([…])` over two suspending calls — `wait`, `sleep`, `invoke`/`invokeAll`. The first to fire exits; the rest never run |
26
+ | `juno/no-nondeterminism` | ⛔ | `Date.now()`, `new Date()`, `Math.random()`, `crypto.randomUUID()` outside a step, and `process.env` anywhere |
27
+ | `juno/no-floating-capability` | ⛔ | a capability call used as a statement without `await` |
28
+ | `juno/no-credential-leak` | ⛔ | `ctx.credentials.*` passed to `log`/`console`, put in a finding, or returned directly from a step |
29
+ | `juno/valid-duration` | ⛔ | a duration string that `time.ParseDuration` rejects — `'1d'`, `'10 minutes'`. Checks `sleep`, `after`, `timeout` and `ttl` arguments |
30
+ | `juno/require-effects-in-step` | ⚠️ | a side effect outside a step, **in a handler that already takes a step or suspends**. Reads (`state.get`, `now`, `getState`) are exempt |
31
+ | `juno/require-suspension-label` | ⚠️ | `wait` / `sleep` with no operator-facing label |
32
+ | `juno/prefer-using-for-handles` | ⚠️ | a handle opened in a loop and bound with `const`/`let` but never `cancel()`ed there. It stays open; a run holds at most 100 — use `using` |
33
+ | `juno/no-duplicate-step-id` | ⚠️ | the same literal step ID at two call sites in one handler |
34
+ | `juno/prefer-step-for-clock` | ⚠️ | `now()` / `solar()` outside a step in a handler that suspends |
35
+ | `juno/no-module-state` | ⚠️ | module-scope `let`/`var` written from a handler. It does not persist — the sandbox is a fresh process per dispatch |
35
36
 
36
37
  ## Integration rules
37
38
 
@@ -53,11 +54,11 @@ re-run only if it throws, as a whole, so wrapping its one target call in a step
53
54
  buys nothing — and demanding it would make the simplest flows the most
54
55
  annotated.
55
56
 
56
- The moment a handler takes a step or calls `sleep`, `waitForEvent` or `invoke`,
57
- replay stops being a possibility and becomes a certainty: the handler **will**
58
- run again from the top. Anything effectful left outside a step happens again on
59
- that pass. That transition is the gate, and it is why the rule fires on a
60
- handler that suspends even when it takes no step at all.
57
+ The moment a handler takes a step or calls `sleep`, `wait` or `invoke`, replay
58
+ stops being a possibility and becomes a certainty: the handler **will** run
59
+ again from the top. Anything effectful left outside a step happens again on that
60
+ pass. That transition is the gate, and it is why the rule fires on a handler
61
+ that suspends even when it takes no step at all.
61
62
 
62
63
  A control's `press()` and `extend()` count as effects — each call is one more
63
64
  press, one more extension — while `activate()` and `release()` do not: they name
package/index.js CHANGED
@@ -232,7 +232,101 @@ function isFlowInvoke(p) {
232
232
  }
233
233
 
234
234
  const isSleep = (p) => tailIs(p, 'sleep');
235
- const isWaitForEvent = (p) => tailIs(p, 'waitForEvent');
235
+
236
+ // ─── Wait handles ────────────────────────────────────────────────────────────
237
+ // A handle is opened by a constructor, listed in a `wait`, and closed by its
238
+ // `cancel()` (or `using`). The vocabulary is every constructor name the handle
239
+ // API will ever have, including the ones later SDK releases add: the rules are
240
+ // name-based, and learning the names once keeps the plugin out of each later
241
+ // release.
242
+
243
+ /**
244
+ * `after` / `at` / `all` / `ask`, `wait` and `notify` are bare words, so they
245
+ * are matched only bare or directly on `ctx` — never as the tail of an
246
+ * arbitrary chain, where `items.at(-1)` and `Promise.all(…)` would read as
247
+ * handle calls.
248
+ */
249
+ function isCtxFunction(p, names) {
250
+ if (!p) return null;
251
+ if (p.length === 1 && names.includes(p[0])) return p[0];
252
+ if (p.length === 2 && p[0] === 'ctx' && names.includes(p[1])) return p[1];
253
+ return null;
254
+ }
255
+
256
+ const STATE_HANDLE_METHODS = ['when', 'becomes', 'changes'];
257
+ const TARGET_HANDLE_METHODS = ['untilEvent', 'start', 'startAll'];
258
+
259
+ /**
260
+ * The constructor's display name (`after()`, `state.x.when()`, …), or null.
261
+ * A constructor is synchronous: it returns its handle at once and queues the
262
+ * open on the socket.
263
+ */
264
+ function handleConstructor(p) {
265
+ const bare = isCtxFunction(p, ['after', 'at', 'all', 'ask']);
266
+ if (bare) return `${bare}()`;
267
+ if (!p || p.length < 3) return null;
268
+ const [obj, binding, method] = p.slice(-3);
269
+ if (obj === 'state' && STATE_HANDLE_METHODS.includes(method)) {
270
+ return `state.${binding}.${method}()`;
271
+ }
272
+ if (obj === 'targets' && TARGET_HANDLE_METHODS.includes(method)) {
273
+ return `targets.${binding}.${method}()`;
274
+ }
275
+ if (obj === 'controls' && method === 'untilPressed') {
276
+ return `controls.${binding}.untilPressed()`;
277
+ }
278
+ return null;
279
+ }
280
+
281
+ const isWait = (p) => !!isCtxFunction(p, ['wait']);
282
+
283
+ /** True for a CallExpression node that constructs a handle. */
284
+ function isConstructorCall(node) {
285
+ const inner = unwrapTS(node);
286
+ return (
287
+ !!inner &&
288
+ inner.type === 'CallExpression' &&
289
+ !!handleConstructor(calleePath(inner))
290
+ );
291
+ }
292
+
293
+ /** The variable `name` resolves to from `scope`, or null. */
294
+ function resolveVariable(scope, name) {
295
+ for (let s = scope; s; s = s.upper) {
296
+ const v = s.set.get(name);
297
+ if (v) return v;
298
+ }
299
+ return null;
300
+ }
301
+
302
+ /**
303
+ * True when `node` is `<handle>.cancel()`: the object is a constructor call
304
+ * itself, or an identifier whose declaration initialised it from one. Any
305
+ * other `.cancel()` — a subscription's, an AbortController's — is not ours.
306
+ */
307
+ function isHandleCancel(sourceCode, node) {
308
+ if (node.type !== 'CallExpression') return false;
309
+ const callee = node.callee;
310
+ if (
311
+ callee.type !== 'MemberExpression' ||
312
+ callee.computed ||
313
+ callee.property.type !== 'Identifier' ||
314
+ callee.property.name !== 'cancel'
315
+ ) {
316
+ return false;
317
+ }
318
+ const obj = unwrapTS(callee.object);
319
+ if (isConstructorCall(obj)) return true;
320
+ if (!obj || obj.type !== 'Identifier') return false;
321
+ const v = resolveVariable(sourceCode.getScope(node), obj.name);
322
+ const def = v && v.defs[0];
323
+ return (
324
+ !!def &&
325
+ def.type === 'Variable' &&
326
+ !!def.node.init &&
327
+ isConstructorCall(def.node.init)
328
+ );
329
+ }
236
330
  const isSolar = (p) => tailIs(p, 'solar');
237
331
  const isNow = (p) => tailIs(p, 'now') && !tailIs(p, 'Date', 'now');
238
332
  const isFetch = (p) => tailIs(p, 'fetch');
@@ -241,20 +335,21 @@ const isLog = (p) =>
241
335
 
242
336
  /** Suspends the run: the sandbox exits and the handler re-enters on wake. */
243
337
  function isSuspending(p) {
244
- return isSleep(p) || isWaitForEvent(p) || !!isFlowInvoke(p);
338
+ return isWait(p) || isSleep(p) || !!isFlowInvoke(p);
245
339
  }
246
340
 
247
341
  /** Recorded in the journal, so it must not be replayed from inside a step. */
248
342
  function journaledKind(p) {
249
343
  const step = isStepCall(p);
250
344
  if (step) return `step.${step}()`;
345
+ if (isWait(p)) return 'wait()';
251
346
  if (isSleep(p)) return 'sleep()';
252
- if (isWaitForEvent(p)) return 'waitForEvent()';
253
347
  const invoke = isFlowInvoke(p);
254
348
  if (invoke) return `${invoke}()`;
255
349
  const finding = isFindingsCall(p);
256
350
  if (finding) return `findings.${finding}()`;
257
351
  if (isStateCall(p) === 'scoped') return 'state.scoped()';
352
+ if (isCtxFunction(p, ['notify'])) return 'notify()';
258
353
  return null;
259
354
  }
260
355
 
@@ -265,8 +360,8 @@ function isCapabilityCall(p) {
265
360
  !!isStateCall(p) ||
266
361
  !!isFindingsCall(p) ||
267
362
  isTargetCall(p) ||
363
+ isWait(p) ||
268
364
  isSleep(p) ||
269
- isWaitForEvent(p) ||
270
365
  isSolar(p)
271
366
  );
272
367
  }
@@ -288,7 +383,14 @@ function isCapabilityCall(p) {
288
383
  function isRepeatedEffect(p) {
289
384
  if (isTargetCall(p)) {
290
385
  const last = p[p.length - 1];
291
- return last !== 'getState' && !isFlowInvoke(p);
386
+ // A handle constructor (untilEvent, start, startAll) is replay-safe: the
387
+ // host keeps the handle, and a replayed open sends nothing. Wrapped in a
388
+ // step it would replay as the step's output, not as a handle.
389
+ return (
390
+ last !== 'getState' &&
391
+ !isFlowInvoke(p) &&
392
+ !TARGET_HANDLE_METHODS.includes(last)
393
+ );
292
394
  }
293
395
  const state = isStateCall(p);
294
396
  if (state) return state !== 'get' && state !== 'scoped';
@@ -369,7 +471,7 @@ const noDynamicScopedName = {
369
471
  context.report({
370
472
  node: name || node,
371
473
  message:
372
- 'state.scoped() name must be a static string literal — the setter is journaled under it, and a computed name cannot be matched on replay',
474
+ 'state.scoped() name must be a static string literal — the read and the setter are journaled under it, and a computed name cannot be matched on replay',
373
475
  });
374
476
  }
375
477
  },
@@ -392,15 +494,21 @@ const noJournaledInStep = {
392
494
  const sourceCode = context.sourceCode;
393
495
  return {
394
496
  CallExpression(node) {
395
- const kind = journaledKind(calleePath(node));
497
+ const p = calleePath(node);
498
+ const handle =
499
+ handleConstructor(p) ||
500
+ (isHandleCancel(sourceCode, node) ? 'cancel()' : null);
501
+ const kind = journaledKind(p) || handle;
396
502
  if (!kind) return;
397
503
  if (!enclosingStepCallback(sourceCode, node)) return;
398
504
 
399
- // Two distinct failures, and the author needs to be told which.
400
- const suspends = isSuspending(calleePath(node));
505
+ // Three distinct failures, and the author needs to be told which.
506
+ const suspends = isSuspending(p);
401
507
  const why = suspends
402
508
  ? 'it suspends the run, so the step never completes and its callback re-runs in full on wake — every side effect before this line fires twice'
403
- : 'its journal ID comes from a counter that only advances when the call executes, so a replay that skips this step misaligns every later call on the same key';
509
+ : handle
510
+ ? 'the callback of a completed step is skipped on replay, so a handle opened or cancelled inside one happens on the first execution only and shifts every later handle ID'
511
+ : 'its journal ID comes from a counter that only advances when the call executes, so a replay that skips this step misaligns every later call on the same key';
404
512
  context.report({
405
513
  node,
406
514
  message: `${kind} must not be called inside step.run() — ${why}`,
@@ -497,14 +605,10 @@ const validDuration = {
497
605
  return {
498
606
  CallExpression(node) {
499
607
  const p = calleePath(node);
500
- if (isSleep(p)) {
608
+ if (isSleep(p) || isCtxFunction(p, ['after'])) {
501
609
  check(node.arguments[0]);
502
610
  return;
503
611
  }
504
- if (isWaitForEvent(p)) {
505
- check(objectProp(node.arguments[1], 'timeout'));
506
- return;
507
- }
508
612
  // The binding names the state, the slot and the signal, so a claim's
509
613
  // options are its second argument and a signal's its first.
510
614
  const state = isStateCall(p);
@@ -532,7 +636,7 @@ const PROMISE_COMBINATORS = new Set(['all', 'allSettled', 'race', 'any']);
532
636
  * not a failed deploy.
533
637
  */
534
638
  function isSuspendingCall(p) {
535
- return !!isFlowInvoke(p) || isSleep(p) || isWaitForEvent(p);
639
+ return !!isFlowInvoke(p) || isWait(p) || isSleep(p);
536
640
  }
537
641
 
538
642
  const noConcurrentCapabilities = {
@@ -586,7 +690,7 @@ const noConcurrentCapabilities = {
586
690
  context.report({
587
691
  node,
588
692
  message:
589
- "sleep(), waitForEvent() and a flow target's invoke() end the sandbox process — the first one to fire wins and the rest never run. Await them one at a time, or use invokeAll() to fan out",
693
+ "wait(), sleep() and a flow target's invoke() end the sandbox process — the first one to fire wins and the rest never run. Await them one at a time, list every handle in one wait(), or use invokeAll() to fan out",
590
694
  });
591
695
  },
592
696
  };
@@ -776,24 +880,26 @@ const noCredentialLeak = {
776
880
  const requireSuspensionLabel = {
777
881
  meta: {
778
882
  type: 'suggestion',
779
- docs: { description: 'sleep() and waitForEvent() should carry a label' },
883
+ docs: {
884
+ description: 'wait() and sleep() should carry a label',
885
+ },
780
886
  schema: [],
781
887
  },
782
888
  create(context) {
783
889
  return {
784
890
  CallExpression(node) {
785
891
  const p = calleePath(node);
786
- if (isSleep(p) && node.arguments.length < 2) {
892
+ if (isWait(p) && node.arguments.length < 2) {
787
893
  context.report({
788
894
  node,
789
895
  message:
790
- 'sleep() without a label shows the operator a generic "Sleeping" — a flow that sleeps in three places is indistinguishable from itself in the run view',
896
+ 'wait() without a label shows the operator a generic "Waiting" — pass a second argument saying what the run is waiting for',
791
897
  });
792
- } else if (isWaitForEvent(p) && node.arguments.length < 3) {
898
+ } else if (isSleep(p) && node.arguments.length < 2) {
793
899
  context.report({
794
900
  node,
795
901
  message:
796
- 'waitForEvent() without a label shows the operator a description derived from the pattern — pass a third argument saying what the run is waiting for',
902
+ 'sleep() without a label shows the operator a generic "Sleeping" — a flow that sleeps in three places is indistinguishable from itself in the run view',
797
903
  });
798
904
  }
799
905
  },
@@ -801,6 +907,93 @@ const requireSuspensionLabel = {
801
907
  },
802
908
  };
803
909
 
910
+ // ─── prefer-using-for-handles ────────────────────────────────────────────────
911
+ //
912
+ // A handle stays open until it fires, is cancelled, or its run ends, and a run
913
+ // holds at most 100 open ones. A handle opened on every iteration of a loop
914
+ // and bound with const/let outlives the iteration, so a long loop runs into
915
+ // the cap. `using` cancels it at the end of the block; an explicit `.cancel()`
916
+ // in the body does the same and is accepted.
917
+ //
918
+ // A warning: a loop that runs a handful of times is correct either way, and
919
+ // the rule cannot count iterations.
920
+
921
+ const LOOP_TYPES = new Set([
922
+ 'ForStatement',
923
+ 'ForInStatement',
924
+ 'ForOfStatement',
925
+ 'WhileStatement',
926
+ 'DoWhileStatement',
927
+ ]);
928
+
929
+ /**
930
+ * The body of the innermost loop enclosing `node` within its own function, or
931
+ * null. A function boundary stops the search: a callback declared in a loop
932
+ * runs whenever it is called, not once per iteration.
933
+ */
934
+ function enclosingLoopBody(sourceCode, node) {
935
+ const ancestors = sourceCode.getAncestors(node);
936
+ let child = node;
937
+ for (let i = ancestors.length - 1; i >= 0; i--) {
938
+ const a = ancestors[i];
939
+ if (isFunction(a)) return null;
940
+ if (LOOP_TYPES.has(a.type) && a.body === child) return a.body;
941
+ child = a;
942
+ }
943
+ return null;
944
+ }
945
+
946
+ function contains(outer, inner) {
947
+ return outer.range[0] <= inner.range[0] && inner.range[1] <= outer.range[1];
948
+ }
949
+
950
+ const preferUsingForHandles = {
951
+ meta: {
952
+ type: 'suggestion',
953
+ docs: {
954
+ description: 'a handle opened in a loop should be declared with using',
955
+ },
956
+ schema: [],
957
+ },
958
+ create(context) {
959
+ const sourceCode = context.sourceCode;
960
+ return {
961
+ VariableDeclarator(node) {
962
+ if (!node.init || !isConstructorCall(node.init)) return;
963
+ const decl = node.parent;
964
+ if (decl.kind !== 'const' && decl.kind !== 'let') return;
965
+ if (node.id.type !== 'Identifier') return;
966
+ const body = enclosingLoopBody(sourceCode, decl);
967
+ if (!body) return;
968
+
969
+ const [variable] = sourceCode.getDeclaredVariables(node);
970
+ const cancelled =
971
+ variable &&
972
+ variable.references.some((ref) => {
973
+ const id = ref.identifier;
974
+ const member = id.parent;
975
+ return (
976
+ contains(body, id) &&
977
+ member.type === 'MemberExpression' &&
978
+ member.object === id &&
979
+ !member.computed &&
980
+ member.property.name === 'cancel' &&
981
+ member.parent.type === 'CallExpression' &&
982
+ member.parent.callee === member
983
+ );
984
+ });
985
+ if (cancelled) return;
986
+
987
+ context.report({
988
+ node,
989
+ message:
990
+ 'a handle opened in a loop stays open after the iteration — declare it with "using" (a run holds at most 100 open handles)',
991
+ });
992
+ },
993
+ };
994
+ },
995
+ };
996
+
804
997
  // ─── no-duplicate-step-id ────────────────────────────────────────────────────
805
998
 
806
999
  const noDuplicateStepId = {
@@ -1167,6 +1360,7 @@ module.exports = {
1167
1360
  'no-floating-capability': noFloatingCapability,
1168
1361
  'no-credential-leak': noCredentialLeak,
1169
1362
  'require-suspension-label': requireSuspensionLabel,
1363
+ 'prefer-using-for-handles': preferUsingForHandles,
1170
1364
  'no-duplicate-step-id': noDuplicateStepId,
1171
1365
  'prefer-step-for-clock': preferStepForClock,
1172
1366
  'no-module-state': noModuleState,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@junoflow/eslint-plugin",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "ESLint rules for Juno flows and integrations",
5
5
  "license": "MIT",
6
6
  "repository": {
package/rulesets.json CHANGED
@@ -16,7 +16,8 @@
16
16
  "juno/no-duplicate-step-id": "warn",
17
17
  "juno/prefer-step-for-clock": "warn",
18
18
  "juno/no-module-state": "warn",
19
- "juno/prefer-claim-over-set": "warn"
19
+ "juno/prefer-claim-over-set": "warn",
20
+ "juno/prefer-using-for-handles": "warn"
20
21
  },
21
22
  "integration": {
22
23
  "juno/no-juno-sdk-import": "error",