@r_masseater/oxlint-plugin-decision 0.9.4 → 0.10.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.
- package/dist/{app-BO1xNTFk.mjs → app-1jZ4qJYY.mjs} +169 -6
- package/dist/app-1jZ4qJYY.mjs.map +1 -0
- package/dist/{claim-rule-BtckE1OP.mjs → claim-rule-Dzu69Utl.mjs} +2 -2
- package/dist/{claim-rule-BtckE1OP.mjs.map → claim-rule-Dzu69Utl.mjs.map} +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{preset-plugin-DlO5OR3z.mjs → preset-plugin-miAjemLS.mjs} +3 -3
- package/dist/{preset-plugin-DlO5OR3z.mjs.map → preset-plugin-miAjemLS.mjs.map} +1 -1
- package/dist/presets/ai-slop.mjs +2 -2
- package/dist/presets/recommended.mjs +1 -1
- package/dist/presets/review-only.mjs +1 -1
- package/dist/presets/strict.mjs +1 -1
- package/dist/{presets/index.d.mts → presets.d.mts} +2 -2
- package/dist/{presets/index.mjs → presets.mjs} +2 -2
- package/package.json +18 -30
- package/dist/app-BO1xNTFk.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { A as JEV_MODEL, B as isReported, C as checkRules, D as resolveModel, E as optionsError, F as locationQuestion, I as selectedLocation, L as sourceLines, M as locates, N as locationCandidates, O as resolveOptions, P as locationOfLine, S as STRICT, T as modelIdsOf, _ as refAt, b as ModelSpecSchema, c as messageOf, d as runOrElse, f as toJson, g as parseVerdicts, h as locationRefOf, j as EVERY_LINE, k as CLEF_MODEL, l as missingEnvOf, m as buildRequest, o as envOf, p as warnOnce, r as snippetRequestsFor, s as failsInCi, u as nowMs, w as checked, x as PREFIX, y as truncateSnippet, z as BOOLEAN_ANSWER } from "./wire-D0YSbfBG.mjs";
|
|
2
|
-
import { Array, Boolean, Console, Effect, Function, Match, Option, Order, Predicate, Record, Schema, String as String$1, Struct, pipe } from "effect";
|
|
2
|
+
import { Array, Boolean, Config, Console, Effect, Exit, FileSystem, Function, Layer, Match, Option, Order, Path, Predicate, Random, Record, Schema, String as String$1, Struct, pipe } from "effect";
|
|
3
3
|
import { createSyncFn } from "synckit";
|
|
4
4
|
// src/entities/decision/model/budget.ts
|
|
5
5
|
const OUT_OF_BUDGET = /^http (?:402|403): .*(?:credit|budget)/iu;
|
|
@@ -776,6 +776,168 @@ const typesafe = syncProvider({
|
|
|
776
776
|
const decisionProviders = Record.fromEntries(pipe([cloudflare, typesafe], Array.map((provider) => [provider.name, provider])));
|
|
777
777
|
// src/app/judge-text.ts
|
|
778
778
|
const judgeText = judgeTextWith(decisionProviders);
|
|
779
|
+
// ../masseater-utils/src/shared/lib/usage-tally.ts
|
|
780
|
+
const TallyFields = Schema.Struct({
|
|
781
|
+
library: Schema.String,
|
|
782
|
+
version: Schema.String,
|
|
783
|
+
kind: Schema.String,
|
|
784
|
+
name: Schema.String,
|
|
785
|
+
calls: Schema.Finite
|
|
786
|
+
});
|
|
787
|
+
const TallyList = Schema.Array(TallyFields);
|
|
788
|
+
const SPOOL_ENV = "USAGE_METER_SPOOL";
|
|
789
|
+
// ../masseater-utils/src/shared/lib/usage-spool.ts
|
|
790
|
+
const ManifestFields = Schema.Struct({
|
|
791
|
+
name: Schema.String,
|
|
792
|
+
version: Schema.String
|
|
793
|
+
});
|
|
794
|
+
const MANIFEST = "package.json";
|
|
795
|
+
const decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(ManifestFields));
|
|
796
|
+
const encodeTallies = Schema.encodeEffect(Schema.fromJsonString(TallyList));
|
|
797
|
+
const manifestAbove = (directory) => Effect.gen(function* manifestAboveDirectory() {
|
|
798
|
+
const fs = yield* FileSystem.FileSystem;
|
|
799
|
+
const path = yield* Path.Path;
|
|
800
|
+
const text = yield* fs.readFileString(path.join(directory, MANIFEST)).pipe(Effect.option);
|
|
801
|
+
const found = pipe(text, Option.flatMap(decodeManifest));
|
|
802
|
+
const parent = path.dirname(directory);
|
|
803
|
+
if (Option.isSome(found) || parent === directory) return found;
|
|
804
|
+
return yield* manifestAbove(parent);
|
|
805
|
+
});
|
|
806
|
+
const tallyOf = ({ moduleUrl, kind, name, calls }) => Effect.gen(function* tallyOfSeen() {
|
|
807
|
+
const path = yield* Path.Path;
|
|
808
|
+
const file = yield* path.fromFileUrl(new URL(moduleUrl)).pipe(Effect.option);
|
|
809
|
+
if (Option.isNone(file)) return Option.none();
|
|
810
|
+
const manifest = yield* manifestAbove(path.dirname(file.value));
|
|
811
|
+
return pipe(manifest, Option.map(({ name: library, version }) => ({
|
|
812
|
+
library,
|
|
813
|
+
version,
|
|
814
|
+
kind,
|
|
815
|
+
name,
|
|
816
|
+
calls
|
|
817
|
+
})));
|
|
818
|
+
});
|
|
819
|
+
const written = (spool, seen) => Effect.gen(function* writeSpool() {
|
|
820
|
+
const fs = yield* FileSystem.FileSystem;
|
|
821
|
+
const path = yield* Path.Path;
|
|
822
|
+
const tallies = yield* Effect.forEach(seen, tallyOf, { concurrency: "unbounded" }).pipe(Effect.map(Array.getSomes));
|
|
823
|
+
const text = yield* encodeTallies(tallies);
|
|
824
|
+
const suffix = yield* Random.nextInt;
|
|
825
|
+
yield* fs.makeDirectory(spool, { recursive: true });
|
|
826
|
+
yield* fs.writeFileString(path.join(spool, `${String(process.pid)}-${String(suffix)}.json`), text);
|
|
827
|
+
}).pipe(Effect.ignore);
|
|
828
|
+
const taggedError = Schema.TaggedError;
|
|
829
|
+
var NodeServicesMissing = class extends taggedError()("NodeServicesMissing", { message: Schema.String }) {};
|
|
830
|
+
const nodeServices = Effect.tryPromise({
|
|
831
|
+
try: () => import("@effect/platform-node/NodeServices"),
|
|
832
|
+
catch: () => NodeServicesMissing.make({ message: "@effect/platform-node could not be loaded" })
|
|
833
|
+
}).pipe(Effect.flatMap(({ layer }) => Layer.build(layer)));
|
|
834
|
+
const spoolWritten = (spool) => (seen) => nodeServices.pipe(Effect.flatMap((services) => Effect.provideContext(written(spool, seen), services)), Effect.scoped, Effect.ignore);
|
|
835
|
+
// ../masseater-utils/src/shared/lib/usage-meter.ts
|
|
836
|
+
const RULE_ENTRIES = [
|
|
837
|
+
"create",
|
|
838
|
+
"createOnce",
|
|
839
|
+
"check",
|
|
840
|
+
"linter",
|
|
841
|
+
"fixer"
|
|
842
|
+
];
|
|
843
|
+
const RULE = "rule";
|
|
844
|
+
const FUNCTION = "function";
|
|
845
|
+
const ONE_CALL = 1;
|
|
846
|
+
const PREFIX_SEPARATOR = "/";
|
|
847
|
+
const KEY_SEPARATOR = "\0";
|
|
848
|
+
const idle = {
|
|
849
|
+
rules: (rules) => rules,
|
|
850
|
+
functions: (functions) => functions,
|
|
851
|
+
plugins: (plugins) => plugins,
|
|
852
|
+
within: () => idle
|
|
853
|
+
};
|
|
854
|
+
const declared = /* @__PURE__ */ new Map();
|
|
855
|
+
const calls = /* @__PURE__ */ new Map();
|
|
856
|
+
const state = {
|
|
857
|
+
flushed: false,
|
|
858
|
+
scheduled: false
|
|
859
|
+
};
|
|
860
|
+
const spoolSetting = Exit.match(Effect.runSyncExit(Config.NonEmptyString(SPOOL_ENV).pipe(Config.option)), {
|
|
861
|
+
onSuccess: (value) => value,
|
|
862
|
+
onFailure: () => Option.none()
|
|
863
|
+
});
|
|
864
|
+
const isCallable = (value) => Predicate.isFunction(value);
|
|
865
|
+
const keyOf = ({ moduleUrl, kind, name }) => Array.join([
|
|
866
|
+
moduleUrl,
|
|
867
|
+
kind,
|
|
868
|
+
name
|
|
869
|
+
], KEY_SEPARATOR);
|
|
870
|
+
const countCall = (key) => {
|
|
871
|
+
const next = (calls.get(key) ?? 0) + ONE_CALL;
|
|
872
|
+
calls.set(key, next);
|
|
873
|
+
};
|
|
874
|
+
const counted = (key, callable) => Object.assign(function countedCall(...args) {
|
|
875
|
+
countCall(key);
|
|
876
|
+
return callable.call(this, ...args);
|
|
877
|
+
}, callable);
|
|
878
|
+
const ruleCounted = (key, rule) => {
|
|
879
|
+
if (isCallable(rule)) return counted(key, rule);
|
|
880
|
+
if (!Predicate.isObject(rule)) return rule;
|
|
881
|
+
const entries = pipe(RULE_ENTRIES, Array.flatMap((entry) => pipe(Option.liftPredicate(Record.get({ ...rule }, entry), Option.isSome), Option.flatMap((found) => Option.liftPredicate(found.value, isCallable)), Option.map((callable) => [entry, counted(key, callable)]), Option.toArray)));
|
|
882
|
+
if (Array.isReadonlyArrayEmpty(entries)) return rule;
|
|
883
|
+
return {
|
|
884
|
+
...rule,
|
|
885
|
+
...Record.fromEntries(entries)
|
|
886
|
+
};
|
|
887
|
+
};
|
|
888
|
+
const functionCounted = (key, value) => {
|
|
889
|
+
if (isCallable(value)) return counted(key, value);
|
|
890
|
+
return value;
|
|
891
|
+
};
|
|
892
|
+
const flushUsage = Effect.suspend(() => {
|
|
893
|
+
if (state.flushed || Option.isNone(spoolSetting)) return Effect.void;
|
|
894
|
+
state.flushed = true;
|
|
895
|
+
const seen = pipe([...declared], Array.map(([key, exported]) => ({
|
|
896
|
+
...exported,
|
|
897
|
+
calls: calls.get(key) ?? 0
|
|
898
|
+
})));
|
|
899
|
+
return spoolWritten(spoolSetting.value)(seen);
|
|
900
|
+
});
|
|
901
|
+
const flushOnExit = () => {
|
|
902
|
+
if (state.scheduled) return;
|
|
903
|
+
state.scheduled = true;
|
|
904
|
+
process.once("beforeExit", () => {
|
|
905
|
+
Effect.runFork(flushUsage);
|
|
906
|
+
});
|
|
907
|
+
};
|
|
908
|
+
const qualified = (prefix, name) => pipe([prefix, name], Array.filter(String$1.isNonEmpty), Array.join(PREFIX_SEPARATOR));
|
|
909
|
+
const wrapped = (moduleUrl, prefix, kind) => (wrap) => (names) => {
|
|
910
|
+
flushOnExit();
|
|
911
|
+
return pipe(names, Record.map((value, name) => {
|
|
912
|
+
const exported = {
|
|
913
|
+
moduleUrl,
|
|
914
|
+
kind,
|
|
915
|
+
name: qualified(prefix, name)
|
|
916
|
+
};
|
|
917
|
+
declared.set(keyOf(exported), exported);
|
|
918
|
+
return wrap(keyOf(exported), value);
|
|
919
|
+
}));
|
|
920
|
+
};
|
|
921
|
+
const meterOf = (moduleUrl, prefix) => {
|
|
922
|
+
const rules = (named) => wrapped(moduleUrl, prefix, RULE)(ruleCounted)(named);
|
|
923
|
+
const plugins = (named) => pipe(named, Record.map((plugin, name) => pipe(Option.fromUndefinedOr(plugin.rules), Option.match({
|
|
924
|
+
onNone: () => plugin,
|
|
925
|
+
onSome: (pluginRules) => ({
|
|
926
|
+
...plugin,
|
|
927
|
+
rules: meterOf(moduleUrl, qualified(prefix, name)).rules(pluginRules)
|
|
928
|
+
})
|
|
929
|
+
}))));
|
|
930
|
+
return {
|
|
931
|
+
rules,
|
|
932
|
+
functions: (named) => wrapped(moduleUrl, prefix, FUNCTION)(functionCounted)(named),
|
|
933
|
+
plugins,
|
|
934
|
+
within: (inner) => meterOf(moduleUrl, qualified(prefix, inner))
|
|
935
|
+
};
|
|
936
|
+
};
|
|
937
|
+
const usageMeter = (moduleUrl) => pipe(spoolSetting, Option.match({
|
|
938
|
+
onNone: () => idle,
|
|
939
|
+
onSome: () => meterOf(moduleUrl, "")
|
|
940
|
+
}));
|
|
779
941
|
// src/app/plugin.ts
|
|
780
942
|
const DEFAULT_NAME = "decision";
|
|
781
943
|
const metaOf = (rule) => ({
|
|
@@ -813,14 +975,15 @@ const createDecisionPlugin = (setup) => {
|
|
|
813
975
|
}, rules, decisionProviders));
|
|
814
976
|
resolve({});
|
|
815
977
|
const shared = sharedFile((settings) => resolve(settings[name]), memoizedRules(decisionProviders));
|
|
978
|
+
const created = Record.fromEntries(pipe(rules, Array.map((rule) => [rule.id, {
|
|
979
|
+
meta: metaOf(rule),
|
|
980
|
+
createOnce: visitorFor(shared, rule)
|
|
981
|
+
}])));
|
|
816
982
|
return {
|
|
817
983
|
meta: { name },
|
|
818
|
-
rules:
|
|
819
|
-
meta: metaOf(rule),
|
|
820
|
-
createOnce: visitorFor(shared, rule)
|
|
821
|
-
}])))
|
|
984
|
+
rules: usageMeter(import.meta.url).within(name).rules(created)
|
|
822
985
|
};
|
|
823
986
|
};
|
|
824
987
|
export { judgeText as n, defineDecisionRule as r, createDecisionPlugin as t };
|
|
825
988
|
|
|
826
|
-
//# sourceMappingURL=app-
|
|
989
|
+
//# sourceMappingURL=app-1jZ4qJYY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-1jZ4qJYY.mjs","names":["Str","Arr","FIRST_LINE","Rec","Str","DATA_FIRST_ARITY_3","Arr","Str","Fn","DATA_FIRST_ARITY_3","Str","Fn","DATA_FIRST_ARITY_3","Fn","Arr","DECIMALS","Bool","Arr","Rec","Bool","Str","Arr","Rec","Fn","DATA_FIRST_ARITY","Fn","Arr","Bool","Rec","Arr","Rec","matchOf","Fn","Arr","Str","Arr","Rec","Arr","Arr","Arr","Rec","Str","Rec","Arr"],"sources":["../src/entities/decision/model/budget.ts","../../lint-host/src/shared/lib/collections.ts","../src/entities/decision/model/nodes.ts","../src/entities/decision/model/context.ts","../src/entities/decision/model/define.ts","../src/entities/decision/model/name.ts","../src/features/judge-code/model/override.ts","../src/features/judge-code/model/explain-text.ts","../src/features/judge-code/model/explain.ts","../src/features/judge-code/model/locate.ts","../src/features/judge-code/model/report.ts","../src/features/judge-code/model/visitor.ts","../src/features/judge-code/model/judge-text.ts","../src/app/sync-provider.ts","../src/app/cloudflare.ts","../src/app/typesafe.ts","../src/app/providers.ts","../src/app/judge-text.ts","../../masseater-utils/src/shared/lib/usage-tally.ts","../../masseater-utils/src/shared/lib/usage-spool.ts","../../masseater-utils/src/shared/lib/usage-meter.ts","../src/app/plugin.ts"],"sourcesContent":["export const OUT_OF_BUDGET = /^http (?:402|403): .*(?:credit|budget)/iu;\n","import { Array as Arr, Option, Order, Record as Rec, String as Str, pipe } from \"effect\";\n\nconst byKey = Order.mapInput(Str.Order, ([key]: readonly [string, unknown]) => key);\n\nexport const sortedRecord = <Value>(\n entries: readonly (readonly [string, Value])[],\n): Readonly<Record<string, Value>> => Rec.fromEntries(Arr.sort(entries, byKey));\n\nconst NEXT = 1;\n\nexport interface Grouped<Head, Item> {\n readonly head: Head;\n readonly items: readonly Item[];\n}\n\nexport const groupedUnder =\n <Item, Head>(asHead: (item: Item) => Option.Option<Head>) =>\n (closes: (head: Head, item: Item) => boolean) =>\n (items: readonly Item[]): readonly Grouped<Head, Item>[] =>\n pipe(\n items,\n Arr.flatMap((item, index) =>\n pipe(\n asHead(item),\n Option.map((head): Grouped<Head, Item> => ({\n head,\n items: pipe(\n items,\n Arr.drop(index + NEXT),\n Arr.takeWhile((next) => !closes(head, next)),\n ),\n })),\n Option.toArray,\n ),\n ),\n );\n\nexport const ancestorsBy =\n <Node>(parentOf: (node: Node) => Option.Option<Node>) =>\n (node: Node): readonly Node[] =>\n Arr.unfold(parentOf(node), (current) =>\n pipe(\n current,\n Option.map((found) => [found, parentOf(found)] as const),\n ),\n );\n\nexport const groupOf =\n (name: string) =>\n (found: RegExpMatchArray | null): Option.Option<string> =>\n pipe(\n Option.fromNullishOr(found),\n Option.flatMap((match) => Option.fromNullishOr(match.groups)),\n Option.flatMap((groups) => Option.fromNullishOr(groups[name])),\n );\n","import type { Location } from \"@oxlint/plugins\";\nimport { Option, String as Str, Record as Rec } from \"effect\";\n\nimport type { AstNode, Target } from \"./types.ts\";\n\nconst FIRST_LINE = 1;\nconst FIRST_COLUMN = 0;\nexport const TARGET_NODE_TYPES = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n call: [\"CallExpression\"],\n jsx: [\"JSXElement\"],\n file: [\"Program\"],\n} as const satisfies Readonly<Record<Target, readonly string[]>>;\n\nconst NAMED_PARENTS = {\n VariableDeclarator: \"init\",\n Property: \"value\",\n MethodDefinition: \"value\",\n PropertyDefinition: \"value\",\n} as const;\n\ntype NamedField = (typeof NAMED_PARENTS)[keyof typeof NAMED_PARENTS];\n\nconst NAMED_PARENT_TYPES: ReadonlySet<string> = new Set(Rec.keys(NAMED_PARENTS));\n\nconst isNamedParentType = (type: string): type is keyof typeof NAMED_PARENTS =>\n NAMED_PARENT_TYPES.has(type);\n\nconst ANONYMOUS_FUNCTIONS: ReadonlySet<string> = new Set([\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n]);\n\nconst holdsAsName = (parent: AstNode, node: AstNode): boolean => {\n if (!isNamedParentType(parent.type)) {\n return false;\n }\n const field: NamedField = NAMED_PARENTS[parent.type];\n return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;\n};\n\nexport const snippetNodeFor = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => holdsAsName(parent, node)),\n Option.getOrElse((): AstNode => node),\n );\nconst headOf = (text: string, line: number, column: number): Location => {\n const [first] = Str.split(text, \"\\n\");\n return { start: { line, column }, end: { line, column: column + first.length } };\n};\n\nexport const REPORT_LOC = {\n function: (node: AstNode, text: string): Location =>\n headOf(text, node.loc.start.line, node.loc.start.column),\n call: (node: AstNode): Location => node.loc,\n jsx: (node: AstNode): Location =>\n Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,\n file: (_node: AstNode, text: string): Location => headOf(text, FIRST_LINE, FIRST_COLUMN),\n} as const satisfies Readonly<Record<Target, (node: AstNode, text: string) => Location>>;\n","import { ancestorsBy } from \"@masseater.dev/lint-host/collections\";\nimport type { Context } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, String as Str, pipe, Function as Fn } from \"effect\";\n\nimport { sourceLines } from \"./location.ts\";\nimport { snippetNodeFor } from \"./nodes.ts\";\nimport type { AstNode, EnclosingKind, ResolvedRule, RuleContext } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DEFAULT_LINES = 5;\nconst FIRST_LINE = 1;\nconst LAST = 1;\nconst END = 1;\n\nconst ENCLOSING_TYPES: Readonly<Record<EnclosingKind, readonly string[]>> = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n class: [\"ClassDeclaration\", \"ClassExpression\"],\n block: [\"BlockStatement\", \"StaticBlock\", \"Program\"],\n};\n\nconst ancestorsOf = ancestorsBy((node: AstNode) => Option.fromNullishOr(node.parent));\n\nconst enclosingText = (context: Context, node: AstNode, kind: EnclosingKind): string =>\n Arr.findFirst(ancestorsOf(node), (ancestor) =>\n ENCLOSING_TYPES[kind].includes(ancestor.type),\n ).pipe(\n Option.match({\n onNone: () => context.sourceCode.text,\n onSome: (ancestor) => context.sourceCode.getText(ancestor),\n }),\n );\n\nconst linesAround = (\n context: Context,\n node: AstNode,\n {\n before = DEFAULT_LINES,\n after = DEFAULT_LINES,\n }: { readonly before?: number; readonly after?: number },\n): string => {\n const lines = sourceLines(context.sourceCode.text);\n const first = Math.max(FIRST_LINE, node.loc.start.line - before);\n const last = Math.min(lines.length, node.loc.end.line + after);\n return pipe(\n lines,\n Arr.drop(first - FIRST_LINE),\n Arr.take(last - first + FIRST_LINE),\n Arr.map((text, index) => `L${String(first + index)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n};\n\nconst DECLARING_PARENTS: ReadonlySet<string> = new Set([\n \"VariableDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportDefaultDeclaration\",\n]);\n\nconst declarationOf = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => DECLARING_PARENTS.has(parent.type)),\n Option.match({ onNone: () => node, onSome: declarationOf }),\n );\n\ninterface Span {\n readonly start: number;\n readonly end: number;\n}\n\nconst leadingOf = (text: string, comments: readonly Span[], until: number): readonly Span[] =>\n Option.match(Arr.last(comments), {\n onNone: () => [],\n onSome: (last) => {\n if (Str.isNonEmpty(Str.trim(Str.slice(last.end, until)(text)))) {\n return [];\n }\n return [...leadingOf(text, Arr.dropRight(comments, LAST), last.start), last];\n },\n });\n\nconst commentedTextOf = (context: Context, node: AstNode): Option.Option<string> => {\n const { text } = context.sourceCode;\n const named = snippetNodeFor(node);\n const [start] = declarationOf(named).range;\n const before = pipe(\n context.sourceCode.getAllComments(),\n Arr.filter((comment) => comment.type !== \"Shebang\" && comment.end <= start),\n );\n return Arr.match(leadingOf(text, before, start), {\n onEmpty: () => Option.none(),\n onNonEmpty: ([first]) => Option.some(Str.slice(first.start, named.range[END])(text)),\n });\n};\n\nconst isCommented = ({ context: wanted }: ResolvedRule): boolean =>\n Predicate.isNotUndefined(wanted) && wanted.scope === \"comment\";\n\nexport const commentedSnippetOf: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string> =>\n Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)),\n);\n\nexport const lacksComment: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => boolean;\n (context: Context, node: AstNode, rule: ResolvedRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): boolean =>\n isCommented(rule) && Option.isNone(commentedTextOf(context, node)),\n);\n\nexport const contextOf: {\n (node: AstNode, rule: RuleContext): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string> => {\n if (rule.scope === \"lines\") {\n return Option.some(linesAround(context, node, rule));\n }\n if (rule.scope === \"enclosing\") {\n return Option.some(enclosingText(context, node, rule.kind));\n }\n return Option.liftPredicate(context.sourceCode.text, () => rule.scope === \"file\");\n },\n);\n","import type { DecisionRule } from \"./types.ts\";\n\nexport const defineDecisionRule = <const Rule extends DecisionRule>(rule: Rule): Rule => rule;\n","import type { Context } from \"@oxlint/plugins\";\nimport { Match, Option, String as Str, Function as Fn } from \"effect\";\n\nimport type { DecisionRule, SelectedNode } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst heldName = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.flatMap(Option.fromNullishOr(node.parent), (parent) =>\n Match.value(parent).pipe(\n Match.when({ type: \"VariableDeclarator\" }, (holder) =>\n Option.liftPredicate(holder.id, () => holder.init === node),\n ),\n Match.when(\n { type: Match.is(\"Property\", \"MethodDefinition\", \"PropertyDefinition\") },\n (holder) => Option.liftPredicate(holder.key, () => holder.value === node),\n ),\n Match.orElse(() => Option.none<SelectedNode>()),\n ),\n );\n\nconst nameNodeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: Match.is(\"FunctionDeclaration\", \"FunctionExpression\") }, (fn) =>\n Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn)),\n ),\n Match.when({ type: \"ArrowFunctionExpression\" }, heldName),\n Match.when({ type: Match.is(\"CallExpression\", \"NewExpression\") }, (call) =>\n Option.some(call.callee),\n ),\n Match.when({ type: \"JSXElement\" }, (element) => Option.some(element.openingElement.name)),\n Match.orElse(() => Option.none<SelectedNode>()),\n );\n\nconst nameOf = (node: SelectedNode, context: Context): string | undefined =>\n Option.getOrUndefined(\n Option.map(nameNodeOf(node), (name) =>\n Str.slice(name.start, name.end)(context.sourceCode.text),\n ),\n );\n\nexport const isSelected: {\n (node: SelectedNode, rule: DecisionRule): (context: Context) => boolean;\n (context: Context, node: SelectedNode, rule: DecisionRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: SelectedNode, { select }: DecisionRule): boolean =>\n Option.match(Option.fromUndefinedOr(select), {\n onNone: () => true,\n onSome: (selects) => selects(node, { name: nameOf(node, context), context }),\n }),\n);\n","import type { RuleOptionsSchema } from \"@oxlint/plugins\";\nimport { Option, Predicate, Schema, Array as Arr, pipe, Function as Fn } from \"effect\";\n\nimport {\n ModelSpecSchema,\n STRICT,\n checked,\n modelIdsOf,\n resolveModel,\n} from \"#/entities/decision/index.ts\";\nimport type { DecisionProvider, ResolvedRule } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst RuleOverrideSchema = Schema.Struct({\n model: Schema.optionalKey(ModelSpecSchema),\n});\n\nexport const RULE_OPTIONS_SCHEMA = [\n {\n type: \"object\",\n additionalProperties: false,\n properties: {\n model: {\n oneOf: [\n { type: \"string\", minLength: 1 },\n { type: \"array\", minItems: 1, items: { type: \"string\", minLength: 1 } },\n ],\n },\n },\n },\n] satisfies RuleOptionsSchema;\n\nconst decodeOverride = Schema.decodeUnknownResult(RuleOverrideSchema, STRICT);\n\nexport const overrideRule: {\n (\n raw: unknown,\n providers: Readonly<Record<string, DecisionProvider>>,\n ): (rule: ResolvedRule) => ResolvedRule;\n (\n rule: ResolvedRule,\n raw: unknown,\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedRule;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n rule: ResolvedRule,\n raw: unknown,\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedRule => {\n if (Predicate.isUndefined(raw)) {\n return rule;\n }\n const { model } = checked(decodeOverride, raw, `options for rule \"${rule.id}\"`);\n return {\n ...rule,\n models: Option.match(Option.fromUndefinedOr(model), {\n onNone: () => rule.models,\n onSome: (spec) =>\n pipe(\n modelIdsOf(spec),\n Arr.map((id) => resolveModel(id, providers)),\n ),\n }),\n };\n },\n);\n","import { Array as Arr, Boolean as Bool, Option, Predicate, Record as Rec, pipe } from \"effect\";\n\nimport { PREFIX, toJson } from \"#/entities/decision/index.ts\";\nimport type { Verdict } from \"#/entities/decision/index.ts\";\n\nconst DECIMALS = 2;\nexport interface ExplainQuestion {\n readonly id: string;\n readonly question: string;\n readonly probabilities: Readonly<Record<string, number>>;\n}\n\nexport interface Explanation {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n readonly rule: string;\n readonly model: string;\n readonly served?: string;\n readonly cutoff: number;\n readonly cached?: boolean;\n readonly durationMs: number;\n readonly state: { readonly chars: number; readonly head: string };\n readonly questions: readonly ExplainQuestion[];\n readonly verdict?: Verdict;\n readonly reported: boolean;\n readonly error?: string;\n}\nconst fixed = (value: number): string => value.toFixed(DECIMALS);\n\nconst cachedText = (cached: boolean | undefined): string =>\n Option.match(Option.fromUndefinedOr(cached), {\n onNone: () => \"unknown\",\n onSome: (hit) => Bool.match(hit, { onTrue: () => \"yes\", onFalse: () => \"no\" }),\n });\n\nconst probabilitiesText = (probabilities: Readonly<Record<string, number>>): string =>\n Option.match(\n Arr.match(Rec.toEntries(probabilities), {\n onEmpty: () => Option.none<string>(),\n onNonEmpty: (entries) =>\n Option.some(\n pipe(\n entries,\n Arr.map(([label, value]) => `${label}=${fixed(value)}`),\n Arr.join(\" \"),\n ),\n ),\n }),\n { onNone: () => \"(no answer)\", onSome: (text) => text },\n );\n\nconst verdictText = (explanation: Explanation): string => {\n if (Predicate.isNotUndefined(explanation.error)) {\n return `error: ${explanation.error}`;\n }\n const outcome = Bool.match(explanation.reported, {\n onTrue: () => \"reported\",\n onFalse: () => \"not reported\",\n });\n const cutoff = `cutoff ${fixed(explanation.cutoff)}`;\n return Option.match(Option.fromUndefinedOr(explanation.verdict), {\n onNone: () => `no verdict, ${cutoff}, ${outcome}`,\n onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`,\n });\n};\n\nconst servedText = (served: string | undefined): string =>\n Option.match(Option.fromUndefinedOr(served), {\n onNone: () => \"\",\n onSome: (id) => ` (served ${id})`,\n });\n\nexport const asText = (explanation: Explanation): string =>\n pipe(\n [\n `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,\n ` state: ${String(explanation.state.chars)} chars ${toJson(explanation.state.head)}`,\n ...pipe(\n explanation.questions,\n Arr.map(\n ({ id, question, probabilities }) =>\n ` ${id}: ${probabilitiesText(probabilities)}\\n ${question}`,\n ),\n ),\n ` verdict: ${verdictText(explanation)}`,\n ],\n Arr.join(\"\\n\"),\n );\n","import type { Location } from \"@oxlint/plugins\";\nimport {\n Array as Arr,\n Boolean as Bool,\n Console,\n Effect,\n Function as Fn,\n Match,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n} from \"effect\";\n\nimport { refAt, envOf, toJson, snippetRequestsFor } from \"#/entities/decision/index.ts\";\nimport type {\n Answer,\n Answers,\n DecisionRequest,\n ExplainSetting,\n Match as RuleMatch,\n Question,\n Verdict,\n WireRequest,\n} from \"#/entities/decision/index.ts\";\n\nimport { asText } from \"./explain-text.ts\";\nimport type { Explanation } from \"./explain-text.ts\";\n\ntype ExplainFormat = Extract<ExplainSetting, string>;\n\ntype ExplainMode = \"off\" | ExplainFormat;\n\nconst EXPLAIN_ENV = \"OXLINT_DECISION_EXPLAIN\";\nconst OFF_VALUES: ReadonlySet<string> = new Set([\"0\", \"false\", \"off\", \"no\"]);\nconst STATE_HEAD_CHARS = 60;\nconst OPTION_SEPARATOR = \"__\";\nconst FIRST = 1;\nconst START = 0;\nconst COLUMN_BASE = 1;\n\nexport interface Outcome {\n readonly served: string;\n readonly answers: Answers;\n readonly cached: boolean | undefined;\n readonly verdict: Option.Option<Verdict>;\n readonly reported: boolean;\n}\n\nexport interface Explainer {\n readonly outcome: (match: RuleMatch, at: Placed, outcome: Outcome) => void;\n readonly failure: (matches: readonly RuleMatch[], reason: string) => void;\n}\n\nexport interface Placed {\n readonly ref: string;\n readonly loc: Location;\n}\n\nexport interface ExplainPass {\n readonly setting: ExplainSetting;\n readonly cwd: string;\n readonly filename: string;\n readonly model: string;\n readonly request: DecisionRequest;\n readonly durationMs: number;\n}\n\nconst SEPARATOR = /^[/\\\\]/u;\n\nconst relativeTo = (root: string, filename: string): string =>\n Bool.match(\n Str.isNonEmpty(root) &&\n Str.startsWith(root)(filename) &&\n SEPARATOR.test(Str.slice(root.length)(filename)),\n {\n onTrue: () => Str.slice(root.length + FIRST)(filename),\n onFalse: () => filename,\n },\n );\n\nconst fromSetting = (setting: ExplainSetting): ExplainMode =>\n Match.value(setting).pipe(\n Match.when(\"json\", (): ExplainMode => \"json\"),\n Match.when(true, (): ExplainMode => \"text\"),\n Match.when(\"text\", (): ExplainMode => \"text\"),\n Match.orElse((): ExplainMode => \"off\"),\n );\n\nconst fromEnv = (value: string): ExplainMode =>\n Match.value(Str.toLowerCase(value)).pipe(\n Match.when(\"json\", (): ExplainMode => \"json\"),\n Match.when(\n (lower) => OFF_VALUES.has(lower),\n (): ExplainMode => \"off\",\n ),\n Match.orElse((): ExplainMode => \"text\"),\n );\n\nconst explainModeOf = (setting: ExplainSetting): ExplainMode =>\n Option.match(envOf(EXPLAIN_ENV), { onNone: () => fromSetting(setting), onSome: fromEnv });\n\nconst probabilitiesIn = (answer: Answer): Option.Option<Readonly<Record<string, number>>> => {\n if (answer.type === \"noul\") {\n return Option.some({ yes: answer.noul });\n }\n return Option.fromUndefinedOr(answer.probabilities);\n};\n\nconst probabilitiesOf = (answer: Answer | undefined): Readonly<Record<string, number>> =>\n Option.fromUndefinedOr(answer).pipe(\n Option.flatMap(probabilitiesIn),\n Option.getOrElse(() => ({})),\n );\n\nconst asksAbout = (ref: string, id: string): boolean =>\n pipe(Str.split(id, OPTION_SEPARATOR), Arr.take(FIRST), Arr.contains(ref));\n\nconst askedAbout =\n (ref: string) =>\n (wire: WireRequest): readonly (readonly [string, Question])[] =>\n pipe(\n Rec.toEntries(wire.questions),\n Arr.filter(([id]) => asksAbout(ref, id)),\n );\n\nconst sentFor = (\n sent: readonly WireRequest[],\n ref: string,\n): readonly (readonly [string, Question])[] => pipe(sent, Arr.flatMap(askedAbout(ref)));\n\nconst stateTextOf = (sent: readonly WireRequest[], ref: string, snippet: string): string =>\n Arr.findFirst(sent, (wire) => Arr.isReadonlyArrayNonEmpty(askedAbout(ref)(wire))).pipe(\n Option.map(({ state }) => state),\n Option.filter(Predicate.isString),\n Option.getOrElse(() => snippet),\n );\n\nconst summaryOf = (text: string): Explanation[\"state\"] => ({\n chars: text.length,\n head: Str.slice(START, STATE_HEAD_CHARS)(Str.trim(Str.replaceAll(/\\s+/gu, \" \")(text))),\n});\n\ntype Base = Pick<\n Explanation,\n \"file\" | \"line\" | \"column\" | \"rule\" | \"model\" | \"cutoff\" | \"durationMs\" | \"state\" | \"questions\"\n>;\n\ninterface Sent {\n readonly pass: ExplainPass;\n readonly sent: readonly WireRequest[];\n}\n\nconst baseOf = (\n { pass, sent }: Sent,\n match: RuleMatch,\n { ref, loc }: Placed,\n): ((answers: Answers) => Base) => {\n const questions = sentFor(sent, ref);\n return (answers) => ({\n file: relativeTo(pass.cwd, pass.filename),\n line: loc.start.line,\n column: loc.start.column + COLUMN_BASE,\n rule: match.rule.id,\n model: pass.model,\n cutoff: match.rule.cutoff,\n durationMs: pass.durationMs,\n state: summaryOf(stateTextOf(sent, ref, match.snippet)),\n questions: pipe(\n questions,\n Arr.map(([id, question]) => ({\n id,\n question: question.instructions,\n probabilities: probabilitiesOf(answers[id]),\n })),\n ),\n });\n};\n\nconst printerFor =\n (mode: ExplainFormat) =>\n (explanation: Explanation): void => {\n const line = Bool.match(mode === \"json\", {\n onTrue: () => toJson(explanation),\n onFalse: () => asText(explanation),\n });\n Effect.runFork(Console.error(line));\n };\n\nconst explaining = (pass: ExplainPass, mode: ExplainFormat): Explainer => {\n const sent = snippetRequestsFor(pass.request);\n const print = printerFor(mode);\n return {\n outcome: (match, at, { served, answers, cached, verdict, reported }): void => {\n print({\n ...baseOf({ pass, sent }, match, at)(answers),\n served,\n ...Option.match(Option.fromUndefinedOr(cached), {\n onNone: () => ({}),\n onSome: (hit) => ({ cached: hit }),\n }),\n ...Option.match(verdict, { onNone: () => ({}), onSome: (found) => ({ verdict: found }) }),\n reported,\n });\n },\n failure: (matches, reason): void => {\n for (const [index, match] of matches.entries()) {\n const at = { ref: refAt(index), loc: match.loc };\n print({ ...baseOf({ pass, sent }, match, at)({}), reported: false, error: reason });\n }\n },\n };\n};\n\nconst SILENT: Explainer = { outcome: Fn.constVoid, failure: Fn.constVoid };\n\nexport const explainerFor = (pass: ExplainPass): Explainer =>\n Match.value(explainModeOf(pass.setting)).pipe(\n Match.when(\"off\", () => SILENT),\n Match.orElse((mode) => explaining(pass, mode)),\n );\n","import type { Location } from \"@oxlint/plugins\";\nimport { Effect, Option, Function as Fn } from \"effect\";\n\nimport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n selectedLocation,\n locationRefOf,\n parseVerdicts,\n messageOf,\n nowMs,\n runOrElse,\n} from \"#/entities/decision/index.ts\";\nimport type {\n LocatedMatch,\n DecideInput,\n DecideResult,\n DecisionRequest,\n LineRange,\n Match,\n ModelRef,\n Verdicts,\n} from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DATA_FIRST_ARITY = 2;\n\nexport type VerdictResult =\n | { readonly ok: true; readonly verdicts: Verdicts; readonly cached: boolean | undefined }\n | { readonly ok: false; readonly reason: string };\n\nexport interface Located {\n readonly loc: Location;\n readonly failure: Option.Option<string>;\n}\n\nexport interface Asking {\n readonly model: ModelRef;\n readonly deadline: number;\n readonly env: Readonly<Record<string, string>>;\n}\n\ninterface Refinement {\n readonly asking: Asking;\n readonly match: Match & LocatedMatch;\n readonly ref: string;\n readonly state: DecisionRequest[\"state\"];\n}\n\nconst MINIMUM_TIMEOUT_MS = 1;\n\nconst remainingMs = (deadline: number): number => Math.max(MINIMUM_TIMEOUT_MS, deadline - nowMs());\n\nexport const verdictsOf: {\n (request: DecisionRequest): (result: DecideResult) => VerdictResult;\n (result: DecideResult, request: DecisionRequest): VerdictResult;\n} = Fn.dual(DATA_FIRST_ARITY, (result: DecideResult, request: DecisionRequest): VerdictResult => {\n if (!result.ok) {\n return result;\n }\n return runOrElse(\n Effect.sync((): VerdictResult => ({\n ok: true,\n verdicts: parseVerdicts(result.response, request),\n cached: result.cached,\n })),\n (cause) => ({ ok: false, reason: messageOf(cause) }),\n );\n});\n\nexport const inputOf: {\n (request: DecisionRequest): (asking: Asking) => DecideInput;\n (asking: Asking, request: DecisionRequest): DecideInput;\n} = Fn.dual(DATA_FIRST_ARITY, (asking: Asking, request: DecisionRequest): DecideInput => ({\n request,\n timeoutMs: remainingMs(asking.deadline),\n env: asking.env,\n}));\n\nconst fetchVerdicts = (asking: Asking, request: DecisionRequest): VerdictResult =>\n verdictsOf(asking.model.provider.decide(inputOf(asking, request)), request);\n\nconst isRange = (location: Option.Option<LineRange>): location is Option.Some<LineRange> =>\n Option.exists(location, ({ start, end }) => start !== end);\n\nconst refineOnce = (\n { asking, match, ref, state }: Refinement,\n within: LineRange,\n): VerdictResult & { readonly next?: Option.Option<LineRange> } => {\n const questionId = locationRefOf(ref);\n const candidates = locationCandidates(match.snippet, within);\n const refined = fetchVerdicts(asking, {\n model: asking.model.model,\n state,\n questions: { [questionId]: locationQuestion(match, ref, candidates) },\n });\n if (!refined.ok) {\n return refined;\n }\n return {\n ...refined,\n next: selectedLocation(\n refined.verdicts.answers[questionId],\n candidates,\n match.rule.location.cutoff,\n ),\n };\n};\n\nconst refine = (refinement: Refinement, first: Option.Option<LineRange>): Located => {\n let location = first;\n while (isRange(location)) {\n const step = refineOnce(refinement, location.value);\n if (!step.ok) {\n return { loc: refinement.match.loc, failure: Option.some(step.reason) };\n }\n location = step.next ?? Option.none();\n }\n return {\n loc: Option.match(location, {\n onNone: () => refinement.match.loc,\n onSome: ({ start }) => locationOfLine(refinement.match.snippet, start),\n }),\n failure: Option.none(),\n };\n};\n\nexport interface LocateInput {\n readonly ref: string;\n readonly verdicts: Verdicts;\n readonly request: DecisionRequest;\n}\n\nexport const locateMatch: {\n (match: Match, input: LocateInput): (asking: Asking) => Located;\n (asking: Asking, match: Match, input: LocateInput): Located;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (asking: Asking, match: Match, { ref, verdicts, request }: LocateInput): Located => {\n if (!locates(match)) {\n return { loc: match.loc, failure: Option.none() };\n }\n const first = selectedLocation(\n verdicts.answers[locationRefOf(ref)],\n locationCandidates(match.snippet, EVERY_LINE),\n match.rule.location.cutoff,\n );\n return refine({ asking, match, ref, state: request.state }, first);\n },\n);\n","import type { Context, Location } from \"@oxlint/plugins\";\nimport { Array as Arr, Boolean as Bool, Option, Record as Rec, pipe } from \"effect\";\n\nimport {\n isReported,\n OUT_OF_BUDGET,\n optionsError,\n buildRequest,\n refAt,\n failsInCi,\n warnOnce,\n} from \"#/entities/decision/index.ts\";\nimport type {\n DecideResult,\n DecisionProvider,\n DecisionRequest,\n Match,\n ModelRef,\n ResolvedOptions,\n Verdicts,\n} from \"#/entities/decision/index.ts\";\n\nimport { explainerFor } from \"./explain.ts\";\nimport type { ExplainPass, Explainer, Outcome, Placed } from \"./explain.ts\";\nimport { inputOf, locateMatch, verdictsOf } from \"./locate.ts\";\nimport type { Asking, Located } from \"./locate.ts\";\n\nexport interface ModelPass {\n readonly contextOf: (match: Match) => Context;\n readonly filename: string;\n readonly options: ResolvedOptions;\n readonly model: ModelRef;\n readonly matches: readonly Match[];\n readonly deadline: number;\n}\n\ninterface Failure {\n readonly match: Match;\n readonly loc: Location;\n readonly reason: string;\n}\n\ninterface Answered {\n readonly asking: Asking;\n readonly verdicts: Verdicts;\n readonly request: DecisionRequest;\n readonly cached: boolean | undefined;\n readonly explainer: Explainer;\n}\n\nconst DECIMALS = 2;\n\nconst failsHere = (pass: ModelPass, reason: string): boolean =>\n failsInCi(pass.options) && !OUT_OF_BUDGET.test(reason);\n\nconst degrade = (pass: ModelPass, reason: string): void => {\n if (failsHere(pass, reason)) {\n throw optionsError(`${reason} (${pass.filename})`);\n }\n warnOnce(reason, `${reason} (${pass.filename})`);\n};\n\nconst reportFailure = (pass: ModelPass, failure: Failure): void => {\n if (failsHere(pass, failure.reason)) {\n pass.contextOf(failure.match).report({\n loc: failure.loc,\n messageId: \"unlocated\",\n data: { id: failure.match.rule.id, reason: failure.reason },\n });\n return;\n }\n warnOnce(failure.reason, `${failure.reason} (${pass.filename})`);\n};\n\nconst locate = (\n answered: Answered,\n match: Match,\n { ref, failed }: { readonly ref: string; readonly failed: boolean },\n): Located => {\n if (failed) {\n return { loc: match.loc, failure: Option.none() };\n }\n return locateMatch(answered.asking, match, { ...answered, ref });\n};\n\nconst outcomeOf = (answered: Answered, match: Match, ref: string): Outcome => {\n const verdict = Option.fromUndefinedOr(answered.verdicts.results[ref]);\n return {\n served: `${answered.asking.model.provider.name}/${answered.verdicts.model}`,\n cached: answered.cached,\n answers: answered.verdicts.answers,\n verdict,\n reported: Option.exists(verdict, (found) => isReported(match.rule, found)),\n };\n};\n\nconst reportMatch = (\n pass: ModelPass,\n answered: Answered,\n { match, ref, failed }: { readonly match: Match; readonly ref: string; readonly failed: boolean },\n): Option.Option<string> => {\n const outcome = outcomeOf(answered, match, ref);\n const { verdict } = outcome;\n if (!outcome.reported || Option.isNone(verdict)) {\n answered.explainer.outcome(match, { ref, loc: match.loc }, outcome);\n return Option.none();\n }\n const located = locate(answered, match, { ref, failed });\n const at: Placed = { ref, loc: located.loc };\n answered.explainer.outcome(match, at, outcome);\n pass.contextOf(match).report({\n loc: located.loc,\n messageId: \"yes\",\n data: {\n id: match.rule.id,\n model: `${pass.model.provider.name}/${answered.verdicts.model}`,\n answer: verdict.value.answer,\n score: verdict.value.probability.toFixed(DECIMALS),\n cutoff: match.rule.cutoff.toFixed(DECIMALS),\n question: match.rule.message ?? match.rule.question,\n },\n });\n return located.failure;\n};\n\nconst reportMatches = (pass: ModelPass, answered: Answered): Option.Option<Failure> => {\n let failure: Option.Option<Failure> = Option.none();\n for (const [index, match] of pass.matches.entries()) {\n const located = reportMatch(pass, answered, {\n match,\n ref: refAt(index),\n failed: Option.isSome(failure),\n });\n failure = Option.orElse(failure, () =>\n located.pipe(Option.map((reason) => ({ match, loc: match.loc, reason }))),\n );\n }\n return failure;\n};\n\nconst explainPassOf = (\n pass: ModelPass,\n { request, durationMs }: Pick<ExplainPass, \"request\" | \"durationMs\">,\n): ExplainPass => ({\n setting: pass.options.explain,\n cwd: Option.match(Arr.head(pass.matches), {\n onNone: () => \"\",\n onSome: (match) => pass.contextOf(match).cwd,\n }),\n filename: pass.filename,\n model: pass.model.id,\n request,\n durationMs,\n});\n\ninterface Prepared {\n readonly pass: ModelPass;\n readonly asking: Asking;\n readonly request: DecisionRequest;\n}\n\nconst prepare = (pass: ModelPass): Prepared => ({\n pass,\n asking: { model: pass.model, deadline: pass.deadline, env: pass.options.env },\n request: buildRequest(pass.model.model, pass.matches),\n});\n\nconst reportAnswer = (\n { pass, asking, request }: Prepared,\n { decided, durationMs }: { readonly decided: DecideResult; readonly durationMs: number },\n): void => {\n const explainer = explainerFor(explainPassOf(pass, { request, durationMs }));\n const result = verdictsOf(decided, request);\n if (!result.ok) {\n explainer.failure(pass.matches, result.reason);\n degrade(pass, result.reason);\n return;\n }\n Option.map(reportMatches(pass, { ...result, asking, request, explainer }), (failure) => {\n reportFailure(pass, failure);\n });\n};\n\nconst decideWith = (\n provider: DecisionProvider,\n prepared: readonly Prepared[],\n): readonly DecideResult[] => {\n const inputs = pipe(\n prepared,\n Arr.map(({ asking, request }) => inputOf(asking, request)),\n );\n return provider.decideAll(inputs);\n};\n\nconst reportProvider = (prepared: Arr.NonEmptyReadonlyArray<Prepared>): void => {\n const { provider } = Arr.headNonEmpty(prepared).pass.model;\n const started = performance.now();\n const results = decideWith(provider, prepared);\n const durationMs = Math.round(performance.now() - started);\n const answers = Bool.match(results.length === prepared.length, {\n onTrue: () => results,\n onFalse: () =>\n pipe(\n prepared,\n Arr.map((): DecideResult => ({\n ok: false,\n reason: `provider ${provider.name} returned ${String(results.length)} results for ${String(prepared.length)} requests`,\n })),\n ),\n });\n for (const [one, decided] of Arr.zip(prepared, answers)) {\n reportAnswer(one, { decided, durationMs });\n }\n};\n\nexport const reportModels = (passes: readonly ModelPass[]): void => {\n const byProvider = Arr.groupBy(\n pipe(\n passes,\n Arr.map((pass) => prepare(pass)),\n ),\n ({ pass }) => pass.model.provider.name,\n );\n for (const prepared of Rec.values(byProvider)) {\n reportProvider(prepared);\n }\n};\n","import type { Context, VisitorWithHooks } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, Record as Rec, pipe, Function as Fn } from \"effect\";\n\nimport {\n commentedSnippetOf,\n contextOf,\n lacksComment,\n isSelected,\n REPORT_LOC,\n TARGET_NODE_TYPES,\n snippetNodeFor,\n optionsError,\n truncateSnippet,\n missingEnvOf,\n failsInCi,\n nowMs,\n warnOnce,\n} from \"#/entities/decision/index.ts\";\nimport type {\n AstNode,\n Match,\n ModelRef,\n ResolvedOptions,\n ResolvedRule,\n SelectedNode,\n Target,\n} from \"#/entities/decision/index.ts\";\n\nimport { reportModels } from \"./report.ts\";\nimport type { ModelPass } from \"./report.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nexport interface Collected {\n readonly options: ResolvedOptions;\n readonly contexts: Readonly<Record<string, Context>>;\n readonly rules: Readonly<Record<string, ResolvedRule>>;\n readonly matches: readonly Match[];\n}\n\nexport interface FileBatch extends Collected {\n readonly contexts: Record<string, Context>;\n readonly rules: Record<string, ResolvedRule>;\n readonly matches: Match[];\n exiting: boolean;\n exits: number;\n}\n\nexport interface RuleFile {\n readonly batch: FileBatch;\n readonly rule: ResolvedRule;\n}\n\nexport interface SharedFile {\n readonly join: (context: Context, id: string) => RuleFile;\n readonly leave: () => void;\n}\n\nexport type OptionsFor = (settings: Readonly<Record<string, unknown>>) => ResolvedOptions;\n\nexport type RuleFor = (rule: ResolvedRule, options: unknown) => ResolvedRule;\n\nconst raisedMissing = new Set<string>();\n\nconst isAvailable = (options: ResolvedOptions, { provider }: ModelRef): boolean => {\n const missingNames = missingEnvOf(options.env, provider);\n if (Arr.isReadonlyArrayEmpty(missingNames)) {\n return true;\n }\n const missing = pipe(missingNames, Arr.join(\", \"));\n if (!failsInCi(options)) {\n warnOnce(`missing:${provider.name}`, `${missing} is not set, skipping ${provider.name} models`);\n } else if (!raisedMissing.has(provider.name)) {\n raisedMissing.add(provider.name);\n throw optionsError(`${missing} is not set`);\n }\n return false;\n};\n\nconst availableModels = (batch: Collected): readonly ModelRef[] => {\n const models = pipe(\n Rec.values(batch.rules),\n Arr.flatMap((rule) => rule.models),\n Arr.map((model) => [model.id, model] as const),\n );\n return pipe(\n Arr.fromIterable(new Map(models).values()),\n Arr.filter((model) => isAvailable(batch.options, model)),\n );\n};\n\nconst snippetOf = (context: Context, node: AstNode): string => {\n if (node.type === \"Program\") {\n return context.sourceCode.text;\n }\n return context.sourceCode.getText(node);\n};\n\nconst namedSnippetOf = (context: Context, node: AstNode): string => {\n const named = snippetNodeFor(node);\n if (named === node) {\n return snippetOf(context, node);\n }\n return context.sourceCode.getText(named);\n};\n\nconst matchOf = (\n context: Context,\n node: AstNode,\n { rule, options }: { readonly rule: ResolvedRule; readonly options: ResolvedOptions },\n): Match => {\n const text = Option.getOrElse(commentedSnippetOf(context, node, rule), () =>\n namedSnippetOf(context, node),\n );\n const surrounding = contextOf(context, node, rule.context ?? { scope: \"node\" });\n return {\n ...Option.match(surrounding, { onNone: () => ({}), onSome: (value) => ({ context: value }) }),\n rule,\n loc: REPORT_LOC[rule.target](node, snippetOf(context, node)),\n snippet: truncateSnippet(text, options.maxSnippetChars),\n truncated: text.length > options.maxSnippetChars,\n };\n};\n\nconst contextOfRule = (batch: Collected, id: string): Context =>\n Option.getOrThrow(Option.fromUndefinedOr(batch.contexts[id]));\n\nconst finish = (batch: Collected): void => {\n const [first] = Rec.values(batch.contexts);\n if (Predicate.isUndefined(first)) {\n return;\n }\n const deadline = nowMs() + batch.options.timeoutMs;\n const passes = pipe(\n availableModels(batch),\n Arr.flatMap((model): readonly ModelPass[] => {\n const matches = pipe(\n batch.matches,\n Arr.filter(({ rule }) =>\n pipe(\n rule.models,\n Arr.some(({ id }) => id === model.id),\n ),\n ),\n );\n return Arr.match(matches, {\n onEmpty: () => [],\n onNonEmpty: (some) => [\n {\n contextOf: (match) => contextOfRule(batch, match.rule.id),\n filename: first.filename,\n options: batch.options,\n model,\n matches: some,\n deadline,\n },\n ],\n });\n }),\n );\n reportModels(passes);\n};\n\nconst ruleIn = (batch: Collected, id: string): ResolvedRule =>\n Option.getOrThrow(Arr.findFirst(batch.options.rules, (rule) => rule.id === id));\n\nexport const sharedFile: {\n (ruleFor: RuleFor): (optionsFor: OptionsFor) => SharedFile;\n (optionsFor: OptionsFor, ruleFor: RuleFor): SharedFile;\n} = Fn.dual(DATA_FIRST_ARITY, (optionsFor: OptionsFor, ruleFor: RuleFor): SharedFile => {\n let current: Option.Option<FileBatch> = Option.none();\n const start = (context: Context): FileBatch => {\n const batch: FileBatch = {\n options: optionsFor(context.settings),\n contexts: {},\n rules: {},\n matches: [],\n exiting: false,\n exits: 0,\n };\n current = Option.some(batch);\n return batch;\n };\n return {\n join: (context, id): RuleFile => {\n const batch = Option.match(current, {\n onNone: () => start(context),\n onSome: (open) => {\n if (open.exiting) {\n return start(context);\n }\n return open;\n },\n });\n const [options] = context.options;\n const rule = ruleFor(ruleIn(batch, id), options);\n batch.contexts[id] = context;\n batch.rules[id] = rule;\n return { batch, rule };\n },\n leave: (): void => {\n if (Option.isNone(current)) {\n return;\n }\n const batch = current.value;\n batch.exits += 1;\n if (batch.exits >= Rec.keys(batch.contexts).length) {\n current = Option.none();\n }\n if (!batch.exiting) {\n batch.exiting = true;\n finish(batch);\n }\n },\n };\n});\n\ntype Visited = SelectedNode & AstNode;\n\nconst isSkipped = (context: Context, node: Visited, rule: ResolvedRule): boolean =>\n !isSelected(context, node, rule) || lacksComment(context, node, rule);\n\nexport interface RuleTarget {\n readonly id: string;\n readonly target: Target;\n}\n\nexport const visitorFor: {\n (rule: RuleTarget): (shared: SharedFile) => (context: Context) => VisitorWithHooks;\n (shared: SharedFile, rule: RuleTarget): (context: Context) => VisitorWithHooks;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (shared: SharedFile, { id, target }: RuleTarget) =>\n (context: Context): VisitorWithHooks => {\n let file: Option.Option<RuleFile> = Option.none();\n\n const collect = (node: Visited): void => {\n if (Option.isNone(file)) {\n return;\n }\n const { batch, rule } = file.value;\n if (isSkipped(context, node, rule)) {\n return;\n }\n batch.matches.push(matchOf(context, node, { rule, options: batch.options }));\n };\n\n const nodeTypes: readonly string[] = TARGET_NODE_TYPES[target];\n\n return {\n ...Rec.fromEntries(\n pipe(\n nodeTypes,\n Arr.map((type) => [type, collect]),\n ),\n ),\n Program: (node: Visited): void => {\n file = Option.some(shared.join(context, id));\n if (target === \"file\") {\n collect(node);\n }\n },\n \"Program:exit\": (): void => {\n file = Option.none();\n shared.leave();\n },\n };\n },\n);\n","import type { Location } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, pipe } from \"effect\";\n\nimport {\n BOOLEAN_ANSWER,\n buildRequest,\n isReported,\n missingEnvOf,\n nowMs,\n refAt,\n resolveModel,\n} from \"#/entities/decision/index.ts\";\nimport type { DecisionProvider, Match, ModelRef, RuleLocation } from \"#/entities/decision/index.ts\";\n\nimport { inputOf, locateMatch, verdictsOf } from \"./locate.ts\";\nimport type { Asking } from \"./locate.ts\";\n\nconst FIRST_MATCH = 0;\n\nconst FILE_START: Location = { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } };\n\nconst DEFAULT_LOCATION: RuleLocation = {\n question: \"Select the line that holds the text which breaks the rule.\",\n cutoff: 0.5,\n};\n\n/** @internal */\nexport interface TextRule {\n readonly id: string;\n readonly question: string;\n readonly cutoff: number;\n readonly location?: RuleLocation;\n}\n\n/** @internal */\nexport interface JudgeTextInput {\n readonly rule: TextRule;\n readonly text: string;\n readonly model: string;\n readonly timeoutMs: number;\n readonly env: Readonly<Record<string, string>>;\n}\n\n/** @internal */\nexport type JudgedText =\n | { readonly status: \"violation\"; readonly line: number }\n | { readonly status: \"pass\" }\n | { readonly status: \"unknown\"; readonly reason: string };\n\nconst unknownBecause = (reason: string): JudgedText => ({ status: \"unknown\", reason });\n\nconst matchOf = ({ rule, text }: JudgeTextInput, model: ModelRef): Match => ({\n rule: {\n id: rule.id,\n target: \"file\",\n question: rule.question,\n cutoff: rule.cutoff,\n location: rule.location ?? DEFAULT_LOCATION,\n answer: BOOLEAN_ANSWER,\n models: [model],\n },\n snippet: text,\n truncated: false,\n loc: FILE_START,\n});\n\nconst judgeWith = (input: JudgeTextInput, model: ModelRef): JudgedText => {\n const match = matchOf(input, model);\n const request = buildRequest(model.model, [match]);\n const asking: Asking = { model, deadline: nowMs() + input.timeoutMs, env: input.env };\n const decided = verdictsOf(model.provider.decide(inputOf(asking, request)), request);\n if (!decided.ok) {\n return unknownBecause(decided.reason);\n }\n const ref = refAt(FIRST_MATCH);\n return Option.match(Option.fromUndefinedOr(decided.verdicts.results[ref]), {\n onNone: () => unknownBecause(\"the decision model returned no answer\"),\n onSome: (verdict): JudgedText => {\n if (!isReported(match.rule, verdict)) {\n return { status: \"pass\" };\n }\n const located = locateMatch(asking, match, { ref, verdicts: decided.verdicts, request });\n return { status: \"violation\", line: located.loc.start.line };\n },\n });\n};\n\n/** @internal */\nexport const judgeTextWith =\n (providers: Readonly<Record<string, DecisionProvider>>) =>\n (input: JudgeTextInput): JudgedText => {\n const model = resolveModel(input.model, providers);\n const missing = missingEnvOf(input.env, model.provider);\n if (Arr.isReadonlyArrayNonEmpty(missing)) {\n return unknownBecause(`${pipe(missing, Arr.join(\", \"))} is not set`);\n }\n return judgeWith(input, model);\n };\n","import { Array as Arr, Effect, Option, String as Str, pipe } from \"effect\";\nimport { createSyncFn } from \"synckit\";\nimport type { Syncify } from \"synckit\";\n\nimport { messageOf, runOrElse } from \"#/entities/decision/index.ts\";\nimport type { DecideInput, DecideResult, DecisionProvider } from \"#/entities/decision/index.ts\";\n\nconst BACKSTOP_MS = 60_000;\nconst SYNCKIT_TIMEOUT = \"Internal error: Atomics.wait() failed: timed-out\";\nconst BUILT_EXTENSION = \".mjs\";\nconst MODULE_EXTENSION = /\\.[cm]?[jt]s$/u;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\ntype Results = Arr.NonEmptyReadonlyArray<DecideResult>;\n\ntype Worker = (inputs: Inputs) => Promise<Results>;\n\n/** @internal */\nexport interface SyncProviderSetup extends Pick<\n DecisionProvider,\n \"name\" | \"requiredEnv\" | \"models\"\n> {\n readonly worker: string;\n}\n\nconst workers = new Map<string, Syncify<Worker>>();\n\nconst workerUrl = (worker: string): URL => {\n const extension = pipe(\n Str.match(MODULE_EXTENSION)(import.meta.url),\n Option.flatMap(Arr.head),\n Option.getOrElse(() => BUILT_EXTENSION),\n );\n return new URL(`${worker}${extension}`, import.meta.url);\n};\n\nconst workerCall = (worker: string): Syncify<Worker> =>\n workers.getOrInsertComputed(worker, () =>\n createSyncFn<Worker>(workerUrl(worker), { timeout: BACKSTOP_MS }),\n );\n\nconst reasonOf = (error: unknown): string => {\n const message = messageOf(error);\n if (message === SYNCKIT_TIMEOUT) {\n return \"timeout\";\n }\n return `network: ${message}`;\n};\n\nconst askWorker = (worker: string, inputs: Inputs): Results =>\n runOrElse(\n Effect.sync(() => workerCall(worker)(inputs)),\n (cause) =>\n pipe(\n inputs,\n Arr.map((): DecideResult => ({ ok: false, reason: reasonOf(cause) })),\n ),\n );\n\n/** @internal */\nexport const syncProvider = ({ worker, ...provider }: SyncProviderSetup): DecisionProvider => ({\n ...provider,\n decide: (input) => Arr.headNonEmpty(askWorker(worker, [input])),\n decideAll: (inputs) =>\n Arr.match(inputs, { onEmpty: () => [], onNonEmpty: (some) => askWorker(worker, some) }),\n});\n","import { CLEF_MODEL } from \"#/entities/decision/index.ts\";\n\nimport { syncProvider } from \"./sync-provider.ts\";\n\nexport const cloudflare = syncProvider({\n name: \"cloudflare\",\n worker: \"cloudflare-worker\",\n requiredEnv: [\"CLOUDFLARE_API_TOKEN\", \"CLOUDFLARE_ACCOUNT_ID\"],\n models: CLEF_MODEL,\n});\n","import { JEV_MODEL } from \"#/entities/decision/index.ts\";\n\nimport { syncProvider } from \"./sync-provider.ts\";\n\nexport const typesafe = syncProvider({\n name: \"typesafe\",\n worker: \"typesafe-worker\",\n requiredEnv: [\"TYPESAFE_API_KEY\"],\n models: JEV_MODEL,\n});\n","import { Array as Arr, Record as Rec, pipe } from \"effect\";\n\nimport type { DecisionProvider } from \"#/entities/decision/index.ts\";\n\nimport { cloudflare } from \"./cloudflare.ts\";\nimport { typesafe } from \"./typesafe.ts\";\n\n/** @internal */\nexport const decisionProviders: Readonly<Record<string, DecisionProvider>> = Rec.fromEntries(\n pipe(\n [cloudflare, typesafe],\n Arr.map((provider) => [provider.name, provider]),\n ),\n);\n","import { judgeTextWith } from \"#/features/judge-code/index.ts\";\n\nimport { decisionProviders } from \"./providers.ts\";\n\nexport const judgeText = judgeTextWith(decisionProviders);\n","import { Schema } from \"effect\";\n\nconst TallyFields = Schema.Struct({\n library: Schema.String,\n version: Schema.String,\n kind: Schema.String,\n name: Schema.String,\n calls: Schema.Finite,\n});\n\nexport type Tally = typeof TallyFields.Type;\n\nexport const TallyList = Schema.Array(TallyFields);\n\nexport const SPOOL_ENV = \"USAGE_METER_SPOOL\";\n\nexport const CALLS_METRIC = \"code.usage.calls\";\n\nexport const NO_CALLS = 0;\n","import {\n Array as Arr,\n Effect,\n FileSystem,\n Layer,\n Option,\n Path,\n Random,\n Schema,\n pipe,\n} from \"effect\";\nimport type { Context } from \"effect\";\n\nimport { TallyList } from \"./usage-tally.ts\";\nimport type { Tally } from \"./usage-tally.ts\";\n\nexport interface Seen {\n readonly moduleUrl: string;\n readonly kind: string;\n readonly name: string;\n readonly calls: number;\n}\n\nconst ManifestFields = Schema.Struct({ name: Schema.String, version: Schema.String });\n\ntype Manifest = typeof ManifestFields.Type;\n\ntype Services = FileSystem.FileSystem | Path.Path;\n\nconst MANIFEST = \"package.json\";\n\nconst decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(ManifestFields));\n\nconst encodeTallies = Schema.encodeEffect(Schema.fromJsonString(TallyList));\n\nconst manifestAbove = (\n directory: string,\n): Effect.Effect<Option.Option<Manifest>, never, Services> =>\n Effect.gen(function* manifestAboveDirectory() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const text = yield* fs.readFileString(path.join(directory, MANIFEST)).pipe(Effect.option);\n const found = pipe(text, Option.flatMap(decodeManifest));\n const parent = path.dirname(directory);\n if (Option.isSome(found) || parent === directory) {\n return found;\n }\n return yield* manifestAbove(parent);\n });\n\nconst tallyOf = ({\n moduleUrl,\n kind,\n name,\n calls,\n}: Seen): Effect.Effect<Option.Option<Tally>, never, Services> =>\n Effect.gen(function* tallyOfSeen() {\n const path = yield* Path.Path;\n const file = yield* path.fromFileUrl(new URL(moduleUrl)).pipe(Effect.option);\n if (Option.isNone(file)) {\n return Option.none<Tally>();\n }\n const manifest = yield* manifestAbove(path.dirname(file.value));\n return pipe(\n manifest,\n Option.map(({ name: library, version }): Tally => ({ library, version, kind, name, calls })),\n );\n });\n\nconst written = (spool: string, seen: readonly Seen[]): Effect.Effect<void, never, Services> =>\n Effect.gen(function* writeSpool() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const tallies = yield* Effect.forEach(seen, tallyOf, { concurrency: \"unbounded\" }).pipe(\n Effect.map(Arr.getSomes),\n );\n const text = yield* encodeTallies(tallies);\n const suffix = yield* Random.nextInt;\n yield* fs.makeDirectory(spool, { recursive: true });\n yield* fs.writeFileString(\n path.join(spool, `${String(process.pid)}-${String(suffix)}.json`),\n text,\n );\n }).pipe(Effect.ignore);\n\nconst taggedError = Schema.TaggedError;\n\nclass NodeServicesMissing extends taggedError<\n NodeServicesMissing,\n { readonly brand: unique symbol }\n>()(\"NodeServicesMissing\", { message: Schema.String }) {}\n\nconst nodeServices = Effect.tryPromise({\n try: () => import(\"@effect/platform-node/NodeServices\"),\n catch: () => NodeServicesMissing.make({ message: \"@effect/platform-node could not be loaded\" }),\n}).pipe(Effect.flatMap(({ layer }) => Layer.build(layer)));\n\nexport const spoolWritten =\n (spool: string) =>\n (seen: readonly Seen[]): Effect.Effect<void> =>\n nodeServices.pipe(\n Effect.flatMap((services: Context.Context<Services>) =>\n Effect.provideContext(written(spool, seen), services),\n ),\n Effect.scoped,\n Effect.ignore,\n );\n","import {\n Array as Arr,\n Config,\n Effect,\n Exit,\n Option,\n Predicate,\n Record as Rec,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { spoolWritten } from \"./usage-spool.ts\";\nimport type { Seen } from \"./usage-spool.ts\";\nimport { NO_CALLS, SPOOL_ENV } from \"./usage-tally.ts\";\n\nexport interface UsageMeter {\n readonly rules: <Name extends string, Rule>(\n rules: Readonly<Record<Name, Rule>>,\n ) => Readonly<Record<Name, Rule>>;\n readonly functions: <Name extends string, Value>(\n functions: Readonly<Record<Name, Value>>,\n ) => Readonly<Record<Name, Value>>;\n readonly plugins: <Plugin extends RulePlugin>(\n plugins: Readonly<Record<string, Plugin>>,\n ) => Readonly<Record<string, Plugin>>;\n readonly within: (prefix: string) => UsageMeter;\n}\n\nexport interface RulePlugin {\n readonly rules?: Readonly<Record<string, unknown>> | undefined;\n}\n\ninterface Declared {\n readonly moduleUrl: string;\n readonly kind: string;\n readonly name: string;\n}\n\ntype Callable = (...args: readonly unknown[]) => unknown;\n\nconst RULE_ENTRIES = [\"create\", \"createOnce\", \"check\", \"linter\", \"fixer\"] as const;\n\nconst RULE = \"rule\";\n\nconst FUNCTION = \"function\";\n\nconst ONE_CALL = 1;\n\nconst PREFIX_SEPARATOR = \"/\";\n\nconst KEY_SEPARATOR = \"\\u0000\";\n\nconst idle: UsageMeter = {\n rules: (rules) => rules,\n functions: (functions) => functions,\n plugins: (plugins) => plugins,\n within: () => idle,\n};\n\nconst declared = new Map<string, Declared>();\n\nconst calls = new Map<string, number>();\n\nconst state = { flushed: false, scheduled: false };\n\nconst spoolSetting = Exit.match(\n Effect.runSyncExit(Config.NonEmptyString(SPOOL_ENV).pipe(Config.option)),\n {\n onSuccess: (value) => value,\n onFailure: () => Option.none<string>(),\n },\n);\n\nconst isCallable = (value: unknown): value is Callable => Predicate.isFunction(value);\n\nconst keyOf = ({ moduleUrl, kind, name }: Declared): string =>\n Arr.join([moduleUrl, kind, name], KEY_SEPARATOR);\n\nconst countCall = (key: string): void => {\n const next = (calls.get(key) ?? NO_CALLS) + ONE_CALL;\n calls.set(key, next);\n};\n\nconst counted = <Value extends Callable>(key: string, callable: Value): Value =>\n Object.assign(function countedCall(this: unknown, ...args: readonly unknown[]): unknown {\n countCall(key);\n return callable.call(this, ...args);\n }, callable);\n\nconst ruleCounted = <Rule>(key: string, rule: Rule): Rule => {\n if (isCallable(rule)) {\n return counted(key, rule);\n }\n if (!Predicate.isObject(rule)) {\n return rule;\n }\n const entries = pipe(\n RULE_ENTRIES,\n Arr.flatMap((entry) =>\n pipe(\n Option.liftPredicate(Rec.get({ ...rule }, entry), Option.isSome),\n Option.flatMap((found) => Option.liftPredicate(found.value, isCallable)),\n Option.map((callable) => [entry, counted(key, callable)] as const),\n Option.toArray,\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(entries)) {\n return rule;\n }\n return { ...rule, ...Rec.fromEntries(entries) };\n};\n\nconst functionCounted = <Value>(key: string, value: Value): Value => {\n if (isCallable(value)) {\n return counted(key, value);\n }\n return value;\n};\n\nexport const flushUsage: Effect.Effect<void> = Effect.suspend(() => {\n if (state.flushed || Option.isNone(spoolSetting)) {\n return Effect.void;\n }\n state.flushed = true;\n const seen = pipe(\n [...declared],\n Arr.map(([key, exported]): Seen => ({ ...exported, calls: calls.get(key) ?? NO_CALLS })),\n );\n return spoolWritten(spoolSetting.value)(seen);\n});\n\nconst flushOnExit = (): void => {\n if (state.scheduled) {\n return;\n }\n state.scheduled = true;\n process.once(\"beforeExit\", () => {\n Effect.runFork(flushUsage);\n });\n};\n\nconst qualified = (prefix: string, name: string): string =>\n pipe([prefix, name], Arr.filter(Str.isNonEmpty), Arr.join(PREFIX_SEPARATOR));\n\nconst wrapped =\n (moduleUrl: string, prefix: string, kind: string) =>\n <Name extends string, Value>(\n wrap: (key: string, value: Value) => Value,\n ): ((names: Readonly<Record<Name, Value>>) => Readonly<Record<Name, Value>>) =>\n (names) => {\n flushOnExit();\n return pipe(\n names,\n Rec.map((value: Value, name: Name) => {\n const exported: Declared = { moduleUrl, kind, name: qualified(prefix, name) };\n declared.set(keyOf(exported), exported);\n return wrap(keyOf(exported), value);\n }),\n );\n };\n\nconst meterOf = (moduleUrl: string, prefix: string): UsageMeter => {\n const rules: UsageMeter[\"rules\"] = (named) =>\n wrapped(moduleUrl, prefix, RULE)(ruleCounted)(named);\n const plugins: UsageMeter[\"plugins\"] = (named) =>\n pipe(\n named,\n Rec.map((plugin, name) =>\n pipe(\n Option.fromUndefinedOr(plugin.rules),\n Option.match({\n onNone: () => plugin,\n onSome: (pluginRules) => ({\n ...plugin,\n rules: meterOf(moduleUrl, qualified(prefix, name)).rules(pluginRules),\n }),\n }),\n ),\n ),\n );\n return {\n rules,\n functions: (named) => wrapped(moduleUrl, prefix, FUNCTION)(functionCounted)(named),\n plugins,\n within: (inner) => meterOf(moduleUrl, qualified(prefix, inner)),\n };\n};\n\nexport const usageMeter = (moduleUrl: string): UsageMeter =>\n pipe(\n spoolSetting,\n Option.match({\n onNone: () => idle,\n onSome: () => meterOf(moduleUrl, \"\"),\n }),\n );\n","import type { Plugin, RuleMeta } from \"@oxlint/plugins\";\nimport { usageMeter } from \"@r_masseater/masseater-utils/usage-meter\";\nimport { Array as Arr, Record as Rec, Struct, pipe } from \"effect\";\n\nimport { PREFIX, checkRules, resolveOptions, toJson } from \"#/entities/decision/index.ts\";\nimport type {\n DecisionOptions,\n DecisionPlugin,\n DecisionPluginSetup,\n DecisionProvider,\n DecisionRule,\n ResolvedOptions,\n ResolvedRule,\n} from \"#/entities/decision/index.ts\";\nimport {\n RULE_OPTIONS_SCHEMA,\n overrideRule,\n sharedFile,\n visitorFor,\n} from \"#/features/judge-code/index.ts\";\n\nimport { decisionProviders } from \"./providers.ts\";\n\nconst DEFAULT_NAME = \"decision\";\n\nconst metaOf = (rule: DecisionRule): RuleMeta => ({\n type: \"problem\",\n docs: { description: rule.question },\n schema: RULE_OPTIONS_SCHEMA,\n messages: {\n yes: \"[{{id}}] {{model}} answered {{answer}} ({{score}} >= {{cutoff}}): {{question}}\",\n unlocated: `${PREFIX}: {{reason}} while refining the location of [{{id}}]; the finding is reported at the file level`,\n },\n});\n\nconst optionsOf = (setup: DecisionPluginSetup): DecisionOptions =>\n Struct.omit(setup, [\"name\", \"rules\"]);\n\ntype Resolve = (settings: unknown) => ResolvedOptions;\n\nconst memoized = (resolve: Resolve): Resolve => {\n const resolved = new Map<string, ResolvedOptions>();\n return (settings) => {\n const key = toJson([settings]);\n return resolved.getOrInsertComputed(key, () => resolve(settings));\n };\n};\n\nconst memoizedRules = (\n providers: Readonly<Record<string, DecisionProvider>>,\n): ((rule: ResolvedRule, options: unknown) => ResolvedRule) => {\n const resolved = new WeakMap<ResolvedRule, Map<string, ResolvedRule>>();\n return (rule, options) => {\n const known = resolved.getOrInsertComputed(rule, () => new Map<string, ResolvedRule>());\n const key = toJson([options]);\n return known.getOrInsertComputed(key, () => overrideRule(rule, options, providers));\n };\n};\n\nexport const createDecisionPlugin = (setup: DecisionPluginSetup): DecisionPlugin => {\n const name = setup.name ?? DEFAULT_NAME;\n const rules = checkRules(setup.rules);\n const options = optionsOf(setup);\n const resolve = memoized((settings) =>\n resolveOptions({ options, settings }, rules, decisionProviders),\n );\n resolve({});\n const shared = sharedFile(\n (settings) => resolve(settings[name]),\n memoizedRules(decisionProviders),\n );\n\n const created = Rec.fromEntries(\n pipe(\n rules,\n Arr.map((rule) => [rule.id, { meta: metaOf(rule), createOnce: visitorFor(shared, rule) }]),\n ),\n );\n return {\n meta: { name },\n rules: usageMeter(import.meta.url)\n .within(name)\n .rules(created),\n } satisfies Plugin;\n};\n"],"mappings":";;;;AAAA,MAAa,gBAAgB;ACEf,MAAM,SAASA,SAAI,QAAQ,CAAC,SAAqC,GAAG;AAmClF,MAAa,eACJ,cACN,SACCC,MAAI,OAAO,SAAS,IAAI,IAAI,YAC1B,KACE,SACA,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AAS,oBAAoB,WAAW,QAAQ,QAAQ,CAAC;CAClE;AACF;AAEA,MAAM,iBACJ,cAC6D;CAC7D,MAAM,2BAAW,IAAI,QAAiD;CACtE,QAAQ,MAAM,YAAY;EACxB,MAAM,QAAQ,SAAS,oBAAoB,4BAAY,IAAI,IAA0B,CAAC;EACtF,MAAM,MAAM,OAAO,CAAC,OAAO,CAAC;EAC5B,OAAO,MAAM,oBAAoB,WAAW,aAAa,MAAM,SAAS,SAAS,CAAC;CACpF;AACF;AAEA,MAAa,wBAAwB,UAA+C;CAClF,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,QAAQ,WAAW,MAAM,KAAK;CACpC,MAAM,UAAU,UAAU,KAAK;CAC/B,MAAM,UAAU,UAAU,aACxB,eAAe;EAAE;EAAS;CAAS,GAAG,OAAO,iBAAiB,CAChE;CACA,QAAQ,CAAC,CAAC;CACV,MAAM,SAAS,YACZ,aAAa,QAAQ,SAAS,KAAK,GACpC,cAAc,iBAAiB,CACjC;CAEA,MAAM,UAAUE,OAAI,YAClB,KACE,OACAC,MAAI,KAAK,SAAS,CAAC,KAAK,IAAI;EAAE,MAAM,OAAO,IAAI;EAAG,YAAY,WAAW,QAAQ,IAAI;CAAE,CAAC,CAAC,CAC3F,CACF;CACA,OAAO;EACL,MAAM,EAAE,KAAK;EACb,OAAO,WAAW,YAAY,GAAG,CAAC,CAC/B,OAAO,IAAI,CAAC,CACZ,MAAM,OAAO;CAClB;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as defineDecisionRule } from "./app-
|
|
1
|
+
import { r as defineDecisionRule } from "./app-1jZ4qJYY.mjs";
|
|
2
2
|
import { Array, Function, Match, Option, Predicate, Record, pipe } from "effect";
|
|
3
3
|
// src/features/define-presets/lib/select.ts
|
|
4
4
|
const DATA_FIRST_ARITY = 2;
|
|
@@ -33,4 +33,4 @@ const ENCLOSING_FUNCTION = {
|
|
|
33
33
|
};
|
|
34
34
|
export { dualSelect as a, containing as i, ENCLOSING_FUNCTION as n, identifierOf as o, claimRule as r, ofType as s, COMMENT as t };
|
|
35
35
|
|
|
36
|
-
//# sourceMappingURL=claim-rule-
|
|
36
|
+
//# sourceMappingURL=claim-rule-Dzu69Utl.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claim-rule-
|
|
1
|
+
{"version":3,"file":"claim-rule-Dzu69Utl.mjs","names":["Fn","Rec","Arr","Arr"],"sources":["../src/features/define-presets/lib/select.ts","../src/features/define-presets/lib/claim-rule.ts"],"sourcesContent":["import {\n Match,\n Option,\n Predicate,\n Array as Arr,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport type { DecisionRule, SelectMatch, SelectedNode } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nexport type Select = NonNullable<DecisionRule[\"select\"]>;\n\nexport interface DualSelect {\n (match: SelectMatch): (node: SelectedNode) => boolean;\n (node: SelectedNode, match: SelectMatch): boolean;\n}\n\nexport const dualSelect = (select: Select): DualSelect => Fn.dual(DATA_FIRST_ARITY, select);\n\nexport type NodeTest = Predicate.Predicate<SelectedNode>;\n\nconst childrenOf = (node: SelectedNode): readonly SelectedNode[] =>\n pipe(\n Rec.toEntries<string, unknown>(node),\n Arr.filter(([key]) => key !== \"parent\"),\n Arr.flatMap(([, value]) => Arr.ensure(value)),\n Arr.filter((value): value is SelectedNode => Predicate.hasProperty(value, \"type\")),\n );\n\nconst descendantsOf = (node: SelectedNode): readonly SelectedNode[] => [\n node,\n ...pipe(\n childrenOf(node),\n Arr.flatMap((child) => descendantsOf(child)),\n ),\n];\n\nexport const containing =\n (test: NodeTest): NodeTest =>\n (node) =>\n pipe(\n descendantsOf(node),\n Arr.some((found) => test(found)),\n );\n\nexport const ofType =\n (...types: readonly string[]): NodeTest =>\n (node) =>\n types.includes(node.type);\n\nexport const identifierOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"Identifier\" }, (identifier) => Option.some(identifier.name)),\n Match.orElse(() => Option.none()),\n );\n","import { Predicate, Array as Arr, pipe } from \"effect\";\n\nimport { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport type { DecisionRule, RuleContext } from \"#/entities/decision/index.ts\";\n\nexport interface Judgement {\n readonly ask: string;\n readonly yes: string;\n readonly no: string;\n readonly note?: string | undefined;\n}\n\nexport interface ClaimRule\n extends Judgement, Pick<DecisionRule, \"id\" | \"cutoff\" | \"select\" | \"context\"> {\n readonly target?: Extract<DecisionRule[\"target\"], \"function\" | \"call\">;\n}\n\nconst questionOf = ({ ask, yes, no, note }: Judgement): string =>\n pipe(\n [ask, `It is true when: ${yes}`, `It is false when: ${no}`, note],\n Arr.filter((part) => Predicate.isNotUndefined(part)),\n Arr.join(\"\\n\\n\"),\n );\n\nexport const claimRule = ({ ask, yes, no, note, ...rule }: ClaimRule): DecisionRule =>\n defineDecisionRule({\n target: \"function\",\n ...rule,\n message: ask,\n question: questionOf({ ask, yes, no, note }),\n });\n\nexport const COMMENT: RuleContext = { scope: \"comment\" };\nexport const ENCLOSING_FUNCTION: RuleContext = { scope: \"enclosing\", kind: \"function\" };\n"],"mappings":";;;AAYA,MAAM,mBAAmB;AASzB,MAAa,cAAc,WAA+BA,SAAG,KAAK,kBAAkB,MAAM;AAI1F,MAAM,cAAc,SAClB,KACEC,OAAI,UAA2B,IAAI,GACnCC,MAAI,QAAQ,CAAC,SAAS,QAAQ,QAAQ,GACtCA,MAAI,SAAS,GAAG,WAAWA,MAAI,OAAO,KAAK,CAAC,GAC5CA,MAAI,QAAQ,UAAiC,UAAU,YAAY,OAAO,MAAM,CAAC,CACnF;AAEF,MAAM,iBAAiB,SAAgD,CACrE,MACA,GAAG,KACD,WAAW,IAAI,GACfA,MAAI,SAAS,UAAU,cAAc,KAAK,CAAC,CAC7C,CACF;AAEA,MAAa,cACV,UACA,SACC,KACE,cAAc,IAAI,GAClBA,MAAI,MAAM,UAAU,KAAK,KAAK,CAAC,CACjC;AAEJ,MAAa,UACV,GAAG,WACH,SACC,MAAM,SAAS,KAAK,IAAI;AAE5B,MAAa,gBAAgB,SAC3B,MAAM,MAAM,IAAI,CAAC,CAAC,KAChB,MAAM,KAAK,EAAE,MAAM,aAAa,IAAI,eAAe,OAAO,KAAK,WAAW,IAAI,CAAC,GAC/E,MAAM,aAAa,OAAO,KAAK,CAAC,CAClC;;ACzCF,MAAM,cAAc,EAAE,KAAK,KAAK,IAAI,WAClC,KACE;CAAC;CAAK,oBAAoB;CAAO,qBAAqB;CAAM;AAAI,GAChEC,MAAI,QAAQ,SAAS,UAAU,eAAe,IAAI,CAAC,GACnDA,MAAI,KAAK,MAAM,CACjB;AAEF,MAAa,aAAa,EAAE,KAAK,KAAK,IAAI,MAAM,GAAG,WACjD,mBAAmB;CACjB,QAAQ;CACR,GAAG;CACH,SAAS;CACT,UAAU,WAAW;EAAE;EAAK;EAAK;EAAI;CAAK,CAAC;AAC7C,CAAC;AAEH,MAAa,UAAuB,EAAE,OAAO,UAAU;AACvD,MAAa,qBAAkC;CAAE,OAAO;CAAa,MAAM;AAAW"}
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as createDecisionPlugin, r as defineDecisionRule, n as judgeText } from "./app-
|
|
1
|
+
export { t as createDecisionPlugin, r as defineDecisionRule, n as judgeText } from "./app-1jZ4qJYY.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as defineDecisionRule, t as createDecisionPlugin } from "./app-
|
|
2
|
-
import { a as dualSelect, i as containing, n as ENCLOSING_FUNCTION, o as identifierOf, r as claimRule, s as ofType, t as COMMENT } from "./claim-rule-
|
|
1
|
+
import { r as defineDecisionRule, t as createDecisionPlugin } from "./app-1jZ4qJYY.mjs";
|
|
2
|
+
import { a as dualSelect, i as containing, n as ENCLOSING_FUNCTION, o as identifierOf, r as claimRule, s as ofType, t as COMMENT } from "./claim-rule-Dzu69Utl.mjs";
|
|
3
3
|
import { Array, Match, Option, Predicate, String, pipe } from "effect";
|
|
4
4
|
// src/features/define-presets/lib/claim-select.ts
|
|
5
5
|
const WORD_STARTS = /* @__PURE__ */ new Set(["", ...String.split("_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", "")]);
|
|
@@ -344,4 +344,4 @@ const presetPlugin = (rules) => createDecisionPlugin({
|
|
|
344
344
|
});
|
|
345
345
|
export { safeNameIsSafe as A, docErrorsMatchBody as C, logLevelMatchesEvent as D, idempotentName as E, logMessageMatchesEvent as O, commentDescribesDeclaration as S, fnNamePromises as T, preferSchemaValidation as _, strict as a, codeClaims as b, testClaims as c, testNameVerifiesClaim as d, domainNaming as f, noPromptInjection as g, noPiiInLogs as h, reviewOnly as i, varNameDescribesValue as j, pureNameIsPure as k, testMocksSubject as l, noHardcodedSecrets as m, presets as n, describeNamesSubject as o, nameMatchesBehavior as p, recommended as r, snapshotOnlyBehaviourClaim as s, presetPlugin as t, testNameDescribesCode as u, untrustedInputRisk as v, errorMessageMatchesCondition as w, commentDescribesBlock as x, catchHidesFailure as y };
|
|
346
346
|
|
|
347
|
-
//# sourceMappingURL=preset-plugin-
|
|
347
|
+
//# sourceMappingURL=preset-plugin-miAjemLS.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preset-plugin-DlO5OR3z.mjs","names":["Str","Arr"],"sources":["../src/features/define-presets/lib/claim-select.ts","../src/features/define-presets/model/code-claims.ts","../src/features/define-presets/model/rules.ts","../src/features/define-presets/model/test-claims.ts","../src/features/define-presets/model/presets.ts","../src/app/preset-plugin.ts"],"sourcesContent":["import { Array as Arr, Match, Option, Predicate, String as Str, pipe } from \"effect\";\n\nimport type { SelectedNode } from \"#/entities/decision/index.ts\";\n\nimport { containing, dualSelect, identifierOf, ofType } from \"./select.ts\";\nimport type { DualSelect, NodeTest, Select } from \"./select.ts\";\n\nconst WORD_STARTS: ReadonlySet<string> = new Set([\n \"\",\n ...Str.split(\"_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"\"),\n]);\n\nconst NEXT_CHARACTER = 1;\n\nconst startsWithWord =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Predicate.and(\n (text: string) => Str.startsWith(word)(text),\n (text: string) => WORD_STARTS.has(Str.slice(word.length, word.length + NEXT_CHARACTER)(text)),\n )(name);\n\nconst endsWith =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Str.endsWith(word)(name);\n\nexport interface NameWords {\n readonly prefixes: readonly string[];\n readonly suffixes?: readonly string[];\n}\n\nexport const namedLike = ({ prefixes, suffixes = [] }: NameWords): Select => {\n const matchers = [\n ...pipe(\n prefixes,\n Arr.map((word) => startsWithWord(word)),\n ),\n ...pipe(\n suffixes,\n Arr.map((word) => endsWith(word)),\n ),\n ];\n return (_node, { name }) =>\n Option.exists(Option.fromUndefinedOr(name), (found) =>\n pipe(\n matchers,\n Arr.some((matches) => matches(found)),\n ),\n );\n};\n\nconst rootOf = (callee: SelectedNode): Option.Option<string> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) => rootOf(member.object)),\n Match.orElse(identifierOf),\n );\n\nconst calleeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) => Option.some(call.callee)),\n Match.orElse(() => Option.none()),\n );\n\nconst callingAny =\n (roots: readonly string[]): Select =>\n (node) =>\n Option.exists(Option.flatMap(calleeOf(node), rootOf), (root) => roots.includes(root));\n\nconst LOG_LEVELS: ReadonlySet<string> = new Set([\n \"trace\",\n \"debug\",\n \"verbose\",\n \"info\",\n \"log\",\n \"warn\",\n \"warning\",\n \"error\",\n \"fatal\",\n]);\n\nconst lastNameOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n identifierOf(member.property),\n ),\n Match.orElse(identifierOf),\n );\n\nconst isLogger = (name: string): boolean =>\n Arr.some([\"console\", \"log\"], (word) => Str.includes(word)(Str.toLowerCase(name)));\n\ninterface LogCall {\n readonly level: Option.Option<string>;\n readonly logger: Option.Option<string>;\n}\n\nconst logCallOf = (callee: SelectedNode): Option.Option<LogCall> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n Option.some({ level: identifierOf(member.property), logger: lastNameOf(member.object) }),\n ),\n Match.orElse(() => Option.none()),\n );\n\nexport const isLogCall: DualSelect = dualSelect((node) =>\n Option.exists(Option.flatMap(calleeOf(node), logCallOf), ({ level, logger }) =>\n Predicate.and(\n () => Option.exists(level, (found) => LOG_LEVELS.has(found)),\n () => Option.exists(logger, isLogger),\n )(node),\n ),\n);\n\nconst isCatchName = (name: SelectedNode): boolean =>\n Match.value(name).pipe(\n Match.when({ type: \"Identifier\" }, (identifier) => Str.startsWith(\"catch\")(identifier.name)),\n Match.orElse(() => false),\n );\n\nconst isCatch: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CatchClause\" }, () => true),\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n isCatchName(member.property),\n ),\n Match.when({ type: \"Property\", computed: false }, (property) => isCatchName(property.key)),\n Match.orElse(() => false),\n );\n\nexport const hasCatch: DualSelect = dualSelect(containing(isCatch));\n\nconst hasCallbackArgument: Select = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) =>\n pipe(\n call.arguments,\n Arr.some((argument) => ofType(\"ArrowFunctionExpression\", \"FunctionExpression\")(argument)),\n ),\n ),\n Match.orElse(() => false),\n );\n\nexport const isTestCall: DualSelect = dualSelect((node, match) =>\n pipe(\n [callingAny([\"it\", \"test\"]), hasCallbackArgument],\n Arr.every((select) => select(node, match)),\n ),\n);\n\nexport const isDescribeCall: DualSelect = dualSelect(callingAny([\"describe\"]));\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport {\n COMMENT,\n ENCLOSING_FUNCTION,\n claimRule,\n} from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { hasCatch, isLogCall, namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const fnNamePromises = claimRule({\n id: \"fn-name-promises\",\n cutoff: 0.8,\n ask: \"The body of this function does something materially different from what its name promises.\",\n yes: \"Someone who read only the name and the parameter list would be wrong about what this function does: it returns a different kind of thing than the name suggests (a count that is a list, a predicate that is a number), it changes state when the name says it only reads, checks, looks up or serialises, it can fail or return nothing when the name promises a value, it handles only a narrower case than the name claims, it never performs an effect or repetition the name names (a drain or remove that leaves the container as it was, a retry that tries once), it computes something no reading of the name accounts for, or it does substantial work the name does not mention at all, such as writing what it was asked to read.\",\n no: \"The name and parameter list describe what the body actually does. Someone who read only them would not be surprised by the body, even if a longer or more specific name could be imagined. A terse or conventional name (run, handle, take, len, fmt, toString, a getter) that the body fits is not a violation, and a comment inside the body that is wrong about the body is a wrong comment, not a wrong name.\",\n});\n\nexport const pureNameIsPure = claimRule({\n id: \"pure-name-is-pure\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"compute\", \"calculate\", \"derive\", \"format\", \"to\", \"parse\"] }),\n ask: \"This function's name presents it as a computation of a result from its inputs, but its body changes state outside itself or performs I/O.\",\n yes: \"The body mutates an argument or something reachable through one, assigns to a module-level binding, a field of `this` or an object it did not create, stores something it computed into a cache, Map, Set or other store that outlives the call, logs, emits or increments a metric, or reads or writes a file, network, database, environment, clock or random source, directly or through a call whose name or arguments show it does so (fetch, a path, a URL, a query, send, save). One such read or write on any path is enough.\",\n no: \"The body derives its result from its parameters, from `this`, from module-level values it only reads, and from dependencies it obtains, and returns it. A mutable local accumulator, a copy of an argument that is then modified, and a local object built up and returned are not effects outside the function.\",\n note: \"Obtaining a dependency (a module, a client, a parser handed back by a loader) is not an effect; using an acquired client to fetch, read, write or send is. A body that puts its own result into a cache that outlives the call is an effect even when it is only memoisation.\",\n});\n\nexport const safeNameIsSafe = claimRule({\n id: \"safe-name-is-safe\",\n cutoff: 0.8,\n select: namedLike({\n prefixes: [\"safe\", \"try\"],\n suffixes: [\"OrNull\", \"OrDefault\", \"OrUndefined\"],\n }),\n ask: \"This function's name says that failure is absorbed and reported as a value, but its body has a path on which a failure escapes as a throw or a rejection.\",\n yes: \"A failure of the kind the name promises to absorb can reach the caller as an exception or a rejected promise: the operation that can fail is outside any try, the catch rethrows or throws a new error, a failing case is detected and answered with a throw instead of the null, undefined, default, false or result value the name promises, or the fallback itself is computed by something that can fail.\",\n no: \"Every failure of the kind the name refers to is turned into the value the name promises: null, undefined, a default, a boolean, or a result object the caller can inspect. A body that cannot fail at all, and so has nothing to catch, honours the name.\",\n note: \"A throw on a programmer error, such as an argument of the wrong type, is not the failure such a name promises to absorb. Logging before returning the fallback is fine.\",\n});\n\nexport const idempotentName = claimRule({\n id: \"idempotent-name\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"ensure\", \"upsert\", \"setup\", \"install\", \"register\"] }),\n ask: \"This function's name says a repeated call is harmless, but calling it a second time with the same arguments leaves a different result from calling it once.\",\n yes: \"The body performs its effect without finding out whether it is already in place, and repeating the effect accumulates or fails: it appends to a list or adds a listener, creates a record, index, table, column or resource that would then exist twice or make the second creation fail, inserts where a matching row may already be, or runs a step that is not itself safe to repeat, with no existence check, no keyed overwrite and no guard that makes the second call a no-op.\",\n no: \"A second call finds the effect already in place and leaves the state as the first call left it: the body checks for existence before acting, writes by key so a repeat overwrites the same entry, assigns rather than appends, uses an operation that is inherently repeatable (put, set, mkdir with recursive, CREATE IF NOT EXISTS, ON CONFLICT), returns early on a flag it sets, or has no effect at all beyond its return value.\",\n note: \"A helper whose own name says it is repeat-safe (ensure*, upsert*, put*, set*) is assumed to be. Logging on each call, or returning a fresh object each call, is not a different result.\",\n});\n\nexport const catchHidesFailure = claimRule({\n id: \"catch-hides-failure\",\n cutoff: 0.8,\n select: hasCatch,\n ask: \"A catch block in this function hides a failure the function's caller needed to know about.\",\n yes: \"The catch block neither rethrows, returns an error value the signature admits, nor reports through a channel the function is documented to use; it returns a default, an empty value, a made-up value or nothing, or only logs, and the function's name or return type promises a real result: a value that was fetched, parsed or computed, or an operation such as a save or a send that the caller will assume happened.\",\n no: \"The function has no catch block; or the failure is propagated (rethrown, wrapped, or logged and then rethrown); converted into a value the caller can distinguish from success, such as a Result or null when the return type admits it; or absorbed where absorbing is the point: a cleanup or best-effort step after the real result is in hand, a fallback to the next attempt or source, a catch that swallows only the case in which the goal already holds, or a top-level entry point that reports and exits with a non-zero status. A function named safe*, try* or *OrNull has promised to absorb failure.\",\n});\n\nexport const errorMessageMatchesCondition = claimRule({\n id: \"error-message-matches-condition\",\n cutoff: 0.8,\n ask: \"The message given to an error thrown in this function misdescribes the condition that leads to the throw.\",\n yes: \"The message names a different cause, value, operation or expectation than the condition guarding the throw actually checks: it says a thing is missing when the check is about its permission, form or range; it names one field or operand when the condition tests another; it names one failure (a timeout, an expiry) when the status or state tested is a different one; it states a bound or direction the condition does not test; or it is a copy of another throw's message in the same function and describes that throw's condition rather than this one.\",\n no: \"The function throws nothing with a message; or every message describes the condition that leads to its throw, whether it states the failed requirement, its consequence, or the intent the check serves. A message that is short, generic or lacks detail is not wrong, only unhelpful. A message that quotes the offending input, names what cannot proceed, or wraps a caught error with the name of the operation that failed, is a match.\",\n});\n\nexport const logLevelMatchesEvent = claimRule({\n id: \"log-level-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The level of this log call misstates the severity of what the surrounding code is handling at that point.\",\n yes: \"The call is at info, debug or trace but sits on a path where the operation has failed and the function gives up, rethrows, exits, discards data or returns a failure the caller must act on; the call is at debug or trace for an outcome the function reports to its caller, such as a refusal; the call is at error or fatal but sits on the ordinary success path or on a routine, expected branch such as a cache miss or a validation failure; or the call is at warn but the code immediately exits or throws with no recovery.\",\n no: \"The level fits what the code around the call shows: error or warn where something went wrong that an operator should see, even if the function recovers from it; info for routine outcomes; debug or trace for per-item progress and chatter; warn for a degraded or transient condition the code goes on to handle. Whether the message text is well written is not the question.\",\n});\n\nexport const logMessageMatchesEvent = claimRule({\n id: \"log-message-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The message of this log call misdescribes the event at the point in the code where the call sits.\",\n yes: \"What the message says happened is not what the code path shows at that point: it reports an outcome as done before the operation that produces it runs, or on the branch where that operation failed or was skipped; it names an action (a retry, a deletion, a cache hit, a send) that the path does not perform; it reports a count of what was selected or attempted as the count of what was deleted, sent or written; it interpolates a value that is not what the message calls it; or it names a kind of thing other than the one the surrounding code acts on.\",\n no: \"The message is true of the point where it sits: an intent phrased before the operation, a completion phrased after it, a failure on the branch that fails, a templated message whose values are what it calls them, or a terse message on the path it describes. A message that is vague or could say more is not wrong. Whether the level fits is not the question.\",\n});\n\nexport const commentDescribesBlock = claimRule({\n id: \"comment-describes-block\",\n cutoff: 0.8,\n ask: \"A comment inside this function makes a claim about the code beneath it that the code contradicts.\",\n yes: \"The comment says what the code beneath it does, and the code does something else: a count, limit, number of attempts or delay that differs from the code's; a direction, order, sign, rounding or unit that is not the one the code uses; a condition the code tests the other way round; or a step the comment says happens here that the code beneath it does not perform.\",\n no: \"The function has no comment inside its body; or every specific claim in each comment holds for the code beneath it, meaning the run of statements down to the next comment or the end of the block. A comment that gives a reason outside the code, says what the whole function is for, is vague, or summarises the code loosely but not wrongly, makes no claim the code can contradict. A comment at the end of a line belongs to that line.\",\n});\n\nexport const commentDescribesDeclaration = claimRule({\n id: \"comment-describes-declaration\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The comment directly above this function claims something that is not true of the code.\",\n yes: \"A specific claim the comment makes is contradicted by the code: it names a different operation, direction, rounding, ordering or unit than the code uses, it states a return value or guarantee the code does not provide, it describes a side effect the code does not perform or omits one it does, it gives a count, limit or default that differs from the code's, or it refers to a parameter, field or function that the code no longer has.\",\n no: \"Every specific claim the comment makes holds for the code below it. A comment that is vague, redundant or says less than it could is not a false comment. A section heading or divider names the part of the file that starts there and makes no claim about the function.\",\n note: \"Only a comment that ends on the line just before the function, or just before the export or declaration that holds it, is directly above it; a comment followed by other code belongs to that code. Judge only claims the code can confirm or contradict. A comment about a caller's obligations, about performance, or about history is not checkable here.\",\n});\n\nexport const docErrorsMatchBody = claimRule({\n id: \"doc-errors-match-body\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The failure contract stated in the documentation right above this function (what it says the function throws, rejects with, or returns in place of a result when something goes wrong, and under what condition) is contradicted by the body.\",\n yes: \"The documentation names a failure the body cannot produce: it says the function throws a named error and the body returns null, a default or a success value on that condition instead. Or it names the wrong failure: a different error type or a different condition than the one the body checks before failing. Or the body explicitly fails on its own (a throw, an assert, or a null or default returned in place of a result) under a condition the documentation says nothing about. Or the documentation says the function never throws and the body has a throw.\",\n no: \"The documentation states no failure contract; or every failure the documentation names is one the body produces under the condition named, and every explicit failure the body writes is covered somewhere in the documentation. A failure described at the level of intent is honoured by whatever mechanism the body uses. A fallback the documentation describes, such as a default when a file is absent, is a documented outcome.\",\n note: \"The snippet starts with the documentation directly above the function, and that documentation is what is judged. An error that merely passes through unchanged from a callee is the callee's failure, not a clause this body owes, unless the documentation says the function cannot fail.\",\n});\n\nexport const varNameDescribesValue = claimRule({\n id: \"var-name-describes-value\",\n cutoff: 0.8,\n ask: \"A binding declared in this function has a name that misdescribes the value it is bound to.\",\n yes: \"The name states a type, unit, shape, quantity or meaning that the initializer does not produce: a plural name bound to a single item or a singular name bound to a collection, a name that reads as a boolean bound to something that is not one, a name naming one unit while the value is in another, a name saying it holds a value while it holds a function or a promise, or a name describing a different thing entirely from what the initializer computes.\",\n no: \"Every name is an accurate description of what its initializer produces, even if it is terse or a clearer name could be imagined. Being short or generic is not a mismatch. A plural name on a number names the count of those things; an accumulator, index or buffer name is a convention, not a claim.\",\n});\n\nexport const codeClaims = [\n fnNamePromises,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n varNameDescribesValue,\n] as const satisfies readonly DecisionRule[];\n","import { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport { namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const noPiiInLogs = defineDecisionRule({\n id: \"no-pii-in-logs\",\n target: \"call\",\n question:\n \"Does this call write personal data, such as an email or phone number, to a log or console?\",\n cutoff: 0.8,\n});\n\nexport const noPromptInjection = defineDecisionRule({\n id: \"no-prompt-injection\",\n target: \"function\",\n question:\n \"Does this function build a language model prompt by concatenating untrusted user input into the instructions?\",\n cutoff: 0.8,\n});\n\nexport const noHardcodedSecrets = defineDecisionRule({\n id: \"no-hardcoded-secrets\",\n target: \"file\",\n question:\n \"Does this file contain a hard-coded secret, such as an API key, password, or private token, as a literal value?\",\n cutoff: 0.8,\n});\n\nexport const nameMatchesBehavior = defineDecisionRule({\n id: \"name-matches-behavior\",\n target: \"function\",\n select: namedLike({\n prefixes: [\"get\", \"find\", \"load\", \"fetch\", \"read\", \"lookup\", \"query\", \"list\", \"search\"],\n }),\n question:\n \"Does this function's name describe only reading or fetching data (for example get, find, load or fetch), while its body also changes or announces something on the side, such as writing to a database or file, logging, or sending a message? Sending the request that fetches the data, such as calling an API or a model and reading its answer, is the fetching itself and does not count.\",\n cutoff: 0.8,\n});\n\nexport const untrustedInputRisk = defineDecisionRule({\n id: \"untrusted-input-risk\",\n target: \"function\",\n question:\n \"Does this function splice untrusted input, such as a user message or request parameter, into the same string as a SQL query, shell command, eval code, HTML, or language model instructions, instead of passing it as a separate parameter or field? Count input as untrusted only when it comes from outside the program, such as a request, a user message, a form, or a file or response the program does not control; a parameter whose origin is not shown counts when its name or type marks it as user or request data. Text taken from the program's own rule definitions, settings, constants or cache is not untrusted, and JSON.parse is not eval.\",\n cutoff: 0.8,\n answer: { kind: \"severity\", minimum: \"warn\" },\n});\n\nexport const domainNaming = defineDecisionRule({\n id: \"domain-naming\",\n target: \"function\",\n question:\n \"Is this function named after a mechanism word such as Manager, Processor, Handler, Helper, Data, Info, handle, process, or do, while its body works on one specific business concept, such as an invoice, an order, or a refund, that the name should call by its domain name instead? Code whose subject is a generic mechanism, such as HTTP, files, the command line, or framework glue, does not count.\",\n cutoff: 0.8,\n});\n\nexport const preferSchemaValidation = defineDecisionRule({\n id: \"prefer-schema-validation\",\n target: \"function\",\n question:\n \"Does this function check the shape or values of untyped data, such as parsed JSON, a request body, config, or an API response, with a long hand-written chain of typeof, instanceof, in, or field checks joined by && or ||, where a schema from a validation library would state the same rules more simply? A single simple check does not count.\",\n cutoff: 0.8,\n});\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport { claimRule } from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { isDescribeCall, isTestCall } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const describeNamesSubject = claimRule({\n id: \"describe-names-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isDescribeCall,\n ask: \"The tests inside this describe block exercise something other than what its title names.\",\n yes: \"The title names a specific function, method, class or module and no test in the block calls, constructs or otherwise reaches it: every test calls a differently named sibling instead; or the title names a behaviour and no test makes that behaviour happen or observes it.\",\n no: \"What the title names is what the tests exercise, directly or through something that reaches it: a feature tested through a public function of another name, a class tested through its factory or an instance created in beforeEach, a title that is a file name, a scenario or a sentence when the tests are about it, or an abbreviation or synonym of what the tests call.\",\n});\n\nexport const testNameDescribesCode = claimRule({\n id: \"test-name-describes-code\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The operation, input or outcome this test exercises is not the one the test's name names.\",\n yes: \"The operation the code calls is not the one the name says; the input or case the code sets up is not the one the name states (three units where the name says above ten); the outcome the code expects is the opposite of the one the name implies; the name promises a throw or a rejection where the code expects an ordinary value; or the name refers to something that the code never calls and never checks.\",\n no: \"The code calls the operation the name says, on the input the name says, and expects the kind of outcome the name says, however weak the assertion is. A one-word title, a synonym for the operation's name, and setup that calls other operations before the named one are all fine.\",\n});\n\nexport const testNameVerifiesClaim = claimRule({\n id: \"test-name-verifies-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test would still pass if the behaviour its name claims were broken.\",\n yes: \"The body does not establish what the name claims: it asserts nothing at all, it asserts something that would hold whether or not the named behaviour worked, it checks an incidental property such as a length or a type instead of the named behaviour itself, or it never sets up the case the name is about.\",\n no: \"The body contains at least one assertion that would fail if the named behaviour were broken. A name that claims only that something renders or matches a snapshot is established by the snapshot; a name that claims an interaction with a collaborator is established by an assertion on that call; a name that claims only that something does not throw is established by calling it.\",\n});\n\nexport const snapshotOnlyBehaviourClaim = claimRule({\n id: \"snapshot-only-behaviour-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test's name claims a specific behaviour, but the body only compares a snapshot.\",\n yes: \"The title asserts a property of the output (an ordering, an element hidden or shown, a state rendered under a condition, a format applied) and the only assertions are toMatchSnapshot, toMatchInlineSnapshot or toMatchFileSnapshot over a whole rendering, so nothing isolates the named property.\",\n no: \"The body uses no snapshot; or the title claims only that the output matches a snapshot or renders, or only names the input; or at least one assertion targets the named behaviour directly; or the inline snapshot is a short literal that is itself the named outcome.\",\n});\n\nexport const testMocksSubject = claimRule({\n id: \"test-mocks-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The behaviour this test's name attributes to the code under test is performed by a mock or stub whose canned value the assertion reads back unchanged.\",\n yes: \"The title says the code under test computes, derives or returns something, but the function or module that would do it is replaced (vi.mock or jest.mock with a fake, mockReturnValue or mockResolvedValue, a stubbed global) and the value the assertion checks can be traced to that stub's configuration with none of the subject's own logic in between. The assertion then checks the test's own setup.\",\n no: \"The body mocks nothing; or the stub stands in for a collaborator the code under test calls (the network, the clock, a repository, a mailer) and the assertion checks what the real code did with the stub's output; or the title is itself about the collaborator; or the spy has no replacement value and the real method runs.\",\n});\n\nexport const testClaims = [\n describeNamesSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n] as const satisfies readonly DecisionRule[];\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\n\nimport {\n catchHidesFailure,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n fnNamePromises,\n idempotentName,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n pureNameIsPure,\n safeNameIsSafe,\n varNameDescribesValue,\n} from \"./code-claims.ts\";\nimport {\n domainNaming,\n nameMatchesBehavior,\n noHardcodedSecrets,\n noPiiInLogs,\n noPromptInjection,\n preferSchemaValidation,\n untrustedInputRisk,\n} from \"./rules.ts\";\nimport {\n describeNamesSubject,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n} from \"./test-claims.ts\";\n\nexport type Preset = readonly [DecisionRule, ...DecisionRule[]];\n\nexport const recommended: Preset = [noPiiInLogs, noPromptInjection, noHardcodedSecrets];\n\nexport const strict: Preset = [\n ...recommended,\n nameMatchesBehavior,\n untrustedInputRisk,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n testNameVerifiesClaim,\n testMocksSubject,\n];\n\nexport const reviewOnly: Preset = [\n domainNaming,\n preferSchemaValidation,\n fnNamePromises,\n commentDescribesDeclaration,\n commentDescribesBlock,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n varNameDescribesValue,\n describeNamesSubject,\n testNameDescribesCode,\n snapshotOnlyBehaviourClaim,\n];\n\nexport const presets = { recommended, strict, reviewOnly } as const satisfies Readonly<\n Record<string, Preset>\n>;\n","import { createDecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\nimport type { DecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\n\nimport type { Preset } from \"#/features/define-presets/index.ts\";\n\nconst PLUGIN_NAME = \"decision-presets\";\n\nexport const presetPlugin =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;CAAC;CAAa;CAAmB;AAAkB;AAEtF,MAAa,SAAiB;CAC5B,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,aAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,UAAU;CAAE;CAAa;CAAQ;AAAW;;AC5DzD,MAAM,cAAc;AAEpB,MAAa,gBAAgB,UAC3B,qBAAqB;CAAE,MAAM;CAAa;AAAM,CAAC"}
|
|
1
|
+
{"version":3,"file":"preset-plugin-miAjemLS.mjs","names":["Str","Arr"],"sources":["../src/features/define-presets/lib/claim-select.ts","../src/features/define-presets/model/code-claims.ts","../src/features/define-presets/model/rules.ts","../src/features/define-presets/model/test-claims.ts","../src/features/define-presets/model/presets.ts","../src/app/preset-plugin.ts"],"sourcesContent":["import { Array as Arr, Match, Option, Predicate, String as Str, pipe } from \"effect\";\n\nimport type { SelectedNode } from \"#/entities/decision/index.ts\";\n\nimport { containing, dualSelect, identifierOf, ofType } from \"./select.ts\";\nimport type { DualSelect, NodeTest, Select } from \"./select.ts\";\n\nconst WORD_STARTS: ReadonlySet<string> = new Set([\n \"\",\n ...Str.split(\"_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"\"),\n]);\n\nconst NEXT_CHARACTER = 1;\n\nconst startsWithWord =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Predicate.and(\n (text: string) => Str.startsWith(word)(text),\n (text: string) => WORD_STARTS.has(Str.slice(word.length, word.length + NEXT_CHARACTER)(text)),\n )(name);\n\nconst endsWith =\n (word: string): Predicate.Predicate<string> =>\n (name) =>\n Str.endsWith(word)(name);\n\nexport interface NameWords {\n readonly prefixes: readonly string[];\n readonly suffixes?: readonly string[];\n}\n\nexport const namedLike = ({ prefixes, suffixes = [] }: NameWords): Select => {\n const matchers = [\n ...pipe(\n prefixes,\n Arr.map((word) => startsWithWord(word)),\n ),\n ...pipe(\n suffixes,\n Arr.map((word) => endsWith(word)),\n ),\n ];\n return (_node, { name }) =>\n Option.exists(Option.fromUndefinedOr(name), (found) =>\n pipe(\n matchers,\n Arr.some((matches) => matches(found)),\n ),\n );\n};\n\nconst rootOf = (callee: SelectedNode): Option.Option<string> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) => rootOf(member.object)),\n Match.orElse(identifierOf),\n );\n\nconst calleeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) => Option.some(call.callee)),\n Match.orElse(() => Option.none()),\n );\n\nconst callingAny =\n (roots: readonly string[]): Select =>\n (node) =>\n Option.exists(Option.flatMap(calleeOf(node), rootOf), (root) => roots.includes(root));\n\nconst LOG_LEVELS: ReadonlySet<string> = new Set([\n \"trace\",\n \"debug\",\n \"verbose\",\n \"info\",\n \"log\",\n \"warn\",\n \"warning\",\n \"error\",\n \"fatal\",\n]);\n\nconst lastNameOf = (node: SelectedNode): Option.Option<string> =>\n Match.value(node).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n identifierOf(member.property),\n ),\n Match.orElse(identifierOf),\n );\n\nconst isLogger = (name: string): boolean =>\n Arr.some([\"console\", \"log\"], (word) => Str.includes(word)(Str.toLowerCase(name)));\n\ninterface LogCall {\n readonly level: Option.Option<string>;\n readonly logger: Option.Option<string>;\n}\n\nconst logCallOf = (callee: SelectedNode): Option.Option<LogCall> =>\n Match.value(callee).pipe(\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n Option.some({ level: identifierOf(member.property), logger: lastNameOf(member.object) }),\n ),\n Match.orElse(() => Option.none()),\n );\n\nexport const isLogCall: DualSelect = dualSelect((node) =>\n Option.exists(Option.flatMap(calleeOf(node), logCallOf), ({ level, logger }) =>\n Predicate.and(\n () => Option.exists(level, (found) => LOG_LEVELS.has(found)),\n () => Option.exists(logger, isLogger),\n )(node),\n ),\n);\n\nconst isCatchName = (name: SelectedNode): boolean =>\n Match.value(name).pipe(\n Match.when({ type: \"Identifier\" }, (identifier) => Str.startsWith(\"catch\")(identifier.name)),\n Match.orElse(() => false),\n );\n\nconst isCatch: NodeTest = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CatchClause\" }, () => true),\n Match.when({ type: \"MemberExpression\", computed: false }, (member) =>\n isCatchName(member.property),\n ),\n Match.when({ type: \"Property\", computed: false }, (property) => isCatchName(property.key)),\n Match.orElse(() => false),\n );\n\nexport const hasCatch: DualSelect = dualSelect(containing(isCatch));\n\nconst hasCallbackArgument: Select = (node) =>\n Match.value(node).pipe(\n Match.when({ type: \"CallExpression\" }, (call) =>\n pipe(\n call.arguments,\n Arr.some((argument) => ofType(\"ArrowFunctionExpression\", \"FunctionExpression\")(argument)),\n ),\n ),\n Match.orElse(() => false),\n );\n\nexport const isTestCall: DualSelect = dualSelect((node, match) =>\n pipe(\n [callingAny([\"it\", \"test\"]), hasCallbackArgument],\n Arr.every((select) => select(node, match)),\n ),\n);\n\nexport const isDescribeCall: DualSelect = dualSelect(callingAny([\"describe\"]));\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport {\n COMMENT,\n ENCLOSING_FUNCTION,\n claimRule,\n} from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { hasCatch, isLogCall, namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const fnNamePromises = claimRule({\n id: \"fn-name-promises\",\n cutoff: 0.8,\n ask: \"The body of this function does something materially different from what its name promises.\",\n yes: \"Someone who read only the name and the parameter list would be wrong about what this function does: it returns a different kind of thing than the name suggests (a count that is a list, a predicate that is a number), it changes state when the name says it only reads, checks, looks up or serialises, it can fail or return nothing when the name promises a value, it handles only a narrower case than the name claims, it never performs an effect or repetition the name names (a drain or remove that leaves the container as it was, a retry that tries once), it computes something no reading of the name accounts for, or it does substantial work the name does not mention at all, such as writing what it was asked to read.\",\n no: \"The name and parameter list describe what the body actually does. Someone who read only them would not be surprised by the body, even if a longer or more specific name could be imagined. A terse or conventional name (run, handle, take, len, fmt, toString, a getter) that the body fits is not a violation, and a comment inside the body that is wrong about the body is a wrong comment, not a wrong name.\",\n});\n\nexport const pureNameIsPure = claimRule({\n id: \"pure-name-is-pure\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"compute\", \"calculate\", \"derive\", \"format\", \"to\", \"parse\"] }),\n ask: \"This function's name presents it as a computation of a result from its inputs, but its body changes state outside itself or performs I/O.\",\n yes: \"The body mutates an argument or something reachable through one, assigns to a module-level binding, a field of `this` or an object it did not create, stores something it computed into a cache, Map, Set or other store that outlives the call, logs, emits or increments a metric, or reads or writes a file, network, database, environment, clock or random source, directly or through a call whose name or arguments show it does so (fetch, a path, a URL, a query, send, save). One such read or write on any path is enough.\",\n no: \"The body derives its result from its parameters, from `this`, from module-level values it only reads, and from dependencies it obtains, and returns it. A mutable local accumulator, a copy of an argument that is then modified, and a local object built up and returned are not effects outside the function.\",\n note: \"Obtaining a dependency (a module, a client, a parser handed back by a loader) is not an effect; using an acquired client to fetch, read, write or send is. A body that puts its own result into a cache that outlives the call is an effect even when it is only memoisation.\",\n});\n\nexport const safeNameIsSafe = claimRule({\n id: \"safe-name-is-safe\",\n cutoff: 0.8,\n select: namedLike({\n prefixes: [\"safe\", \"try\"],\n suffixes: [\"OrNull\", \"OrDefault\", \"OrUndefined\"],\n }),\n ask: \"This function's name says that failure is absorbed and reported as a value, but its body has a path on which a failure escapes as a throw or a rejection.\",\n yes: \"A failure of the kind the name promises to absorb can reach the caller as an exception or a rejected promise: the operation that can fail is outside any try, the catch rethrows or throws a new error, a failing case is detected and answered with a throw instead of the null, undefined, default, false or result value the name promises, or the fallback itself is computed by something that can fail.\",\n no: \"Every failure of the kind the name refers to is turned into the value the name promises: null, undefined, a default, a boolean, or a result object the caller can inspect. A body that cannot fail at all, and so has nothing to catch, honours the name.\",\n note: \"A throw on a programmer error, such as an argument of the wrong type, is not the failure such a name promises to absorb. Logging before returning the fallback is fine.\",\n});\n\nexport const idempotentName = claimRule({\n id: \"idempotent-name\",\n cutoff: 0.8,\n select: namedLike({ prefixes: [\"ensure\", \"upsert\", \"setup\", \"install\", \"register\"] }),\n ask: \"This function's name says a repeated call is harmless, but calling it a second time with the same arguments leaves a different result from calling it once.\",\n yes: \"The body performs its effect without finding out whether it is already in place, and repeating the effect accumulates or fails: it appends to a list or adds a listener, creates a record, index, table, column or resource that would then exist twice or make the second creation fail, inserts where a matching row may already be, or runs a step that is not itself safe to repeat, with no existence check, no keyed overwrite and no guard that makes the second call a no-op.\",\n no: \"A second call finds the effect already in place and leaves the state as the first call left it: the body checks for existence before acting, writes by key so a repeat overwrites the same entry, assigns rather than appends, uses an operation that is inherently repeatable (put, set, mkdir with recursive, CREATE IF NOT EXISTS, ON CONFLICT), returns early on a flag it sets, or has no effect at all beyond its return value.\",\n note: \"A helper whose own name says it is repeat-safe (ensure*, upsert*, put*, set*) is assumed to be. Logging on each call, or returning a fresh object each call, is not a different result.\",\n});\n\nexport const catchHidesFailure = claimRule({\n id: \"catch-hides-failure\",\n cutoff: 0.8,\n select: hasCatch,\n ask: \"A catch block in this function hides a failure the function's caller needed to know about.\",\n yes: \"The catch block neither rethrows, returns an error value the signature admits, nor reports through a channel the function is documented to use; it returns a default, an empty value, a made-up value or nothing, or only logs, and the function's name or return type promises a real result: a value that was fetched, parsed or computed, or an operation such as a save or a send that the caller will assume happened.\",\n no: \"The function has no catch block; or the failure is propagated (rethrown, wrapped, or logged and then rethrown); converted into a value the caller can distinguish from success, such as a Result or null when the return type admits it; or absorbed where absorbing is the point: a cleanup or best-effort step after the real result is in hand, a fallback to the next attempt or source, a catch that swallows only the case in which the goal already holds, or a top-level entry point that reports and exits with a non-zero status. A function named safe*, try* or *OrNull has promised to absorb failure.\",\n});\n\nexport const errorMessageMatchesCondition = claimRule({\n id: \"error-message-matches-condition\",\n cutoff: 0.8,\n ask: \"The message given to an error thrown in this function misdescribes the condition that leads to the throw.\",\n yes: \"The message names a different cause, value, operation or expectation than the condition guarding the throw actually checks: it says a thing is missing when the check is about its permission, form or range; it names one field or operand when the condition tests another; it names one failure (a timeout, an expiry) when the status or state tested is a different one; it states a bound or direction the condition does not test; or it is a copy of another throw's message in the same function and describes that throw's condition rather than this one.\",\n no: \"The function throws nothing with a message; or every message describes the condition that leads to its throw, whether it states the failed requirement, its consequence, or the intent the check serves. A message that is short, generic or lacks detail is not wrong, only unhelpful. A message that quotes the offending input, names what cannot proceed, or wraps a caught error with the name of the operation that failed, is a match.\",\n});\n\nexport const logLevelMatchesEvent = claimRule({\n id: \"log-level-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The level of this log call misstates the severity of what the surrounding code is handling at that point.\",\n yes: \"The call is at info, debug or trace but sits on a path where the operation has failed and the function gives up, rethrows, exits, discards data or returns a failure the caller must act on; the call is at debug or trace for an outcome the function reports to its caller, such as a refusal; the call is at error or fatal but sits on the ordinary success path or on a routine, expected branch such as a cache miss or a validation failure; or the call is at warn but the code immediately exits or throws with no recovery.\",\n no: \"The level fits what the code around the call shows: error or warn where something went wrong that an operator should see, even if the function recovers from it; info for routine outcomes; debug or trace for per-item progress and chatter; warn for a degraded or transient condition the code goes on to handle. Whether the message text is well written is not the question.\",\n});\n\nexport const logMessageMatchesEvent = claimRule({\n id: \"log-message-matches-event\",\n target: \"call\",\n cutoff: 0.8,\n select: isLogCall,\n context: ENCLOSING_FUNCTION,\n ask: \"The message of this log call misdescribes the event at the point in the code where the call sits.\",\n yes: \"What the message says happened is not what the code path shows at that point: it reports an outcome as done before the operation that produces it runs, or on the branch where that operation failed or was skipped; it names an action (a retry, a deletion, a cache hit, a send) that the path does not perform; it reports a count of what was selected or attempted as the count of what was deleted, sent or written; it interpolates a value that is not what the message calls it; or it names a kind of thing other than the one the surrounding code acts on.\",\n no: \"The message is true of the point where it sits: an intent phrased before the operation, a completion phrased after it, a failure on the branch that fails, a templated message whose values are what it calls them, or a terse message on the path it describes. A message that is vague or could say more is not wrong. Whether the level fits is not the question.\",\n});\n\nexport const commentDescribesBlock = claimRule({\n id: \"comment-describes-block\",\n cutoff: 0.8,\n ask: \"A comment inside this function makes a claim about the code beneath it that the code contradicts.\",\n yes: \"The comment says what the code beneath it does, and the code does something else: a count, limit, number of attempts or delay that differs from the code's; a direction, order, sign, rounding or unit that is not the one the code uses; a condition the code tests the other way round; or a step the comment says happens here that the code beneath it does not perform.\",\n no: \"The function has no comment inside its body; or every specific claim in each comment holds for the code beneath it, meaning the run of statements down to the next comment or the end of the block. A comment that gives a reason outside the code, says what the whole function is for, is vague, or summarises the code loosely but not wrongly, makes no claim the code can contradict. A comment at the end of a line belongs to that line.\",\n});\n\nexport const commentDescribesDeclaration = claimRule({\n id: \"comment-describes-declaration\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The comment directly above this function claims something that is not true of the code.\",\n yes: \"A specific claim the comment makes is contradicted by the code: it names a different operation, direction, rounding, ordering or unit than the code uses, it states a return value or guarantee the code does not provide, it describes a side effect the code does not perform or omits one it does, it gives a count, limit or default that differs from the code's, or it refers to a parameter, field or function that the code no longer has.\",\n no: \"Every specific claim the comment makes holds for the code below it. A comment that is vague, redundant or says less than it could is not a false comment. A section heading or divider names the part of the file that starts there and makes no claim about the function.\",\n note: \"Only a comment that ends on the line just before the function, or just before the export or declaration that holds it, is directly above it; a comment followed by other code belongs to that code. Judge only claims the code can confirm or contradict. A comment about a caller's obligations, about performance, or about history is not checkable here.\",\n});\n\nexport const docErrorsMatchBody = claimRule({\n id: \"doc-errors-match-body\",\n cutoff: 0.8,\n context: COMMENT,\n ask: \"The failure contract stated in the documentation right above this function (what it says the function throws, rejects with, or returns in place of a result when something goes wrong, and under what condition) is contradicted by the body.\",\n yes: \"The documentation names a failure the body cannot produce: it says the function throws a named error and the body returns null, a default or a success value on that condition instead. Or it names the wrong failure: a different error type or a different condition than the one the body checks before failing. Or the body explicitly fails on its own (a throw, an assert, or a null or default returned in place of a result) under a condition the documentation says nothing about. Or the documentation says the function never throws and the body has a throw.\",\n no: \"The documentation states no failure contract; or every failure the documentation names is one the body produces under the condition named, and every explicit failure the body writes is covered somewhere in the documentation. A failure described at the level of intent is honoured by whatever mechanism the body uses. A fallback the documentation describes, such as a default when a file is absent, is a documented outcome.\",\n note: \"The snippet starts with the documentation directly above the function, and that documentation is what is judged. An error that merely passes through unchanged from a callee is the callee's failure, not a clause this body owes, unless the documentation says the function cannot fail.\",\n});\n\nexport const varNameDescribesValue = claimRule({\n id: \"var-name-describes-value\",\n cutoff: 0.8,\n ask: \"A binding declared in this function has a name that misdescribes the value it is bound to.\",\n yes: \"The name states a type, unit, shape, quantity or meaning that the initializer does not produce: a plural name bound to a single item or a singular name bound to a collection, a name that reads as a boolean bound to something that is not one, a name naming one unit while the value is in another, a name saying it holds a value while it holds a function or a promise, or a name describing a different thing entirely from what the initializer computes.\",\n no: \"Every name is an accurate description of what its initializer produces, even if it is terse or a clearer name could be imagined. Being short or generic is not a mismatch. A plural name on a number names the count of those things; an accumulator, index or buffer name is a convention, not a claim.\",\n});\n\nexport const codeClaims = [\n fnNamePromises,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n varNameDescribesValue,\n] as const satisfies readonly DecisionRule[];\n","import { defineDecisionRule } from \"#/entities/decision/index.ts\";\nimport { namedLike } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const noPiiInLogs = defineDecisionRule({\n id: \"no-pii-in-logs\",\n target: \"call\",\n question:\n \"Does this call write personal data, such as an email or phone number, to a log or console?\",\n cutoff: 0.8,\n});\n\nexport const noPromptInjection = defineDecisionRule({\n id: \"no-prompt-injection\",\n target: \"function\",\n question:\n \"Does this function build a language model prompt by concatenating untrusted user input into the instructions?\",\n cutoff: 0.8,\n});\n\nexport const noHardcodedSecrets = defineDecisionRule({\n id: \"no-hardcoded-secrets\",\n target: \"file\",\n question:\n \"Does this file contain a hard-coded secret, such as an API key, password, or private token, as a literal value?\",\n cutoff: 0.8,\n});\n\nexport const nameMatchesBehavior = defineDecisionRule({\n id: \"name-matches-behavior\",\n target: \"function\",\n select: namedLike({\n prefixes: [\"get\", \"find\", \"load\", \"fetch\", \"read\", \"lookup\", \"query\", \"list\", \"search\"],\n }),\n question:\n \"Does this function's name describe only reading or fetching data (for example get, find, load or fetch), while its body also changes or announces something on the side, such as writing to a database or file, logging, or sending a message? Sending the request that fetches the data, such as calling an API or a model and reading its answer, is the fetching itself and does not count.\",\n cutoff: 0.8,\n});\n\nexport const untrustedInputRisk = defineDecisionRule({\n id: \"untrusted-input-risk\",\n target: \"function\",\n question:\n \"Does this function splice untrusted input, such as a user message or request parameter, into the same string as a SQL query, shell command, eval code, HTML, or language model instructions, instead of passing it as a separate parameter or field? Count input as untrusted only when it comes from outside the program, such as a request, a user message, a form, or a file or response the program does not control; a parameter whose origin is not shown counts when its name or type marks it as user or request data. Text taken from the program's own rule definitions, settings, constants or cache is not untrusted, and JSON.parse is not eval.\",\n cutoff: 0.8,\n answer: { kind: \"severity\", minimum: \"warn\" },\n});\n\nexport const domainNaming = defineDecisionRule({\n id: \"domain-naming\",\n target: \"function\",\n question:\n \"Is this function named after a mechanism word such as Manager, Processor, Handler, Helper, Data, Info, handle, process, or do, while its body works on one specific business concept, such as an invoice, an order, or a refund, that the name should call by its domain name instead? Code whose subject is a generic mechanism, such as HTTP, files, the command line, or framework glue, does not count.\",\n cutoff: 0.8,\n});\n\nexport const preferSchemaValidation = defineDecisionRule({\n id: \"prefer-schema-validation\",\n target: \"function\",\n question:\n \"Does this function check the shape or values of untyped data, such as parsed JSON, a request body, config, or an API response, with a long hand-written chain of typeof, instanceof, in, or field checks joined by && or ||, where a schema from a validation library would state the same rules more simply? A single simple check does not count.\",\n cutoff: 0.8,\n});\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\nimport { claimRule } from \"#/features/define-presets/lib/claim-rule.ts\";\nimport { isDescribeCall, isTestCall } from \"#/features/define-presets/lib/claim-select.ts\";\n\nexport const describeNamesSubject = claimRule({\n id: \"describe-names-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isDescribeCall,\n ask: \"The tests inside this describe block exercise something other than what its title names.\",\n yes: \"The title names a specific function, method, class or module and no test in the block calls, constructs or otherwise reaches it: every test calls a differently named sibling instead; or the title names a behaviour and no test makes that behaviour happen or observes it.\",\n no: \"What the title names is what the tests exercise, directly or through something that reaches it: a feature tested through a public function of another name, a class tested through its factory or an instance created in beforeEach, a title that is a file name, a scenario or a sentence when the tests are about it, or an abbreviation or synonym of what the tests call.\",\n});\n\nexport const testNameDescribesCode = claimRule({\n id: \"test-name-describes-code\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The operation, input or outcome this test exercises is not the one the test's name names.\",\n yes: \"The operation the code calls is not the one the name says; the input or case the code sets up is not the one the name states (three units where the name says above ten); the outcome the code expects is the opposite of the one the name implies; the name promises a throw or a rejection where the code expects an ordinary value; or the name refers to something that the code never calls and never checks.\",\n no: \"The code calls the operation the name says, on the input the name says, and expects the kind of outcome the name says, however weak the assertion is. A one-word title, a synonym for the operation's name, and setup that calls other operations before the named one are all fine.\",\n});\n\nexport const testNameVerifiesClaim = claimRule({\n id: \"test-name-verifies-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test would still pass if the behaviour its name claims were broken.\",\n yes: \"The body does not establish what the name claims: it asserts nothing at all, it asserts something that would hold whether or not the named behaviour worked, it checks an incidental property such as a length or a type instead of the named behaviour itself, or it never sets up the case the name is about.\",\n no: \"The body contains at least one assertion that would fail if the named behaviour were broken. A name that claims only that something renders or matches a snapshot is established by the snapshot; a name that claims an interaction with a collaborator is established by an assertion on that call; a name that claims only that something does not throw is established by calling it.\",\n});\n\nexport const snapshotOnlyBehaviourClaim = claimRule({\n id: \"snapshot-only-behaviour-claim\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"This test's name claims a specific behaviour, but the body only compares a snapshot.\",\n yes: \"The title asserts a property of the output (an ordering, an element hidden or shown, a state rendered under a condition, a format applied) and the only assertions are toMatchSnapshot, toMatchInlineSnapshot or toMatchFileSnapshot over a whole rendering, so nothing isolates the named property.\",\n no: \"The body uses no snapshot; or the title claims only that the output matches a snapshot or renders, or only names the input; or at least one assertion targets the named behaviour directly; or the inline snapshot is a short literal that is itself the named outcome.\",\n});\n\nexport const testMocksSubject = claimRule({\n id: \"test-mocks-subject\",\n cutoff: 0.8,\n target: \"call\",\n select: isTestCall,\n ask: \"The behaviour this test's name attributes to the code under test is performed by a mock or stub whose canned value the assertion reads back unchanged.\",\n yes: \"The title says the code under test computes, derives or returns something, but the function or module that would do it is replaced (vi.mock or jest.mock with a fake, mockReturnValue or mockResolvedValue, a stubbed global) and the value the assertion checks can be traced to that stub's configuration with none of the subject's own logic in between. The assertion then checks the test's own setup.\",\n no: \"The body mocks nothing; or the stub stands in for a collaborator the code under test calls (the network, the clock, a repository, a mailer) and the assertion checks what the real code did with the stub's output; or the title is itself about the collaborator; or the spy has no replacement value and the real method runs.\",\n});\n\nexport const testClaims = [\n describeNamesSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n] as const satisfies readonly DecisionRule[];\n","import type { DecisionRule } from \"#/entities/decision/index.ts\";\n\nimport {\n catchHidesFailure,\n commentDescribesBlock,\n commentDescribesDeclaration,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n fnNamePromises,\n idempotentName,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n pureNameIsPure,\n safeNameIsSafe,\n varNameDescribesValue,\n} from \"./code-claims.ts\";\nimport {\n domainNaming,\n nameMatchesBehavior,\n noHardcodedSecrets,\n noPiiInLogs,\n noPromptInjection,\n preferSchemaValidation,\n untrustedInputRisk,\n} from \"./rules.ts\";\nimport {\n describeNamesSubject,\n snapshotOnlyBehaviourClaim,\n testMocksSubject,\n testNameDescribesCode,\n testNameVerifiesClaim,\n} from \"./test-claims.ts\";\n\nexport type Preset = readonly [DecisionRule, ...DecisionRule[]];\n\nexport const recommended: Preset = [noPiiInLogs, noPromptInjection, noHardcodedSecrets];\n\nexport const strict: Preset = [\n ...recommended,\n nameMatchesBehavior,\n untrustedInputRisk,\n pureNameIsPure,\n safeNameIsSafe,\n idempotentName,\n catchHidesFailure,\n testNameVerifiesClaim,\n testMocksSubject,\n];\n\nexport const reviewOnly: Preset = [\n domainNaming,\n preferSchemaValidation,\n fnNamePromises,\n commentDescribesDeclaration,\n commentDescribesBlock,\n docErrorsMatchBody,\n errorMessageMatchesCondition,\n logLevelMatchesEvent,\n logMessageMatchesEvent,\n varNameDescribesValue,\n describeNamesSubject,\n testNameDescribesCode,\n snapshotOnlyBehaviourClaim,\n];\n\nexport const presets = { recommended, strict, reviewOnly } as const satisfies Readonly<\n Record<string, Preset>\n>;\n","import { createDecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\nimport type { DecisionPlugin } from \"@r_masseater/oxlint-plugin-decision\";\n\nimport type { Preset } from \"#/features/define-presets/index.ts\";\n\nconst PLUGIN_NAME = \"decision-presets\";\n\nexport const presetPlugin = (rules: Preset): DecisionPlugin =>\n createDecisionPlugin({ name: PLUGIN_NAME, rules });\n"],"mappings":";;;;AAOA,MAAM,8BAAmC,IAAI,IAAI,CAC/C,IACA,GAAGA,OAAI,MAAM,yCAAyC,EAAE,CAC1D,CAAC;AAED,MAAM,iBAAiB;AAEvB,MAAM,kBACH,UACA,SACC,UAAU,KACP,SAAiBA,OAAI,WAAW,IAAI,CAAC,CAAC,IAAI,IAC1C,SAAiB,YAAY,IAAIA,OAAI,MAAM,KAAK,QAAQ,KAAK,SAAS,cAAc,CAAC,CAAC,IAAI,CAAC,CAC9F,CAAC,CAAC,IAAI;AAEV,MAAM,YACH,UACA,SACCA,OAAI,SAAS,IAAI,CAAC,CAAC,IAAI;AA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,UACE;CACF,QAAQ;AACV,CAAC;AAED,MAAa,yBAAyB,mBAAmB;CACvD,IAAI;CACJ,QAAQ;CACR,UACE;CACF,QAAQ;AACV,CAAC;;ACzDD,MAAa,uBAAuB,UAAU;CAC5C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,wBAAwB,UAAU;CAC7C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,wBAAwB,UAAU;CAC7C,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,6BAA6B,UAAU;CAClD,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,mBAAmB,UAAU;CACxC,IAAI;CACJ,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,KAAK;CACL,KAAK;CACL,IAAI;AACN,CAAC;AAED,MAAa,aAAa;CACxB;CACA;CACA;CACA;CACA;AACF;;ACzBA,MAAa,cAAsB;CAAC;CAAa;CAAmB;AAAkB;AAEtF,MAAa,SAAiB;CAC5B,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,aAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,UAAU;CAAE;CAAa;CAAQ;AAAW;;AC5DzD,MAAM,cAAc;AAEpB,MAAa,gBAAgB,UAC3B,qBAAqB;CAAE,MAAM;CAAa;AAAM,CAAC"}
|
package/dist/presets/ai-slop.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as createDecisionPlugin } from "../app-
|
|
2
|
-
import { a as dualSelect, i as containing, o as identifierOf, r as claimRule, s as ofType } from "../claim-rule-
|
|
1
|
+
import { t as createDecisionPlugin } from "../app-1jZ4qJYY.mjs";
|
|
2
|
+
import { a as dualSelect, i as containing, o as identifierOf, r as claimRule, s as ofType } from "../claim-rule-Dzu69Utl.mjs";
|
|
3
3
|
import { Array, Match, Option, Predicate, String, pipe } from "effect";
|
|
4
4
|
// src/features/define-presets/lib/ai-slop-select.ts
|
|
5
5
|
const isPlaceholderValue = ofType("Literal", "TemplateLiteral", "ArrayExpression", "ObjectExpression");
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as recommended, t as presetPlugin } from "../preset-plugin-
|
|
1
|
+
import { r as recommended, t as presetPlugin } from "../preset-plugin-miAjemLS.mjs";
|
|
2
2
|
// src/app/recommended.ts
|
|
3
3
|
const plugin = presetPlugin(recommended);
|
|
4
4
|
export { plugin as default };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as reviewOnly, t as presetPlugin } from "../preset-plugin-
|
|
1
|
+
import { i as reviewOnly, t as presetPlugin } from "../preset-plugin-miAjemLS.mjs";
|
|
2
2
|
// src/app/review-only.ts
|
|
3
3
|
const plugin = presetPlugin(reviewOnly);
|
|
4
4
|
export { plugin as default };
|
package/dist/presets/strict.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import plugin from "./recommended.mjs";
|
|
2
|
-
import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as reviewOnly, a as testNameDescribesCode, b as codeClaims, c as nameMatchesBehavior, d as noPromptInjection, f as preferSchemaValidation, g as recommended, h as presets, i as testMocksSubject, j as varNameDescribesValue, k as pureNameIsPure, l as noHardcodedSecrets, m as Preset, n as snapshotOnlyBehaviourClaim, o as testNameVerifiesClaim, p as untrustedInputRisk, r as testClaims, s as domainNaming, t as describeNamesSubject, u as noPiiInLogs, v as strict, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "
|
|
1
|
+
import plugin from "./presets/recommended.mjs";
|
|
2
|
+
import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as reviewOnly, a as testNameDescribesCode, b as codeClaims, c as nameMatchesBehavior, d as noPromptInjection, f as preferSchemaValidation, g as recommended, h as presets, i as testMocksSubject, j as varNameDescribesValue, k as pureNameIsPure, l as noHardcodedSecrets, m as Preset, n as snapshotOnlyBehaviourClaim, o as testNameVerifiesClaim, p as untrustedInputRisk, r as testClaims, s as domainNaming, t as describeNamesSubject, u as noPiiInLogs, v as strict, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "./index-YYrIqZKY.mjs";
|
|
3
3
|
export { type Preset, catchHidesFailure, codeClaims, commentDescribesBlock, commentDescribesDeclaration, plugin as default, describeNamesSubject, docErrorsMatchBody, domainNaming, errorMessageMatchesCondition, fnNamePromises, idempotentName, logLevelMatchesEvent, logMessageMatchesEvent, nameMatchesBehavior, noHardcodedSecrets, noPiiInLogs, noPromptInjection, preferSchemaValidation, presets, pureNameIsPure, recommended, reviewOnly, safeNameIsSafe, snapshotOnlyBehaviourClaim, strict, testClaims, testMocksSubject, testNameDescribesCode, testNameVerifiesClaim, untrustedInputRisk, varNameDescribesValue };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import plugin from "./recommended.mjs";
|
|
2
|
-
import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as preferSchemaValidation, a as strict, b as codeClaims, c as testClaims, d as testNameVerifiesClaim, f as domainNaming, g as noPromptInjection, h as noPiiInLogs, i as reviewOnly, j as varNameDescribesValue, k as pureNameIsPure, l as testMocksSubject, m as noHardcodedSecrets, n as presets, o as describeNamesSubject, p as nameMatchesBehavior, r as recommended, s as snapshotOnlyBehaviourClaim, u as testNameDescribesCode, v as untrustedInputRisk, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "
|
|
1
|
+
import plugin from "./presets/recommended.mjs";
|
|
2
|
+
import { A as safeNameIsSafe, C as docErrorsMatchBody, D as logLevelMatchesEvent, E as idempotentName, O as logMessageMatchesEvent, S as commentDescribesDeclaration, T as fnNamePromises, _ as preferSchemaValidation, a as strict, b as codeClaims, c as testClaims, d as testNameVerifiesClaim, f as domainNaming, g as noPromptInjection, h as noPiiInLogs, i as reviewOnly, j as varNameDescribesValue, k as pureNameIsPure, l as testMocksSubject, m as noHardcodedSecrets, n as presets, o as describeNamesSubject, p as nameMatchesBehavior, r as recommended, s as snapshotOnlyBehaviourClaim, u as testNameDescribesCode, v as untrustedInputRisk, w as errorMessageMatchesCondition, x as commentDescribesBlock, y as catchHidesFailure } from "./preset-plugin-miAjemLS.mjs";
|
|
3
3
|
export { catchHidesFailure, codeClaims, commentDescribesBlock, commentDescribesDeclaration, plugin as default, describeNamesSubject, docErrorsMatchBody, domainNaming, errorMessageMatchesCondition, fnNamePromises, idempotentName, logLevelMatchesEvent, logMessageMatchesEvent, nameMatchesBehavior, noHardcodedSecrets, noPiiInLogs, noPromptInjection, preferSchemaValidation, presets, pureNameIsPure, recommended, reviewOnly, safeNameIsSafe, snapshotOnlyBehaviourClaim, strict, testClaims, testMocksSubject, testNameDescribesCode, testNameVerifiesClaim, untrustedInputRisk, varNameDescribesValue };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@r_masseater/oxlint-plugin-decision",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.1",
|
|
4
4
|
"description": "Oxlint JS plugin that lints code with plain-English rules answered by decision models: Clef on Workers AI or Jev on the Typesafe System One API.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai-gateway",
|
|
@@ -34,30 +34,12 @@
|
|
|
34
34
|
"#/*": "./src/*"
|
|
35
35
|
},
|
|
36
36
|
"exports": {
|
|
37
|
-
".":
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"./presets":
|
|
42
|
-
|
|
43
|
-
"default": "./dist/presets/index.mjs"
|
|
44
|
-
},
|
|
45
|
-
"./presets/recommended": {
|
|
46
|
-
"types": "./dist/presets/recommended.d.mts",
|
|
47
|
-
"default": "./dist/presets/recommended.mjs"
|
|
48
|
-
},
|
|
49
|
-
"./presets/strict": {
|
|
50
|
-
"types": "./dist/presets/strict.d.mts",
|
|
51
|
-
"default": "./dist/presets/strict.mjs"
|
|
52
|
-
},
|
|
53
|
-
"./presets/review-only": {
|
|
54
|
-
"types": "./dist/presets/review-only.d.mts",
|
|
55
|
-
"default": "./dist/presets/review-only.mjs"
|
|
56
|
-
},
|
|
57
|
-
"./presets/ai-slop": {
|
|
58
|
-
"types": "./dist/presets/ai-slop.d.mts",
|
|
59
|
-
"default": "./dist/presets/ai-slop.mjs"
|
|
60
|
-
},
|
|
37
|
+
".": "./dist/index.mjs",
|
|
38
|
+
"./presets": "./dist/presets.mjs",
|
|
39
|
+
"./presets/recommended": "./dist/presets/recommended.mjs",
|
|
40
|
+
"./presets/strict": "./dist/presets/strict.mjs",
|
|
41
|
+
"./presets/review-only": "./dist/presets/review-only.mjs",
|
|
42
|
+
"./presets/ai-slop": "./dist/presets/ai-slop.mjs",
|
|
61
43
|
"./package.json": "./package.json"
|
|
62
44
|
},
|
|
63
45
|
"publishConfig": {
|
|
@@ -68,23 +50,29 @@
|
|
|
68
50
|
"synckit": "^0.12.3"
|
|
69
51
|
},
|
|
70
52
|
"devDependencies": {
|
|
71
|
-
"@effect/platform-node": "4.
|
|
72
|
-
"@effect/platform-node-shared": "4.
|
|
53
|
+
"@effect/platform-node": "4.2.0",
|
|
54
|
+
"@effect/platform-node-shared": "4.2.0",
|
|
73
55
|
"@effect/tsgo": "0.74.1",
|
|
74
|
-
"@effect/vitest": "4.
|
|
56
|
+
"@effect/vitest": "4.2.0",
|
|
75
57
|
"@masseater.dev/lint-host": "0.0.0",
|
|
76
58
|
"@oxlint/plugins": "1.95.0",
|
|
59
|
+
"@r_masseater/masseater-utils": "0.2.1",
|
|
77
60
|
"@types/node": "26.6.11",
|
|
78
|
-
"effect": "4.
|
|
61
|
+
"effect": "4.2.0",
|
|
79
62
|
"oxlint": "1.95.0",
|
|
80
63
|
"vite-plus": "1.8.0"
|
|
81
64
|
},
|
|
82
65
|
"peerDependencies": {
|
|
66
|
+
"@effect/platform-node": "^4.1.0",
|
|
83
67
|
"@effect/platform-node-shared": "^4.1.0",
|
|
84
68
|
"effect": "^4.1.0",
|
|
85
69
|
"oxlint": ">=1.94.0"
|
|
86
70
|
},
|
|
87
|
-
"peerDependenciesMeta": {
|
|
71
|
+
"peerDependenciesMeta": {
|
|
72
|
+
"@effect/platform-node": {
|
|
73
|
+
"optional": true
|
|
74
|
+
}
|
|
75
|
+
},
|
|
88
76
|
"engines": {
|
|
89
77
|
"node": ">=26.13.1"
|
|
90
78
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"app-BO1xNTFk.mjs","names":["Str","Arr","FIRST_LINE","Rec","Str","DATA_FIRST_ARITY_3","Arr","Str","Fn","DATA_FIRST_ARITY_3","Str","Fn","DATA_FIRST_ARITY_3","Fn","Arr","DECIMALS","Bool","Arr","Rec","Bool","Str","Arr","Rec","Fn","DATA_FIRST_ARITY","Fn","Arr","Bool","Rec","Arr","Rec","matchOf","Fn","Arr","Str","Arr","Rec","Arr","Rec","Arr"],"sources":["../src/entities/decision/model/budget.ts","../../lint-host/src/shared/lib/collections.ts","../src/entities/decision/model/nodes.ts","../src/entities/decision/model/context.ts","../src/entities/decision/model/define.ts","../src/entities/decision/model/name.ts","../src/features/judge-code/model/override.ts","../src/features/judge-code/model/explain-text.ts","../src/features/judge-code/model/explain.ts","../src/features/judge-code/model/locate.ts","../src/features/judge-code/model/report.ts","../src/features/judge-code/model/visitor.ts","../src/features/judge-code/model/judge-text.ts","../src/app/sync-provider.ts","../src/app/cloudflare.ts","../src/app/typesafe.ts","../src/app/providers.ts","../src/app/judge-text.ts","../src/app/plugin.ts"],"sourcesContent":["export const OUT_OF_BUDGET = /^http (?:402|403): .*(?:credit|budget)/iu;\n","import { Array as Arr, Option, Order, Record as Rec, String as Str, pipe } from \"effect\";\n\nconst byKey = Order.mapInput(Str.Order, ([key]: readonly [string, unknown]) => key);\n\nexport const sortedRecord = <Value>(\n entries: readonly (readonly [string, Value])[],\n): Readonly<Record<string, Value>> => Rec.fromEntries(Arr.sort(entries, byKey));\n\nconst NEXT = 1;\n\nexport interface Grouped<Head, Item> {\n readonly head: Head;\n readonly items: readonly Item[];\n}\n\nexport const groupedUnder =\n <Item, Head>(asHead: (item: Item) => Option.Option<Head>) =>\n (closes: (head: Head, item: Item) => boolean) =>\n (items: readonly Item[]): readonly Grouped<Head, Item>[] =>\n pipe(\n items,\n Arr.flatMap((item, index) =>\n pipe(\n asHead(item),\n Option.map((head): Grouped<Head, Item> => ({\n head,\n items: pipe(\n items,\n Arr.drop(index + NEXT),\n Arr.takeWhile((next) => !closes(head, next)),\n ),\n })),\n Option.toArray,\n ),\n ),\n );\n\nexport const ancestorsBy =\n <Node>(parentOf: (node: Node) => Option.Option<Node>) =>\n (node: Node): readonly Node[] =>\n Arr.unfold(parentOf(node), (current) =>\n pipe(\n current,\n Option.map((found) => [found, parentOf(found)] as const),\n ),\n );\n\nexport const groupOf =\n (name: string) =>\n (found: RegExpMatchArray | null): Option.Option<string> =>\n pipe(\n Option.fromNullishOr(found),\n Option.flatMap((match) => Option.fromNullishOr(match.groups)),\n Option.flatMap((groups) => Option.fromNullishOr(groups[name])),\n );\n","import type { Location } from \"@oxlint/plugins\";\nimport { Option, String as Str, Record as Rec } from \"effect\";\n\nimport type { AstNode, Target } from \"./types.ts\";\n\nconst FIRST_LINE = 1;\nconst FIRST_COLUMN = 0;\nexport const TARGET_NODE_TYPES = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n call: [\"CallExpression\"],\n jsx: [\"JSXElement\"],\n file: [\"Program\"],\n} as const satisfies Readonly<Record<Target, readonly string[]>>;\n\nconst NAMED_PARENTS = {\n VariableDeclarator: \"init\",\n Property: \"value\",\n MethodDefinition: \"value\",\n PropertyDefinition: \"value\",\n} as const;\n\ntype NamedField = (typeof NAMED_PARENTS)[keyof typeof NAMED_PARENTS];\n\nconst NAMED_PARENT_TYPES: ReadonlySet<string> = new Set(Rec.keys(NAMED_PARENTS));\n\nconst isNamedParentType = (type: string): type is keyof typeof NAMED_PARENTS =>\n NAMED_PARENT_TYPES.has(type);\n\nconst ANONYMOUS_FUNCTIONS: ReadonlySet<string> = new Set([\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n]);\n\nconst holdsAsName = (parent: AstNode, node: AstNode): boolean => {\n if (!isNamedParentType(parent.type)) {\n return false;\n }\n const field: NamedField = NAMED_PARENTS[parent.type];\n return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;\n};\n\nexport const snippetNodeFor = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => holdsAsName(parent, node)),\n Option.getOrElse((): AstNode => node),\n );\nconst headOf = (text: string, line: number, column: number): Location => {\n const [first] = Str.split(text, \"\\n\");\n return { start: { line, column }, end: { line, column: column + first.length } };\n};\n\nexport const REPORT_LOC = {\n function: (node: AstNode, text: string): Location =>\n headOf(text, node.loc.start.line, node.loc.start.column),\n call: (node: AstNode): Location => node.loc,\n jsx: (node: AstNode): Location =>\n Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,\n file: (_node: AstNode, text: string): Location => headOf(text, FIRST_LINE, FIRST_COLUMN),\n} as const satisfies Readonly<Record<Target, (node: AstNode, text: string) => Location>>;\n","import { ancestorsBy } from \"@masseater.dev/lint-host/collections\";\nimport type { Context } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, String as Str, pipe, Function as Fn } from \"effect\";\n\nimport { sourceLines } from \"./location.ts\";\nimport { snippetNodeFor } from \"./nodes.ts\";\nimport type { AstNode, EnclosingKind, ResolvedRule, RuleContext } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DEFAULT_LINES = 5;\nconst FIRST_LINE = 1;\nconst LAST = 1;\nconst END = 1;\n\nconst ENCLOSING_TYPES: Readonly<Record<EnclosingKind, readonly string[]>> = {\n function: [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"],\n class: [\"ClassDeclaration\", \"ClassExpression\"],\n block: [\"BlockStatement\", \"StaticBlock\", \"Program\"],\n};\n\nconst ancestorsOf = ancestorsBy((node: AstNode) => Option.fromNullishOr(node.parent));\n\nconst enclosingText = (context: Context, node: AstNode, kind: EnclosingKind): string =>\n Arr.findFirst(ancestorsOf(node), (ancestor) =>\n ENCLOSING_TYPES[kind].includes(ancestor.type),\n ).pipe(\n Option.match({\n onNone: () => context.sourceCode.text,\n onSome: (ancestor) => context.sourceCode.getText(ancestor),\n }),\n );\n\nconst linesAround = (\n context: Context,\n node: AstNode,\n {\n before = DEFAULT_LINES,\n after = DEFAULT_LINES,\n }: { readonly before?: number; readonly after?: number },\n): string => {\n const lines = sourceLines(context.sourceCode.text);\n const first = Math.max(FIRST_LINE, node.loc.start.line - before);\n const last = Math.min(lines.length, node.loc.end.line + after);\n return pipe(\n lines,\n Arr.drop(first - FIRST_LINE),\n Arr.take(last - first + FIRST_LINE),\n Arr.map((text, index) => `L${String(first + index)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n};\n\nconst DECLARING_PARENTS: ReadonlySet<string> = new Set([\n \"VariableDeclaration\",\n \"ExportNamedDeclaration\",\n \"ExportDefaultDeclaration\",\n]);\n\nconst declarationOf = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => DECLARING_PARENTS.has(parent.type)),\n Option.match({ onNone: () => node, onSome: declarationOf }),\n );\n\ninterface Span {\n readonly start: number;\n readonly end: number;\n}\n\nconst leadingOf = (text: string, comments: readonly Span[], until: number): readonly Span[] =>\n Option.match(Arr.last(comments), {\n onNone: () => [],\n onSome: (last) => {\n if (Str.isNonEmpty(Str.trim(Str.slice(last.end, until)(text)))) {\n return [];\n }\n return [...leadingOf(text, Arr.dropRight(comments, LAST), last.start), last];\n },\n });\n\nconst commentedTextOf = (context: Context, node: AstNode): Option.Option<string> => {\n const { text } = context.sourceCode;\n const named = snippetNodeFor(node);\n const [start] = declarationOf(named).range;\n const before = pipe(\n context.sourceCode.getAllComments(),\n Arr.filter((comment) => comment.type !== \"Shebang\" && comment.end <= start),\n );\n return Arr.match(leadingOf(text, before, start), {\n onEmpty: () => Option.none(),\n onNonEmpty: ([first]) => Option.some(Str.slice(first.start, named.range[END])(text)),\n });\n};\n\nconst isCommented = ({ context: wanted }: ResolvedRule): boolean =>\n Predicate.isNotUndefined(wanted) && wanted.scope === \"comment\";\n\nexport const commentedSnippetOf: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): Option.Option<string> =>\n Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)),\n);\n\nexport const lacksComment: {\n (node: AstNode, rule: ResolvedRule): (context: Context) => boolean;\n (context: Context, node: AstNode, rule: ResolvedRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: ResolvedRule): boolean =>\n isCommented(rule) && Option.isNone(commentedTextOf(context, node)),\n);\n\nexport const contextOf: {\n (node: AstNode, rule: RuleContext): (context: Context) => Option.Option<string>;\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: AstNode, rule: RuleContext): Option.Option<string> => {\n if (rule.scope === \"lines\") {\n return Option.some(linesAround(context, node, rule));\n }\n if (rule.scope === \"enclosing\") {\n return Option.some(enclosingText(context, node, rule.kind));\n }\n return Option.liftPredicate(context.sourceCode.text, () => rule.scope === \"file\");\n },\n);\n","import type { DecisionRule } from \"./types.ts\";\n\nexport const defineDecisionRule = <const Rule extends DecisionRule>(rule: Rule): Rule => rule;\n","import type { Context } from \"@oxlint/plugins\";\nimport { Match, Option, String as Str, Function as Fn } from \"effect\";\n\nimport type { DecisionRule, SelectedNode } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst heldName = (node: SelectedNode): Option.Option<SelectedNode> =>\n Option.flatMap(Option.fromNullishOr(node.parent), (parent) =>\n Match.value(parent).pipe(\n Match.when({ type: \"VariableDeclarator\" }, (holder) =>\n Option.liftPredicate(holder.id, () => holder.init === node),\n ),\n Match.when(\n { type: Match.is(\"Property\", \"MethodDefinition\", \"PropertyDefinition\") },\n (holder) => Option.liftPredicate(holder.key, () => holder.value === node),\n ),\n Match.orElse(() => Option.none<SelectedNode>()),\n ),\n );\n\nconst nameNodeOf = (node: SelectedNode): Option.Option<SelectedNode> =>\n Match.value(node).pipe(\n Match.when({ type: Match.is(\"FunctionDeclaration\", \"FunctionExpression\") }, (fn) =>\n Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn)),\n ),\n Match.when({ type: \"ArrowFunctionExpression\" }, heldName),\n Match.when({ type: Match.is(\"CallExpression\", \"NewExpression\") }, (call) =>\n Option.some(call.callee),\n ),\n Match.when({ type: \"JSXElement\" }, (element) => Option.some(element.openingElement.name)),\n Match.orElse(() => Option.none<SelectedNode>()),\n );\n\nconst nameOf = (node: SelectedNode, context: Context): string | undefined =>\n Option.getOrUndefined(\n Option.map(nameNodeOf(node), (name) =>\n Str.slice(name.start, name.end)(context.sourceCode.text),\n ),\n );\n\nexport const isSelected: {\n (node: SelectedNode, rule: DecisionRule): (context: Context) => boolean;\n (context: Context, node: SelectedNode, rule: DecisionRule): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (context: Context, node: SelectedNode, { select }: DecisionRule): boolean =>\n Option.match(Option.fromUndefinedOr(select), {\n onNone: () => true,\n onSome: (selects) => selects(node, { name: nameOf(node, context), context }),\n }),\n);\n","import type { RuleOptionsSchema } from \"@oxlint/plugins\";\nimport { Option, Predicate, Schema, Array as Arr, pipe, Function as Fn } from \"effect\";\n\nimport {\n ModelSpecSchema,\n STRICT,\n checked,\n modelIdsOf,\n resolveModel,\n} from \"#/entities/decision/index.ts\";\nimport type { DecisionProvider, ResolvedRule } from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst RuleOverrideSchema = Schema.Struct({\n model: Schema.optionalKey(ModelSpecSchema),\n});\n\nexport const RULE_OPTIONS_SCHEMA = [\n {\n type: \"object\",\n additionalProperties: false,\n properties: {\n model: {\n oneOf: [\n { type: \"string\", minLength: 1 },\n { type: \"array\", minItems: 1, items: { type: \"string\", minLength: 1 } },\n ],\n },\n },\n },\n] satisfies RuleOptionsSchema;\n\nconst decodeOverride = Schema.decodeUnknownResult(RuleOverrideSchema, STRICT);\n\nexport const overrideRule: {\n (\n raw: unknown,\n providers: Readonly<Record<string, DecisionProvider>>,\n ): (rule: ResolvedRule) => ResolvedRule;\n (\n rule: ResolvedRule,\n raw: unknown,\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedRule;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n rule: ResolvedRule,\n raw: unknown,\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedRule => {\n if (Predicate.isUndefined(raw)) {\n return rule;\n }\n const { model } = checked(decodeOverride, raw, `options for rule \"${rule.id}\"`);\n return {\n ...rule,\n models: Option.match(Option.fromUndefinedOr(model), {\n onNone: () => rule.models,\n onSome: (spec) =>\n pipe(\n modelIdsOf(spec),\n Arr.map((id) => resolveModel(id, providers)),\n ),\n }),\n };\n },\n);\n","import { Array as Arr, Boolean as Bool, Option, Predicate, Record as Rec, pipe } from \"effect\";\n\nimport { PREFIX, toJson } from \"#/entities/decision/index.ts\";\nimport type { Verdict } from \"#/entities/decision/index.ts\";\n\nconst DECIMALS = 2;\nexport interface ExplainQuestion {\n readonly id: string;\n readonly question: string;\n readonly probabilities: Readonly<Record<string, number>>;\n}\n\nexport interface Explanation {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n readonly rule: string;\n readonly model: string;\n readonly served?: string;\n readonly cutoff: number;\n readonly cached?: boolean;\n readonly durationMs: number;\n readonly state: { readonly chars: number; readonly head: string };\n readonly questions: readonly ExplainQuestion[];\n readonly verdict?: Verdict;\n readonly reported: boolean;\n readonly error?: string;\n}\nconst fixed = (value: number): string => value.toFixed(DECIMALS);\n\nconst cachedText = (cached: boolean | undefined): string =>\n Option.match(Option.fromUndefinedOr(cached), {\n onNone: () => \"unknown\",\n onSome: (hit) => Bool.match(hit, { onTrue: () => \"yes\", onFalse: () => \"no\" }),\n });\n\nconst probabilitiesText = (probabilities: Readonly<Record<string, number>>): string =>\n Option.match(\n Arr.match(Rec.toEntries(probabilities), {\n onEmpty: () => Option.none<string>(),\n onNonEmpty: (entries) =>\n Option.some(\n pipe(\n entries,\n Arr.map(([label, value]) => `${label}=${fixed(value)}`),\n Arr.join(\" \"),\n ),\n ),\n }),\n { onNone: () => \"(no answer)\", onSome: (text) => text },\n );\n\nconst verdictText = (explanation: Explanation): string => {\n if (Predicate.isNotUndefined(explanation.error)) {\n return `error: ${explanation.error}`;\n }\n const outcome = Bool.match(explanation.reported, {\n onTrue: () => \"reported\",\n onFalse: () => \"not reported\",\n });\n const cutoff = `cutoff ${fixed(explanation.cutoff)}`;\n return Option.match(Option.fromUndefinedOr(explanation.verdict), {\n onNone: () => `no verdict, ${cutoff}, ${outcome}`,\n onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`,\n });\n};\n\nconst servedText = (served: string | undefined): string =>\n Option.match(Option.fromUndefinedOr(served), {\n onNone: () => \"\",\n onSome: (id) => ` (served ${id})`,\n });\n\nexport const asText = (explanation: Explanation): string =>\n pipe(\n [\n `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,\n ` state: ${String(explanation.state.chars)} chars ${toJson(explanation.state.head)}`,\n ...pipe(\n explanation.questions,\n Arr.map(\n ({ id, question, probabilities }) =>\n ` ${id}: ${probabilitiesText(probabilities)}\\n ${question}`,\n ),\n ),\n ` verdict: ${verdictText(explanation)}`,\n ],\n Arr.join(\"\\n\"),\n );\n","import type { Location } from \"@oxlint/plugins\";\nimport {\n Array as Arr,\n Boolean as Bool,\n Console,\n Effect,\n Function as Fn,\n Match,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n} from \"effect\";\n\nimport { refAt, envOf, toJson, snippetRequestsFor } from \"#/entities/decision/index.ts\";\nimport type {\n Answer,\n Answers,\n DecisionRequest,\n ExplainSetting,\n Match as RuleMatch,\n Question,\n Verdict,\n WireRequest,\n} from \"#/entities/decision/index.ts\";\n\nimport { asText } from \"./explain-text.ts\";\nimport type { Explanation } from \"./explain-text.ts\";\n\ntype ExplainFormat = Extract<ExplainSetting, string>;\n\ntype ExplainMode = \"off\" | ExplainFormat;\n\nconst EXPLAIN_ENV = \"OXLINT_DECISION_EXPLAIN\";\nconst OFF_VALUES: ReadonlySet<string> = new Set([\"0\", \"false\", \"off\", \"no\"]);\nconst STATE_HEAD_CHARS = 60;\nconst OPTION_SEPARATOR = \"__\";\nconst FIRST = 1;\nconst START = 0;\nconst COLUMN_BASE = 1;\n\nexport interface Outcome {\n readonly served: string;\n readonly answers: Answers;\n readonly cached: boolean | undefined;\n readonly verdict: Option.Option<Verdict>;\n readonly reported: boolean;\n}\n\nexport interface Explainer {\n readonly outcome: (match: RuleMatch, at: Placed, outcome: Outcome) => void;\n readonly failure: (matches: readonly RuleMatch[], reason: string) => void;\n}\n\nexport interface Placed {\n readonly ref: string;\n readonly loc: Location;\n}\n\nexport interface ExplainPass {\n readonly setting: ExplainSetting;\n readonly cwd: string;\n readonly filename: string;\n readonly model: string;\n readonly request: DecisionRequest;\n readonly durationMs: number;\n}\n\nconst SEPARATOR = /^[/\\\\]/u;\n\nconst relativeTo = (root: string, filename: string): string =>\n Bool.match(\n Str.isNonEmpty(root) &&\n Str.startsWith(root)(filename) &&\n SEPARATOR.test(Str.slice(root.length)(filename)),\n {\n onTrue: () => Str.slice(root.length + FIRST)(filename),\n onFalse: () => filename,\n },\n );\n\nconst fromSetting = (setting: ExplainSetting): ExplainMode =>\n Match.value(setting).pipe(\n Match.when(\"json\", (): ExplainMode => \"json\"),\n Match.when(true, (): ExplainMode => \"text\"),\n Match.when(\"text\", (): ExplainMode => \"text\"),\n Match.orElse((): ExplainMode => \"off\"),\n );\n\nconst fromEnv = (value: string): ExplainMode =>\n Match.value(Str.toLowerCase(value)).pipe(\n Match.when(\"json\", (): ExplainMode => \"json\"),\n Match.when(\n (lower) => OFF_VALUES.has(lower),\n (): ExplainMode => \"off\",\n ),\n Match.orElse((): ExplainMode => \"text\"),\n );\n\nconst explainModeOf = (setting: ExplainSetting): ExplainMode =>\n Option.match(envOf(EXPLAIN_ENV), { onNone: () => fromSetting(setting), onSome: fromEnv });\n\nconst probabilitiesIn = (answer: Answer): Option.Option<Readonly<Record<string, number>>> => {\n if (answer.type === \"noul\") {\n return Option.some({ yes: answer.noul });\n }\n return Option.fromUndefinedOr(answer.probabilities);\n};\n\nconst probabilitiesOf = (answer: Answer | undefined): Readonly<Record<string, number>> =>\n Option.fromUndefinedOr(answer).pipe(\n Option.flatMap(probabilitiesIn),\n Option.getOrElse(() => ({})),\n );\n\nconst asksAbout = (ref: string, id: string): boolean =>\n pipe(Str.split(id, OPTION_SEPARATOR), Arr.take(FIRST), Arr.contains(ref));\n\nconst askedAbout =\n (ref: string) =>\n (wire: WireRequest): readonly (readonly [string, Question])[] =>\n pipe(\n Rec.toEntries(wire.questions),\n Arr.filter(([id]) => asksAbout(ref, id)),\n );\n\nconst sentFor = (\n sent: readonly WireRequest[],\n ref: string,\n): readonly (readonly [string, Question])[] => pipe(sent, Arr.flatMap(askedAbout(ref)));\n\nconst stateTextOf = (sent: readonly WireRequest[], ref: string, snippet: string): string =>\n Arr.findFirst(sent, (wire) => Arr.isReadonlyArrayNonEmpty(askedAbout(ref)(wire))).pipe(\n Option.map(({ state }) => state),\n Option.filter(Predicate.isString),\n Option.getOrElse(() => snippet),\n );\n\nconst summaryOf = (text: string): Explanation[\"state\"] => ({\n chars: text.length,\n head: Str.slice(START, STATE_HEAD_CHARS)(Str.trim(Str.replaceAll(/\\s+/gu, \" \")(text))),\n});\n\ntype Base = Pick<\n Explanation,\n \"file\" | \"line\" | \"column\" | \"rule\" | \"model\" | \"cutoff\" | \"durationMs\" | \"state\" | \"questions\"\n>;\n\ninterface Sent {\n readonly pass: ExplainPass;\n readonly sent: readonly WireRequest[];\n}\n\nconst baseOf = (\n { pass, sent }: Sent,\n match: RuleMatch,\n { ref, loc }: Placed,\n): ((answers: Answers) => Base) => {\n const questions = sentFor(sent, ref);\n return (answers) => ({\n file: relativeTo(pass.cwd, pass.filename),\n line: loc.start.line,\n column: loc.start.column + COLUMN_BASE,\n rule: match.rule.id,\n model: pass.model,\n cutoff: match.rule.cutoff,\n durationMs: pass.durationMs,\n state: summaryOf(stateTextOf(sent, ref, match.snippet)),\n questions: pipe(\n questions,\n Arr.map(([id, question]) => ({\n id,\n question: question.instructions,\n probabilities: probabilitiesOf(answers[id]),\n })),\n ),\n });\n};\n\nconst printerFor =\n (mode: ExplainFormat) =>\n (explanation: Explanation): void => {\n const line = Bool.match(mode === \"json\", {\n onTrue: () => toJson(explanation),\n onFalse: () => asText(explanation),\n });\n Effect.runFork(Console.error(line));\n };\n\nconst explaining = (pass: ExplainPass, mode: ExplainFormat): Explainer => {\n const sent = snippetRequestsFor(pass.request);\n const print = printerFor(mode);\n return {\n outcome: (match, at, { served, answers, cached, verdict, reported }): void => {\n print({\n ...baseOf({ pass, sent }, match, at)(answers),\n served,\n ...Option.match(Option.fromUndefinedOr(cached), {\n onNone: () => ({}),\n onSome: (hit) => ({ cached: hit }),\n }),\n ...Option.match(verdict, { onNone: () => ({}), onSome: (found) => ({ verdict: found }) }),\n reported,\n });\n },\n failure: (matches, reason): void => {\n for (const [index, match] of matches.entries()) {\n const at = { ref: refAt(index), loc: match.loc };\n print({ ...baseOf({ pass, sent }, match, at)({}), reported: false, error: reason });\n }\n },\n };\n};\n\nconst SILENT: Explainer = { outcome: Fn.constVoid, failure: Fn.constVoid };\n\nexport const explainerFor = (pass: ExplainPass): Explainer =>\n Match.value(explainModeOf(pass.setting)).pipe(\n Match.when(\"off\", () => SILENT),\n Match.orElse((mode) => explaining(pass, mode)),\n );\n","import type { Location } from \"@oxlint/plugins\";\nimport { Effect, Option, Function as Fn } from \"effect\";\n\nimport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n selectedLocation,\n locationRefOf,\n parseVerdicts,\n messageOf,\n nowMs,\n runOrElse,\n} from \"#/entities/decision/index.ts\";\nimport type {\n LocatedMatch,\n DecideInput,\n DecideResult,\n DecisionRequest,\n LineRange,\n Match,\n ModelRef,\n Verdicts,\n} from \"#/entities/decision/index.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DATA_FIRST_ARITY = 2;\n\nexport type VerdictResult =\n | { readonly ok: true; readonly verdicts: Verdicts; readonly cached: boolean | undefined }\n | { readonly ok: false; readonly reason: string };\n\nexport interface Located {\n readonly loc: Location;\n readonly failure: Option.Option<string>;\n}\n\nexport interface Asking {\n readonly model: ModelRef;\n readonly deadline: number;\n readonly env: Readonly<Record<string, string>>;\n}\n\ninterface Refinement {\n readonly asking: Asking;\n readonly match: Match & LocatedMatch;\n readonly ref: string;\n readonly state: DecisionRequest[\"state\"];\n}\n\nconst MINIMUM_TIMEOUT_MS = 1;\n\nconst remainingMs = (deadline: number): number => Math.max(MINIMUM_TIMEOUT_MS, deadline - nowMs());\n\nexport const verdictsOf: {\n (request: DecisionRequest): (result: DecideResult) => VerdictResult;\n (result: DecideResult, request: DecisionRequest): VerdictResult;\n} = Fn.dual(DATA_FIRST_ARITY, (result: DecideResult, request: DecisionRequest): VerdictResult => {\n if (!result.ok) {\n return result;\n }\n return runOrElse(\n Effect.sync((): VerdictResult => ({\n ok: true,\n verdicts: parseVerdicts(result.response, request),\n cached: result.cached,\n })),\n (cause) => ({ ok: false, reason: messageOf(cause) }),\n );\n});\n\nexport const inputOf: {\n (request: DecisionRequest): (asking: Asking) => DecideInput;\n (asking: Asking, request: DecisionRequest): DecideInput;\n} = Fn.dual(DATA_FIRST_ARITY, (asking: Asking, request: DecisionRequest): DecideInput => ({\n request,\n timeoutMs: remainingMs(asking.deadline),\n env: asking.env,\n}));\n\nconst fetchVerdicts = (asking: Asking, request: DecisionRequest): VerdictResult =>\n verdictsOf(asking.model.provider.decide(inputOf(asking, request)), request);\n\nconst isRange = (location: Option.Option<LineRange>): location is Option.Some<LineRange> =>\n Option.exists(location, ({ start, end }) => start !== end);\n\nconst refineOnce = (\n { asking, match, ref, state }: Refinement,\n within: LineRange,\n): VerdictResult & { readonly next?: Option.Option<LineRange> } => {\n const questionId = locationRefOf(ref);\n const candidates = locationCandidates(match.snippet, within);\n const refined = fetchVerdicts(asking, {\n model: asking.model.model,\n state,\n questions: { [questionId]: locationQuestion(match, ref, candidates) },\n });\n if (!refined.ok) {\n return refined;\n }\n return {\n ...refined,\n next: selectedLocation(\n refined.verdicts.answers[questionId],\n candidates,\n match.rule.location.cutoff,\n ),\n };\n};\n\nconst refine = (refinement: Refinement, first: Option.Option<LineRange>): Located => {\n let location = first;\n while (isRange(location)) {\n const step = refineOnce(refinement, location.value);\n if (!step.ok) {\n return { loc: refinement.match.loc, failure: Option.some(step.reason) };\n }\n location = step.next ?? Option.none();\n }\n return {\n loc: Option.match(location, {\n onNone: () => refinement.match.loc,\n onSome: ({ start }) => locationOfLine(refinement.match.snippet, start),\n }),\n failure: Option.none(),\n };\n};\n\nexport interface LocateInput {\n readonly ref: string;\n readonly verdicts: Verdicts;\n readonly request: DecisionRequest;\n}\n\nexport const locateMatch: {\n (match: Match, input: LocateInput): (asking: Asking) => Located;\n (asking: Asking, match: Match, input: LocateInput): Located;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (asking: Asking, match: Match, { ref, verdicts, request }: LocateInput): Located => {\n if (!locates(match)) {\n return { loc: match.loc, failure: Option.none() };\n }\n const first = selectedLocation(\n verdicts.answers[locationRefOf(ref)],\n locationCandidates(match.snippet, EVERY_LINE),\n match.rule.location.cutoff,\n );\n return refine({ asking, match, ref, state: request.state }, first);\n },\n);\n","import type { Context, Location } from \"@oxlint/plugins\";\nimport { Array as Arr, Boolean as Bool, Option, Record as Rec, pipe } from \"effect\";\n\nimport {\n isReported,\n OUT_OF_BUDGET,\n optionsError,\n buildRequest,\n refAt,\n failsInCi,\n warnOnce,\n} from \"#/entities/decision/index.ts\";\nimport type {\n DecideResult,\n DecisionProvider,\n DecisionRequest,\n Match,\n ModelRef,\n ResolvedOptions,\n Verdicts,\n} from \"#/entities/decision/index.ts\";\n\nimport { explainerFor } from \"./explain.ts\";\nimport type { ExplainPass, Explainer, Outcome, Placed } from \"./explain.ts\";\nimport { inputOf, locateMatch, verdictsOf } from \"./locate.ts\";\nimport type { Asking, Located } from \"./locate.ts\";\n\nexport interface ModelPass {\n readonly contextOf: (match: Match) => Context;\n readonly filename: string;\n readonly options: ResolvedOptions;\n readonly model: ModelRef;\n readonly matches: readonly Match[];\n readonly deadline: number;\n}\n\ninterface Failure {\n readonly match: Match;\n readonly loc: Location;\n readonly reason: string;\n}\n\ninterface Answered {\n readonly asking: Asking;\n readonly verdicts: Verdicts;\n readonly request: DecisionRequest;\n readonly cached: boolean | undefined;\n readonly explainer: Explainer;\n}\n\nconst DECIMALS = 2;\n\nconst failsHere = (pass: ModelPass, reason: string): boolean =>\n failsInCi(pass.options) && !OUT_OF_BUDGET.test(reason);\n\nconst degrade = (pass: ModelPass, reason: string): void => {\n if (failsHere(pass, reason)) {\n throw optionsError(`${reason} (${pass.filename})`);\n }\n warnOnce(reason, `${reason} (${pass.filename})`);\n};\n\nconst reportFailure = (pass: ModelPass, failure: Failure): void => {\n if (failsHere(pass, failure.reason)) {\n pass.contextOf(failure.match).report({\n loc: failure.loc,\n messageId: \"unlocated\",\n data: { id: failure.match.rule.id, reason: failure.reason },\n });\n return;\n }\n warnOnce(failure.reason, `${failure.reason} (${pass.filename})`);\n};\n\nconst locate = (\n answered: Answered,\n match: Match,\n { ref, failed }: { readonly ref: string; readonly failed: boolean },\n): Located => {\n if (failed) {\n return { loc: match.loc, failure: Option.none() };\n }\n return locateMatch(answered.asking, match, { ...answered, ref });\n};\n\nconst outcomeOf = (answered: Answered, match: Match, ref: string): Outcome => {\n const verdict = Option.fromUndefinedOr(answered.verdicts.results[ref]);\n return {\n served: `${answered.asking.model.provider.name}/${answered.verdicts.model}`,\n cached: answered.cached,\n answers: answered.verdicts.answers,\n verdict,\n reported: Option.exists(verdict, (found) => isReported(match.rule, found)),\n };\n};\n\nconst reportMatch = (\n pass: ModelPass,\n answered: Answered,\n { match, ref, failed }: { readonly match: Match; readonly ref: string; readonly failed: boolean },\n): Option.Option<string> => {\n const outcome = outcomeOf(answered, match, ref);\n const { verdict } = outcome;\n if (!outcome.reported || Option.isNone(verdict)) {\n answered.explainer.outcome(match, { ref, loc: match.loc }, outcome);\n return Option.none();\n }\n const located = locate(answered, match, { ref, failed });\n const at: Placed = { ref, loc: located.loc };\n answered.explainer.outcome(match, at, outcome);\n pass.contextOf(match).report({\n loc: located.loc,\n messageId: \"yes\",\n data: {\n id: match.rule.id,\n model: `${pass.model.provider.name}/${answered.verdicts.model}`,\n answer: verdict.value.answer,\n score: verdict.value.probability.toFixed(DECIMALS),\n cutoff: match.rule.cutoff.toFixed(DECIMALS),\n question: match.rule.message ?? match.rule.question,\n },\n });\n return located.failure;\n};\n\nconst reportMatches = (pass: ModelPass, answered: Answered): Option.Option<Failure> => {\n let failure: Option.Option<Failure> = Option.none();\n for (const [index, match] of pass.matches.entries()) {\n const located = reportMatch(pass, answered, {\n match,\n ref: refAt(index),\n failed: Option.isSome(failure),\n });\n failure = Option.orElse(failure, () =>\n located.pipe(Option.map((reason) => ({ match, loc: match.loc, reason }))),\n );\n }\n return failure;\n};\n\nconst explainPassOf = (\n pass: ModelPass,\n { request, durationMs }: Pick<ExplainPass, \"request\" | \"durationMs\">,\n): ExplainPass => ({\n setting: pass.options.explain,\n cwd: Option.match(Arr.head(pass.matches), {\n onNone: () => \"\",\n onSome: (match) => pass.contextOf(match).cwd,\n }),\n filename: pass.filename,\n model: pass.model.id,\n request,\n durationMs,\n});\n\ninterface Prepared {\n readonly pass: ModelPass;\n readonly asking: Asking;\n readonly request: DecisionRequest;\n}\n\nconst prepare = (pass: ModelPass): Prepared => ({\n pass,\n asking: { model: pass.model, deadline: pass.deadline, env: pass.options.env },\n request: buildRequest(pass.model.model, pass.matches),\n});\n\nconst reportAnswer = (\n { pass, asking, request }: Prepared,\n { decided, durationMs }: { readonly decided: DecideResult; readonly durationMs: number },\n): void => {\n const explainer = explainerFor(explainPassOf(pass, { request, durationMs }));\n const result = verdictsOf(decided, request);\n if (!result.ok) {\n explainer.failure(pass.matches, result.reason);\n degrade(pass, result.reason);\n return;\n }\n Option.map(reportMatches(pass, { ...result, asking, request, explainer }), (failure) => {\n reportFailure(pass, failure);\n });\n};\n\nconst decideWith = (\n provider: DecisionProvider,\n prepared: readonly Prepared[],\n): readonly DecideResult[] => {\n const inputs = pipe(\n prepared,\n Arr.map(({ asking, request }) => inputOf(asking, request)),\n );\n return provider.decideAll(inputs);\n};\n\nconst reportProvider = (prepared: Arr.NonEmptyReadonlyArray<Prepared>): void => {\n const { provider } = Arr.headNonEmpty(prepared).pass.model;\n const started = performance.now();\n const results = decideWith(provider, prepared);\n const durationMs = Math.round(performance.now() - started);\n const answers = Bool.match(results.length === prepared.length, {\n onTrue: () => results,\n onFalse: () =>\n pipe(\n prepared,\n Arr.map((): DecideResult => ({\n ok: false,\n reason: `provider ${provider.name} returned ${String(results.length)} results for ${String(prepared.length)} requests`,\n })),\n ),\n });\n for (const [one, decided] of Arr.zip(prepared, answers)) {\n reportAnswer(one, { decided, durationMs });\n }\n};\n\nexport const reportModels = (passes: readonly ModelPass[]): void => {\n const byProvider = Arr.groupBy(\n pipe(\n passes,\n Arr.map((pass) => prepare(pass)),\n ),\n ({ pass }) => pass.model.provider.name,\n );\n for (const prepared of Rec.values(byProvider)) {\n reportProvider(prepared);\n }\n};\n","import type { Context, VisitorWithHooks } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, Record as Rec, pipe, Function as Fn } from \"effect\";\n\nimport {\n commentedSnippetOf,\n contextOf,\n lacksComment,\n isSelected,\n REPORT_LOC,\n TARGET_NODE_TYPES,\n snippetNodeFor,\n optionsError,\n truncateSnippet,\n missingEnvOf,\n failsInCi,\n nowMs,\n warnOnce,\n} from \"#/entities/decision/index.ts\";\nimport type {\n AstNode,\n Match,\n ModelRef,\n ResolvedOptions,\n ResolvedRule,\n SelectedNode,\n Target,\n} from \"#/entities/decision/index.ts\";\n\nimport { reportModels } from \"./report.ts\";\nimport type { ModelPass } from \"./report.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nexport interface Collected {\n readonly options: ResolvedOptions;\n readonly contexts: Readonly<Record<string, Context>>;\n readonly rules: Readonly<Record<string, ResolvedRule>>;\n readonly matches: readonly Match[];\n}\n\nexport interface FileBatch extends Collected {\n readonly contexts: Record<string, Context>;\n readonly rules: Record<string, ResolvedRule>;\n readonly matches: Match[];\n exiting: boolean;\n exits: number;\n}\n\nexport interface RuleFile {\n readonly batch: FileBatch;\n readonly rule: ResolvedRule;\n}\n\nexport interface SharedFile {\n readonly join: (context: Context, id: string) => RuleFile;\n readonly leave: () => void;\n}\n\nexport type OptionsFor = (settings: Readonly<Record<string, unknown>>) => ResolvedOptions;\n\nexport type RuleFor = (rule: ResolvedRule, options: unknown) => ResolvedRule;\n\nconst raisedMissing = new Set<string>();\n\nconst isAvailable = (options: ResolvedOptions, { provider }: ModelRef): boolean => {\n const missingNames = missingEnvOf(options.env, provider);\n if (Arr.isReadonlyArrayEmpty(missingNames)) {\n return true;\n }\n const missing = pipe(missingNames, Arr.join(\", \"));\n if (!failsInCi(options)) {\n warnOnce(`missing:${provider.name}`, `${missing} is not set, skipping ${provider.name} models`);\n } else if (!raisedMissing.has(provider.name)) {\n raisedMissing.add(provider.name);\n throw optionsError(`${missing} is not set`);\n }\n return false;\n};\n\nconst availableModels = (batch: Collected): readonly ModelRef[] => {\n const models = pipe(\n Rec.values(batch.rules),\n Arr.flatMap((rule) => rule.models),\n Arr.map((model) => [model.id, model] as const),\n );\n return pipe(\n Arr.fromIterable(new Map(models).values()),\n Arr.filter((model) => isAvailable(batch.options, model)),\n );\n};\n\nconst snippetOf = (context: Context, node: AstNode): string => {\n if (node.type === \"Program\") {\n return context.sourceCode.text;\n }\n return context.sourceCode.getText(node);\n};\n\nconst namedSnippetOf = (context: Context, node: AstNode): string => {\n const named = snippetNodeFor(node);\n if (named === node) {\n return snippetOf(context, node);\n }\n return context.sourceCode.getText(named);\n};\n\nconst matchOf = (\n context: Context,\n node: AstNode,\n { rule, options }: { readonly rule: ResolvedRule; readonly options: ResolvedOptions },\n): Match => {\n const text = Option.getOrElse(commentedSnippetOf(context, node, rule), () =>\n namedSnippetOf(context, node),\n );\n const surrounding = contextOf(context, node, rule.context ?? { scope: \"node\" });\n return {\n ...Option.match(surrounding, { onNone: () => ({}), onSome: (value) => ({ context: value }) }),\n rule,\n loc: REPORT_LOC[rule.target](node, snippetOf(context, node)),\n snippet: truncateSnippet(text, options.maxSnippetChars),\n truncated: text.length > options.maxSnippetChars,\n };\n};\n\nconst contextOfRule = (batch: Collected, id: string): Context =>\n Option.getOrThrow(Option.fromUndefinedOr(batch.contexts[id]));\n\nconst finish = (batch: Collected): void => {\n const [first] = Rec.values(batch.contexts);\n if (Predicate.isUndefined(first)) {\n return;\n }\n const deadline = nowMs() + batch.options.timeoutMs;\n const passes = pipe(\n availableModels(batch),\n Arr.flatMap((model): readonly ModelPass[] => {\n const matches = pipe(\n batch.matches,\n Arr.filter(({ rule }) =>\n pipe(\n rule.models,\n Arr.some(({ id }) => id === model.id),\n ),\n ),\n );\n return Arr.match(matches, {\n onEmpty: () => [],\n onNonEmpty: (some) => [\n {\n contextOf: (match) => contextOfRule(batch, match.rule.id),\n filename: first.filename,\n options: batch.options,\n model,\n matches: some,\n deadline,\n },\n ],\n });\n }),\n );\n reportModels(passes);\n};\n\nconst ruleIn = (batch: Collected, id: string): ResolvedRule =>\n Option.getOrThrow(Arr.findFirst(batch.options.rules, (rule) => rule.id === id));\n\nexport const sharedFile: {\n (ruleFor: RuleFor): (optionsFor: OptionsFor) => SharedFile;\n (optionsFor: OptionsFor, ruleFor: RuleFor): SharedFile;\n} = Fn.dual(DATA_FIRST_ARITY, (optionsFor: OptionsFor, ruleFor: RuleFor): SharedFile => {\n let current: Option.Option<FileBatch> = Option.none();\n const start = (context: Context): FileBatch => {\n const batch: FileBatch = {\n options: optionsFor(context.settings),\n contexts: {},\n rules: {},\n matches: [],\n exiting: false,\n exits: 0,\n };\n current = Option.some(batch);\n return batch;\n };\n return {\n join: (context, id): RuleFile => {\n const batch = Option.match(current, {\n onNone: () => start(context),\n onSome: (open) => {\n if (open.exiting) {\n return start(context);\n }\n return open;\n },\n });\n const [options] = context.options;\n const rule = ruleFor(ruleIn(batch, id), options);\n batch.contexts[id] = context;\n batch.rules[id] = rule;\n return { batch, rule };\n },\n leave: (): void => {\n if (Option.isNone(current)) {\n return;\n }\n const batch = current.value;\n batch.exits += 1;\n if (batch.exits >= Rec.keys(batch.contexts).length) {\n current = Option.none();\n }\n if (!batch.exiting) {\n batch.exiting = true;\n finish(batch);\n }\n },\n };\n});\n\ntype Visited = SelectedNode & AstNode;\n\nconst isSkipped = (context: Context, node: Visited, rule: ResolvedRule): boolean =>\n !isSelected(context, node, rule) || lacksComment(context, node, rule);\n\nexport interface RuleTarget {\n readonly id: string;\n readonly target: Target;\n}\n\nexport const visitorFor: {\n (rule: RuleTarget): (shared: SharedFile) => (context: Context) => VisitorWithHooks;\n (shared: SharedFile, rule: RuleTarget): (context: Context) => VisitorWithHooks;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (shared: SharedFile, { id, target }: RuleTarget) =>\n (context: Context): VisitorWithHooks => {\n let file: Option.Option<RuleFile> = Option.none();\n\n const collect = (node: Visited): void => {\n if (Option.isNone(file)) {\n return;\n }\n const { batch, rule } = file.value;\n if (isSkipped(context, node, rule)) {\n return;\n }\n batch.matches.push(matchOf(context, node, { rule, options: batch.options }));\n };\n\n const nodeTypes: readonly string[] = TARGET_NODE_TYPES[target];\n\n return {\n ...Rec.fromEntries(\n pipe(\n nodeTypes,\n Arr.map((type) => [type, collect]),\n ),\n ),\n Program: (node: Visited): void => {\n file = Option.some(shared.join(context, id));\n if (target === \"file\") {\n collect(node);\n }\n },\n \"Program:exit\": (): void => {\n file = Option.none();\n shared.leave();\n },\n };\n },\n);\n","import type { Location } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, pipe } from \"effect\";\n\nimport {\n BOOLEAN_ANSWER,\n buildRequest,\n isReported,\n missingEnvOf,\n nowMs,\n refAt,\n resolveModel,\n} from \"#/entities/decision/index.ts\";\nimport type { DecisionProvider, Match, ModelRef, RuleLocation } from \"#/entities/decision/index.ts\";\n\nimport { inputOf, locateMatch, verdictsOf } from \"./locate.ts\";\nimport type { Asking } from \"./locate.ts\";\n\nconst FIRST_MATCH = 0;\n\nconst FILE_START: Location = { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } };\n\nconst DEFAULT_LOCATION: RuleLocation = {\n question: \"Select the line that holds the text which breaks the rule.\",\n cutoff: 0.5,\n};\n\n/** @internal */\nexport interface TextRule {\n readonly id: string;\n readonly question: string;\n readonly cutoff: number;\n readonly location?: RuleLocation;\n}\n\n/** @internal */\nexport interface JudgeTextInput {\n readonly rule: TextRule;\n readonly text: string;\n readonly model: string;\n readonly timeoutMs: number;\n readonly env: Readonly<Record<string, string>>;\n}\n\n/** @internal */\nexport type JudgedText =\n | { readonly status: \"violation\"; readonly line: number }\n | { readonly status: \"pass\" }\n | { readonly status: \"unknown\"; readonly reason: string };\n\nconst unknownBecause = (reason: string): JudgedText => ({ status: \"unknown\", reason });\n\nconst matchOf = ({ rule, text }: JudgeTextInput, model: ModelRef): Match => ({\n rule: {\n id: rule.id,\n target: \"file\",\n question: rule.question,\n cutoff: rule.cutoff,\n location: rule.location ?? DEFAULT_LOCATION,\n answer: BOOLEAN_ANSWER,\n models: [model],\n },\n snippet: text,\n truncated: false,\n loc: FILE_START,\n});\n\nconst judgeWith = (input: JudgeTextInput, model: ModelRef): JudgedText => {\n const match = matchOf(input, model);\n const request = buildRequest(model.model, [match]);\n const asking: Asking = { model, deadline: nowMs() + input.timeoutMs, env: input.env };\n const decided = verdictsOf(model.provider.decide(inputOf(asking, request)), request);\n if (!decided.ok) {\n return unknownBecause(decided.reason);\n }\n const ref = refAt(FIRST_MATCH);\n return Option.match(Option.fromUndefinedOr(decided.verdicts.results[ref]), {\n onNone: () => unknownBecause(\"the decision model returned no answer\"),\n onSome: (verdict): JudgedText => {\n if (!isReported(match.rule, verdict)) {\n return { status: \"pass\" };\n }\n const located = locateMatch(asking, match, { ref, verdicts: decided.verdicts, request });\n return { status: \"violation\", line: located.loc.start.line };\n },\n });\n};\n\n/** @internal */\nexport const judgeTextWith =\n (providers: Readonly<Record<string, DecisionProvider>>) =>\n (input: JudgeTextInput): JudgedText => {\n const model = resolveModel(input.model, providers);\n const missing = missingEnvOf(input.env, model.provider);\n if (Arr.isReadonlyArrayNonEmpty(missing)) {\n return unknownBecause(`${pipe(missing, Arr.join(\", \"))} is not set`);\n }\n return judgeWith(input, model);\n };\n","import { Array as Arr, Effect, Option, String as Str, pipe } from \"effect\";\nimport { createSyncFn } from \"synckit\";\nimport type { Syncify } from \"synckit\";\n\nimport { messageOf, runOrElse } from \"#/entities/decision/index.ts\";\nimport type { DecideInput, DecideResult, DecisionProvider } from \"#/entities/decision/index.ts\";\n\nconst BACKSTOP_MS = 60_000;\nconst SYNCKIT_TIMEOUT = \"Internal error: Atomics.wait() failed: timed-out\";\nconst BUILT_EXTENSION = \".mjs\";\nconst MODULE_EXTENSION = /\\.[cm]?[jt]s$/u;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\ntype Results = Arr.NonEmptyReadonlyArray<DecideResult>;\n\ntype Worker = (inputs: Inputs) => Promise<Results>;\n\n/** @internal */\nexport interface SyncProviderSetup extends Pick<\n DecisionProvider,\n \"name\" | \"requiredEnv\" | \"models\"\n> {\n readonly worker: string;\n}\n\nconst workers = new Map<string, Syncify<Worker>>();\n\nconst workerUrl = (worker: string): URL => {\n const extension = pipe(\n Str.match(MODULE_EXTENSION)(import.meta.url),\n Option.flatMap(Arr.head),\n Option.getOrElse(() => BUILT_EXTENSION),\n );\n return new URL(`${worker}${extension}`, import.meta.url);\n};\n\nconst workerCall = (worker: string): Syncify<Worker> =>\n workers.getOrInsertComputed(worker, () =>\n createSyncFn<Worker>(workerUrl(worker), { timeout: BACKSTOP_MS }),\n );\n\nconst reasonOf = (error: unknown): string => {\n const message = messageOf(error);\n if (message === SYNCKIT_TIMEOUT) {\n return \"timeout\";\n }\n return `network: ${message}`;\n};\n\nconst askWorker = (worker: string, inputs: Inputs): Results =>\n runOrElse(\n Effect.sync(() => workerCall(worker)(inputs)),\n (cause) =>\n pipe(\n inputs,\n Arr.map((): DecideResult => ({ ok: false, reason: reasonOf(cause) })),\n ),\n );\n\n/** @internal */\nexport const syncProvider = ({ worker, ...provider }: SyncProviderSetup): DecisionProvider => ({\n ...provider,\n decide: (input) => Arr.headNonEmpty(askWorker(worker, [input])),\n decideAll: (inputs) =>\n Arr.match(inputs, { onEmpty: () => [], onNonEmpty: (some) => askWorker(worker, some) }),\n});\n","import { CLEF_MODEL } from \"#/entities/decision/index.ts\";\n\nimport { syncProvider } from \"./sync-provider.ts\";\n\nexport const cloudflare = syncProvider({\n name: \"cloudflare\",\n worker: \"cloudflare-worker\",\n requiredEnv: [\"CLOUDFLARE_API_TOKEN\", \"CLOUDFLARE_ACCOUNT_ID\"],\n models: CLEF_MODEL,\n});\n","import { JEV_MODEL } from \"#/entities/decision/index.ts\";\n\nimport { syncProvider } from \"./sync-provider.ts\";\n\nexport const typesafe = syncProvider({\n name: \"typesafe\",\n worker: \"typesafe-worker\",\n requiredEnv: [\"TYPESAFE_API_KEY\"],\n models: JEV_MODEL,\n});\n","import { Array as Arr, Record as Rec, pipe } from \"effect\";\n\nimport type { DecisionProvider } from \"#/entities/decision/index.ts\";\n\nimport { cloudflare } from \"./cloudflare.ts\";\nimport { typesafe } from \"./typesafe.ts\";\n\n/** @internal */\nexport const decisionProviders: Readonly<Record<string, DecisionProvider>> = Rec.fromEntries(\n pipe(\n [cloudflare, typesafe],\n Arr.map((provider) => [provider.name, provider]),\n ),\n);\n","import { judgeTextWith } from \"#/features/judge-code/index.ts\";\n\nimport { decisionProviders } from \"./providers.ts\";\n\nexport const judgeText = judgeTextWith(decisionProviders);\n","import type { Plugin, RuleMeta } from \"@oxlint/plugins\";\nimport { Array as Arr, Record as Rec, Struct, pipe } from \"effect\";\n\nimport { PREFIX, checkRules, resolveOptions, toJson } from \"#/entities/decision/index.ts\";\nimport type {\n DecisionOptions,\n DecisionPlugin,\n DecisionPluginSetup,\n DecisionProvider,\n DecisionRule,\n ResolvedOptions,\n ResolvedRule,\n} from \"#/entities/decision/index.ts\";\nimport {\n RULE_OPTIONS_SCHEMA,\n overrideRule,\n sharedFile,\n visitorFor,\n} from \"#/features/judge-code/index.ts\";\n\nimport { decisionProviders } from \"./providers.ts\";\n\nconst DEFAULT_NAME = \"decision\";\n\nconst metaOf = (rule: DecisionRule): RuleMeta => ({\n type: \"problem\",\n docs: { description: rule.question },\n schema: RULE_OPTIONS_SCHEMA,\n messages: {\n yes: \"[{{id}}] {{model}} answered {{answer}} ({{score}} >= {{cutoff}}): {{question}}\",\n unlocated: `${PREFIX}: {{reason}} while refining the location of [{{id}}]; the finding is reported at the file level`,\n },\n});\n\nconst optionsOf = (setup: DecisionPluginSetup): DecisionOptions =>\n Struct.omit(setup, [\"name\", \"rules\"]);\n\ntype Resolve = (settings: unknown) => ResolvedOptions;\n\nconst memoized = (resolve: Resolve): Resolve => {\n const resolved = new Map<string, ResolvedOptions>();\n return (settings) => {\n const key = toJson([settings]);\n return resolved.getOrInsertComputed(key, () => resolve(settings));\n };\n};\n\nconst memoizedRules = (\n providers: Readonly<Record<string, DecisionProvider>>,\n): ((rule: ResolvedRule, options: unknown) => ResolvedRule) => {\n const resolved = new WeakMap<ResolvedRule, Map<string, ResolvedRule>>();\n return (rule, options) => {\n const known = resolved.getOrInsertComputed(rule, () => new Map<string, ResolvedRule>());\n const key = toJson([options]);\n return known.getOrInsertComputed(key, () => overrideRule(rule, options, providers));\n };\n};\n\nexport const createDecisionPlugin = (setup: DecisionPluginSetup): DecisionPlugin => {\n const name = setup.name ?? DEFAULT_NAME;\n const rules = checkRules(setup.rules);\n const options = optionsOf(setup);\n const resolve = memoized((settings) =>\n resolveOptions({ options, settings }, rules, decisionProviders),\n );\n resolve({});\n const shared = sharedFile(\n (settings) => resolve(settings[name]),\n memoizedRules(decisionProviders),\n );\n\n return {\n meta: { name },\n rules: Rec.fromEntries(\n pipe(\n rules,\n Arr.map((rule) => [rule.id, { meta: metaOf(rule), createOnce: visitorFor(shared, rule) }]),\n ),\n ),\n } satisfies Plugin;\n};\n"],"mappings":";;;;AAAA,MAAa,gBAAgB;ACEf,MAAM,SAASA,SAAI,QAAQ,CAAC,SAAqC,GAAG;AAmClF,MAAa,eACJ,cACN,SACCC,MAAI,OAAO,SAAS,IAAI,IAAI,YAC1B,KACE,SACA,OAAO,KAAK,UAAU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