@r_masseater/oxlint-plugin-decision 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,112 @@
1
+ import { a as messageOf, y as AnswerSchema } from "./runtime-CICpEidL.mjs";
2
+ import { s as parseVerdicts } from "./wire-BbVK3Q_K.mjs";
3
+ import { Array, Clock, Effect, FileSystem, Function, Layer, Option, Path, Schema, pipe } from "effect";
4
+ import { runAsWorker } from "synckit";
5
+ import { FetchHttpClient } from "effect/http";
6
+ import { Digest } from "effect/crypto";
7
+ import { layerDigest } from "@effect/platform-node-shared/NodeCrypto";
8
+ import { layer } from "@effect/platform-node-shared/NodeFileSystem";
9
+ import { layer as layer$1 } from "@effect/platform-node-shared/NodePath";
10
+ import { OtlpSerialization, OtlpTracer } from "effect/observability";
11
+ // src/cache.ts
12
+ const DATA_FIRST_ARITY = 2;
13
+ const CACHE_VERSION = 7;
14
+ const CACHE_DIR = [
15
+ "node_modules",
16
+ ".cache",
17
+ "oxlint-plugin-decision"
18
+ ];
19
+ const encodeJson = (value) => Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);
20
+ const cacheFile = Effect.fn("cacheFile")(function* cacheFile(endpoint, request) {
21
+ const digest = yield* Digest.Digest;
22
+ const path = yield* Path.Path;
23
+ const json = yield* encodeJson({
24
+ version: CACHE_VERSION,
25
+ endpoint,
26
+ request
27
+ });
28
+ const payload = new TextEncoder().encode(json);
29
+ const hash = yield* digest.digestHex(Digest.sha256, payload);
30
+ return path.resolve(...CACHE_DIR, `${hash}.json`);
31
+ });
32
+ const CachedResponse = Schema.Struct({
33
+ model: Schema.NonEmptyString,
34
+ answers: Schema.Record(Schema.String, AnswerSchema)
35
+ });
36
+ const decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));
37
+ const isComplete = Function.dual(DATA_FIRST_ARITY, (response, request) => Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(Option.getOrElse(() => false)));
38
+ const readCache = Effect.fn("readCache")(function* readCache(file, request) {
39
+ return (yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.option)).pipe(Option.flatMap((raw) => decodeCached(raw)), Option.filter((response) => isComplete(response, request)));
40
+ });
41
+ const writeCache = Effect.fn("writeCache")(function* writeCache(file, response) {
42
+ const fs = yield* FileSystem.FileSystem;
43
+ const path = yield* Path.Path;
44
+ const now = yield* Clock.currentTimeMillis;
45
+ const temp = `${file}.tmp-${String(now)}`;
46
+ const json = yield* encodeJson(response);
47
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
48
+ yield* fs.writeFileString(temp, json);
49
+ yield* fs.rename(temp, file);
50
+ });
51
+ // src/services.ts
52
+ const tracing = OtlpTracer.layerFromConfig({ resource: { serviceName: "oxlint-plugin-decision" } }).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
53
+ const workerServices = [
54
+ layer,
55
+ layer$1,
56
+ layerDigest,
57
+ FetchHttpClient.layer,
58
+ tracing
59
+ ];
60
+ // src/serve-decisions.ts
61
+ const ask = Effect.fn("ask")(function* ask(transport, endpoint, { request, timeoutMs, env }) {
62
+ const responses = yield* Effect.forEach(transport.wires(request), (wire) => transport.send(endpoint, wire, { env }), { concurrency: "unbounded" }).pipe(Effect.timeoutOrElse({
63
+ duration: timeoutMs,
64
+ orElse: () => Effect.fail("timeout")
65
+ }));
66
+ return transport.combine(request, responses);
67
+ });
68
+ const askAndStore = Effect.fn("askAndStore")(function* askAndStore(transport, { endpoint, file }, input) {
69
+ const response = yield* ask(transport, endpoint, input);
70
+ if (isComplete(response, input.request)) yield* writeCache(file, response).pipe(Effect.ignore);
71
+ return response;
72
+ });
73
+ const decide = Effect.fn("decide")(function* decide(transport, input) {
74
+ yield* Effect.annotateCurrentSpan({ model: input.request.model });
75
+ const endpoint = yield* transport.endpoint(input.env);
76
+ const file = yield* cacheFile(endpoint, input.request);
77
+ const cached = yield* readCache(file, input.request);
78
+ yield* Effect.annotateCurrentSpan({ cached: Option.isSome(cached) });
79
+ if (Option.isSome(cached)) return {
80
+ response: cached.value,
81
+ cached: true
82
+ };
83
+ return {
84
+ response: yield* askAndStore(transport, {
85
+ endpoint,
86
+ file
87
+ }, input),
88
+ cached: false
89
+ };
90
+ });
91
+ const reasonOf = (error) => {
92
+ if (typeof error === "string") return error;
93
+ return messageOf(error);
94
+ };
95
+ const decideOne = (transport, input) => decide(transport, input).pipe(Effect.match({
96
+ onSuccess: ({ response, cached }) => ({
97
+ ok: true,
98
+ response,
99
+ cached
100
+ }),
101
+ onFailure: (error) => ({
102
+ ok: false,
103
+ reason: reasonOf(error)
104
+ })
105
+ }));
106
+ const decideEach = (transport, inputs) => Effect.all(pipe(inputs, Array.map((input) => decideOne(transport, input))), { concurrency: "unbounded" }).pipe(Effect.provide(workerServices));
107
+ const serveDecisions = (transport) => {
108
+ runAsWorker((inputs) => Effect.runPromise(decideEach(transport, inputs)));
109
+ };
110
+ export { serveDecisions as t };
111
+
112
+ //# sourceMappingURL=serve-decisions-pOSYU_8a.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-decisions-pOSYU_8a.mjs","names":["Fn","fileSystem","path","Arr"],"sources":["../src/cache.ts","../src/services.ts","../src/serve-decisions.ts"],"sourcesContent":["import { Clock, Effect, FileSystem, Option, Path, Schema, Function as Fn } from \"effect\";\nimport { Digest } from \"effect/crypto\";\n\nimport { AnswerSchema } from \"./answer.ts\";\nimport { parseVerdicts } from \"./request.ts\";\nimport type { DecisionRequest, DecisionResponse } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst CACHE_VERSION = 7;\nconst CACHE_DIR = [\"node_modules\", \".cache\", \"oxlint-plugin-decision\"] as const;\n\nconst encodeJson = (value: unknown): Effect.Effect<string> =>\n Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))(value).pipe(Effect.orDie);\n\nconst cacheFile = Effect.fn(\"cacheFile\")(function* cacheFile(\n endpoint: string,\n request: DecisionRequest,\n) {\n const digest = yield* Digest.Digest;\n const path = yield* Path.Path;\n const json = yield* encodeJson({ version: CACHE_VERSION, endpoint, request });\n const payload = new TextEncoder().encode(json);\n const hash = yield* digest.digestHex(Digest.sha256, payload);\n return path.resolve(...CACHE_DIR, `${hash}.json`);\n});\n\nconst CachedResponse = Schema.Struct({\n model: Schema.NonEmptyString,\n answers: Schema.Record(Schema.String, AnswerSchema),\n});\n\nconst decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));\n\nconst isComplete: {\n (request: DecisionRequest): (response: DecisionResponse) => boolean;\n (response: DecisionResponse, request: DecisionRequest): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\n ),\n);\n\nconst readCache = Effect.fn(\"readCache\")(function* readCache(\n file: string,\n request: DecisionRequest,\n) {\n const fs = yield* FileSystem.FileSystem;\n const text = yield* fs.readFileString(file).pipe(Effect.option);\n return text.pipe(\n Option.flatMap((raw): Option.Option<DecisionResponse> => decodeCached(raw)),\n Option.filter((response) => isComplete(response, request)),\n );\n});\n\nconst writeCache = Effect.fn(\"writeCache\")(function* writeCache(\n file: string,\n response: DecisionResponse,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const now = yield* Clock.currentTimeMillis;\n const temp = `${file}.tmp-${String(now)}`;\n const json = yield* encodeJson(response);\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, json);\n yield* fs.rename(temp, file);\n});\n\ntype CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n\n/** @internal */\nexport { CACHE_DIR, cacheFile, isComplete, readCache, writeCache };\n/** @internal */\nexport type { CacheServices };\n","import { layerDigest } from \"@effect/platform-node-shared/NodeCrypto\";\nimport { layer as fileSystem } from \"@effect/platform-node-shared/NodeFileSystem\";\nimport { layer as path } from \"@effect/platform-node-shared/NodePath\";\nimport { Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport { OtlpSerialization, OtlpTracer } from \"effect/observability\";\n\nconst tracing = OtlpTracer.layerFromConfig({\n resource: { serviceName: \"oxlint-plugin-decision\" },\n}).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));\n\nconst workerServices: [\n typeof fileSystem,\n typeof path,\n typeof layerDigest,\n typeof FetchHttpClient.layer,\n typeof tracing,\n] = [fileSystem, path, layerDigest, FetchHttpClient.layer, tracing];\n\n/** @internal */\nexport { workerServices };\n","import { Array as Arr, Effect, Option, pipe } from \"effect\";\nimport type { Config } from \"effect\";\nimport type { HttpClient } from \"effect/http\";\nimport { runAsWorker } from \"synckit\";\n\nimport { cacheFile, isComplete, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices } from \"./cache.ts\";\nimport type { AppServices } from \"./openrouter-app.ts\";\nimport { messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult, DecisionRequest, DecisionResponse } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\ntype Services = AppServices | CacheServices | HttpClient.HttpClient;\n\ntype Inputs = Arr.NonEmptyReadonlyArray<DecideInput>;\n\ninterface Transport {\n readonly endpoint: (env: DecideInput[\"env\"]) => Config.Config<string>;\n readonly wires: (request: DecisionRequest) => Arr.NonEmptyReadonlyArray<WireRequest>;\n readonly combine: (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ) => DecisionResponse;\n readonly send: (\n endpoint: string,\n wire: WireRequest,\n input: Pick<DecideInput, \"env\">,\n ) => Effect.Effect<DecisionResponse, Config.ConfigError | string, Services>;\n}\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n transport: Transport,\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n transport.wires(request),\n (wire) => transport.send(endpoint, wire, { env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return transport.combine(request, responses);\n});\n\nconst askAndStore = Effect.fn(\"askAndStore\")(function* askAndStore(\n transport: Transport,\n { endpoint, file }: Readonly<{ endpoint: string; file: string }>,\n input: DecideInput,\n) {\n const response = yield* ask(transport, endpoint, input);\n if (isComplete(response, input.request)) {\n yield* writeCache(file, response).pipe(Effect.ignore);\n }\n return response;\n});\n\nconst decide = Effect.fn(\"decide\")(function* decide(transport: Transport, input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* transport.endpoint(input.env);\n const file = yield* cacheFile(endpoint, input.request);\n const cached = yield* readCache(file, input.request);\n yield* Effect.annotateCurrentSpan({ cached: Option.isSome(cached) });\n if (Option.isSome(cached)) {\n return { response: cached.value, cached: true };\n }\n return { response: yield* askAndStore(transport, { endpoint, file }, input), cached: false };\n});\n\nconst reasonOf = (error: unknown): string => {\n if (typeof error === \"string\") {\n return error;\n }\n return messageOf(error);\n};\n\nconst decideOne = (\n transport: Transport,\n input: DecideInput,\n): Effect.Effect<DecideResult, never, Services> =>\n decide(transport, input).pipe(\n Effect.match({\n onSuccess: ({ response, cached }): DecideResult => ({ ok: true, response, cached }),\n onFailure: (error): DecideResult => ({ ok: false, reason: reasonOf(error) }),\n }),\n );\n\nconst decideEach = (\n transport: Transport,\n inputs: Inputs,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(transport, input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\nconst serveDecisions = (transport: Transport): void => {\n runAsWorker((inputs: Inputs): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.runPromise(decideEach(transport, inputs)),\n );\n};\n\n/** @internal */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ORDER, w as probabilityOfChoice, x as choiceOf } from "./runtime-CICpEidL.mjs";
2
+ import { Array, Boolean, Function, Number as Number$1, Option, Order, Predicate, Record, String as String$1, pipe } from "effect";
3
+ // src/location.ts
4
+ const DATA_FIRST_ARITY$3 = 2;
5
+ const DATA_FIRST_ARITY_3 = 3;
6
+ const CHOICE_OPTION_LIMIT = 254;
7
+ const FIRST_LINE$1 = 1;
8
+ const MINIMUM_WIDTH = 1;
9
+ const UNKNOWN_CHOICE = "unknown";
10
+ const sourceLines = (text) => String$1.split(text, /\r\n|[\n\r\u2028\u2029]/u);
11
+ const locates = (match) => Predicate.isNotUndefined(match.rule.location) && !match.truncated;
12
+ const EVERY_LINE = {
13
+ start: FIRST_LINE$1,
14
+ end: Number.POSITIVE_INFINITY
15
+ };
16
+ const isWithin = (line, within) => Number$1.between(line, {
17
+ minimum: within.start,
18
+ maximum: within.end
19
+ });
20
+ const rangeKey = ({ start, end }) => Boolean.match(start === end, {
21
+ onTrue: () => `L${String(start)}`,
22
+ onFalse: () => `L${String(start)}-L${String(end)}`
23
+ });
24
+ const rangeLabel = ({ start, end }) => Boolean.match(start === end, {
25
+ onTrue: () => `Line ${String(start)}`,
26
+ onFalse: () => `Lines ${String(start)} to ${String(end)}`
27
+ });
28
+ const rangeOf = (group) => ({
29
+ start: Array.headNonEmpty(group).line,
30
+ end: Array.lastNonEmpty(group).line
31
+ });
32
+ const numberedLines = (snippet) => pipe(sourceLines(snippet), Array.map((text, index) => ({
33
+ text,
34
+ line: Number$1.sum(index, FIRST_LINE$1)
35
+ })));
36
+ const locationCandidates = Function.dual(DATA_FIRST_ARITY$3, (snippet, within) => {
37
+ const lines = pipe(numberedLines(snippet), Array.filter(({ text, line }) => String$1.trim(text).length >= FIRST_LINE$1 && isWithin(line, within)));
38
+ const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));
39
+ return Record.fromEntries(pipe(Array.chunksOf(lines, width), Array.map((group) => {
40
+ const range = rangeOf(group);
41
+ return [rangeKey(range), range];
42
+ })));
43
+ });
44
+ const locationQuestion = Function.dual(DATA_FIRST_ARITY_3, (match, ref, candidates) => ({
45
+ type: "choice",
46
+ instructions: `Consider only the numbered source in state.snippets.${ref}. If it violates this rule, select the line (or range containing that line) to annotate. Rule: ${match.rule.question} Location: ${match.rule.location.question} If multiple violations exist, select the earliest one. Select ${UNKNOWN_CHOICE} if no violation exists or its location is unclear.`,
47
+ criteria: {
48
+ ...Record.fromEntries(pipe(Record.toEntries(candidates), Array.map(([key, range]) => [key, rangeLabel(range)]))),
49
+ [UNKNOWN_CHOICE]: "No clear source location for this violation"
50
+ }
51
+ }));
52
+ const validChoice = Function.dual(DATA_FIRST_ARITY$3, (answer, criteria) => Option.exists(choiceOf(answer), (chosen) => Record.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen))));
53
+ const selectedLocation = Function.dual(DATA_FIRST_ARITY_3, (answer, candidates, cutoff) => choiceOf(answer).pipe(Option.filter((chosen) => Option.exists(probabilityOfChoice(chosen), (probability) => Number$1.isGreaterThanOrEqualTo(probability, cutoff))), Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice]))));
54
+ const locationOfLine = Function.dual(DATA_FIRST_ARITY$3, (snippet, line) => {
55
+ const text = Option.getOrElse(Array.get(sourceLines(snippet), Number$1.decrement(line)), () => "");
56
+ return {
57
+ start: {
58
+ line,
59
+ column: Option.getOrElse(String$1.search(/\S/u)(text), () => Number$1.decrement(FIRST_LINE$1))
60
+ },
61
+ end: {
62
+ line,
63
+ column: String$1.trimEnd(text).length
64
+ }
65
+ };
66
+ });
67
+ // src/request.ts
68
+ const DATA_FIRST_ARITY$2 = 2;
69
+ const FIRST_LINE = 1;
70
+ const LOCATION_SUFFIX = "_location";
71
+ const TRUNCATION_MARKER = "/* ...truncated */";
72
+ const refAt = (index) => `s${String(index)}`;
73
+ const locationRefOf = (ref) => `${ref}${LOCATION_SUFFIX}`;
74
+ const snippetRefOf = (questionId) => Boolean.match(String$1.endsWith(LOCATION_SUFFIX)(questionId), {
75
+ onTrue: () => String$1.slice(Number$1.decrement(FIRST_LINE), -9)(questionId),
76
+ onFalse: () => questionId
77
+ });
78
+ const truncateSnippet = Function.dual(DATA_FIRST_ARITY$2, (text, maxChars) => Boolean.match(text.length <= maxChars, {
79
+ onTrue: () => text,
80
+ onFalse: () => `${String$1.slice(Number$1.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`
81
+ }));
82
+ const numbered = (snippet) => pipe(numberedLines(snippet), Array.map(({ text, line }) => `L${String(line)}| ${text}`), Array.join("\n"));
83
+ const contextNote = (match, ref) => {
84
+ if (Predicate.isUndefined(match.context)) return "";
85
+ return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;
86
+ };
87
+ const mainQuestionFor = (match, ref) => [ref, questionFor(match.rule.answer, `Consider only snippet "${ref}" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`)];
88
+ const questionsFor = (match, ref) => {
89
+ if (!locates(match)) return [mainQuestionFor(match, ref)];
90
+ return [mainQuestionFor(match, ref), [locationRefOf(ref), locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE))]];
91
+ };
92
+ const snippetFor = (match) => {
93
+ if (locates(match)) return numbered(match.snippet);
94
+ return match.snippet;
95
+ };
96
+ const contextsOf = (matches) => {
97
+ const contexts = pipe(matches, Array.flatMap((match, index) => Option.toArray(Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text]))));
98
+ if (Array.isReadonlyArrayEmpty(contexts)) return {};
99
+ return { contexts: Record.fromEntries(contexts) };
100
+ };
101
+ const buildRequest = Function.dual(DATA_FIRST_ARITY$2, (model, matches) => ({
102
+ model,
103
+ state: {
104
+ snippets: Record.fromEntries(pipe(matches, Array.map((match, index) => [refAt(index), snippetFor(match)]))),
105
+ ...contextsOf(matches)
106
+ },
107
+ questions: Record.fromEntries(pipe(matches, Array.flatMap((match, index) => questionsFor(match, refAt(index)))))
108
+ }));
109
+ const choiceQuestionsOf$1 = (request) => pipe(Record.toEntries(request.questions), Array.flatMap(([id, question]) => {
110
+ if (question.type === "choice") return [[id, question.criteria]];
111
+ return [];
112
+ }));
113
+ const mainQuestionsOf = (request) => pipe(Record.toEntries(request.questions), Array.filter(([id]) => !String$1.endsWith(LOCATION_SUFFIX)(id)));
114
+ const resultOf = (answers, [ref, question]) => [ref, Option.getOrThrowWith(verdictOf(question, answers[ref]), () => /* @__PURE__ */ new Error(`response has no valid answer for "${ref}"`))];
115
+ const parseVerdicts = Function.dual(DATA_FIRST_ARITY$2, (response, request) => {
116
+ const { model, answers } = Option.getOrThrowWith(Option.liftPredicate(response, ({ model: served }) => String$1.isNonEmpty(served)), () => /* @__PURE__ */ new Error("response has no model id"));
117
+ return {
118
+ model,
119
+ results: Record.fromEntries(pipe(mainQuestionsOf(request), Array.map((entry) => resultOf(answers, entry)))),
120
+ answers,
121
+ complete: pipe(choiceQuestionsOf$1(request), Array.every(([id, criteria]) => validChoice(answers[id], criteria)))
122
+ };
123
+ });
124
+ // src/wire-choice.ts
125
+ const DATA_FIRST_ARITY$1 = 2;
126
+ const RESPAN_MODELS = ["respan/"];
127
+ const OPTION_SEPARATOR = "__";
128
+ const CERTAIN = 1;
129
+ const NO_SEVERITY = "none";
130
+ const isRespan = (model) => pipe(RESPAN_MODELS, Array.some((prefix) => String$1.startsWith(prefix)(model)));
131
+ const optionIdOf = Function.dual(DATA_FIRST_ARITY$1, (id, label) => `${id}${OPTION_SEPARATOR}${label}`);
132
+ const isSeverityScale = (criteria) => pipe(Record.keys(criteria), Array.join(",")) === pipe(SEVERITY_ORDER, Array.join(","));
133
+ const levelsAboveNone = (criteria) => pipe(Record.toEntries(criteria), Array.filter(([label]) => label !== NO_SEVERITY));
134
+ const byYes = Order.mapInput(Order.Number, ({ yes }) => yes);
135
+ const scoreOf = (answers, id, label) => Option.map(noulOf(answers[optionIdOf(id, label)]), ({ noul }) => ({
136
+ label,
137
+ yes: noul
138
+ }));
139
+ const scoresOf = (answers, id, labels) => pipe(labels, Array.map((label) => scoreOf(answers, id, label)), Option.all, Option.flatMap((scores) => Option.liftPredicate(scores, Array.isArrayNonEmpty)));
140
+ const probabilitiesOf = (scores) => Record.fromEntries(pipe(scores, Array.map(({ label, yes }) => [label, yes])));
141
+ const choiceAnswer = (choice, probabilities) => ({
142
+ type: "choice",
143
+ choice,
144
+ probabilities
145
+ });
146
+ const bestLabel = (scores) => choiceAnswer(Array.max(scores, byYes).label, probabilitiesOf(scores));
147
+ const atLeast = (scores) => pipe(scores, Array.map(({ label }, index) => ({
148
+ label,
149
+ yes: Math.max(...pipe(scores.slice(index), Array.map(({ yes }) => yes)))
150
+ })));
151
+ const severityLevel = (scores) => {
152
+ const cumulative = atLeast(scores);
153
+ const probabilities = {
154
+ [NO_SEVERITY]: Number$1.subtract(CERTAIN, Array.headNonEmpty(cumulative).yes),
155
+ ...probabilitiesOf(cumulative)
156
+ };
157
+ const reached = pipe(cumulative, Array.findLast(({ yes }) => yes >= CONFIDENT));
158
+ return choiceAnswer(Option.match(reached, {
159
+ onNone: () => NO_SEVERITY,
160
+ onSome: ({ label }) => label
161
+ }), probabilities);
162
+ };
163
+ const labelsAsked = (criteria) => {
164
+ if (isSeverityScale(criteria)) return pipe(levelsAboveNone(criteria), Array.map(([label]) => label));
165
+ return Record.keys(criteria);
166
+ };
167
+ const choiceFromYesNo = (answers, [id, { criteria }]) => {
168
+ const collapse = Boolean.match(isSeverityScale(criteria), {
169
+ onTrue: () => severityLevel,
170
+ onFalse: () => bestLabel
171
+ });
172
+ return scoresOf(answers, id, labelsAsked(criteria)).pipe(Option.map((scores) => [id, collapse(scores)]), Option.toArray);
173
+ };
174
+ const choiceQuestionsOf = (request) => pipe(Record.toEntries(request.questions), Array.flatMap(([id, question]) => {
175
+ if (question.type === "choice") return [[id, question]];
176
+ return [];
177
+ }));
178
+ const collapseChoices = Function.dual(DATA_FIRST_ARITY$1, (request, answers) => ({
179
+ ...answers,
180
+ ...Record.fromEntries(pipe(choiceQuestionsOf(request), Array.flatMap((entry) => choiceFromYesNo(answers, entry))))
181
+ }));
182
+ const withChoices = Function.dual(DATA_FIRST_ARITY$1, (request, answers) => {
183
+ if (!isRespan(request.model)) return answers;
184
+ return collapseChoices(request, answers);
185
+ });
186
+ // src/wire.ts
187
+ const DATA_FIRST_ARITY = 2;
188
+ const sectionsOf = (name, entries) => pipe(Record.toEntries(entries), Array.map(([ref, text]) => `state.${name}.${ref}:\n${text}`));
189
+ const stateAsText = ({ snippets, contexts = {} }) => pipe([...sectionsOf("snippets", snippets), ...sectionsOf("contexts", contexts)], Array.join("\n\n"));
190
+ const only = (entries, ref) => Option.match(Option.fromUndefinedOr(entries[ref]), {
191
+ onNone: () => ({}),
192
+ onSome: (text) => ({ [ref]: text })
193
+ });
194
+ const stateOf = ({ snippets, contexts }, ref) => {
195
+ if (Predicate.isUndefined(contexts)) return { snippets: only(snippets, ref) };
196
+ return {
197
+ snippets: only(snippets, ref),
198
+ contexts: only(contexts, ref)
199
+ };
200
+ };
201
+ const optionText = (label, description) => Option.match(Option.fromNullishOr(description), {
202
+ onNone: () => `"${label}"`,
203
+ onSome: (text) => `"${label}" (${text})`
204
+ });
205
+ const labelQuestion = (instructions, label, description) => ({
206
+ type: "noul",
207
+ instructions: `${instructions} Does the label ${optionText(label, description)} fit?`
208
+ });
209
+ const levelQuestion = (instructions, label, description) => ({
210
+ type: "noul",
211
+ instructions: `${instructions} Is it at least as serious as ${optionText(label, description)}?`
212
+ });
213
+ const yesNoQuestionsOf = (id, { instructions, criteria }) => {
214
+ if (isSeverityScale(criteria)) return pipe(levelsAboveNone(criteria), Array.map(([label, description]) => [optionIdOf(id, label), levelQuestion(instructions, label, description)]));
215
+ return pipe(Record.toEntries(criteria), Array.map(([label, description]) => [optionIdOf(id, label), labelQuestion(instructions, label, description)]));
216
+ };
217
+ const asYesNo = ([id, question]) => {
218
+ if (question.type === "choice") return yesNoQuestionsOf(id, question);
219
+ return [[id, question]];
220
+ };
221
+ const yesNoRequestsFor = (request) => {
222
+ const bySnippet = Array.groupBy(Record.toEntries(request.questions), ([id]) => snippetRefOf(id));
223
+ const wires = pipe(Record.values(bySnippet), Array.map((questions) => {
224
+ const [[id]] = questions;
225
+ return {
226
+ model: request.model,
227
+ state: stateAsText(stateOf(request.state, snippetRefOf(id))),
228
+ questions: Record.fromEntries(pipe(questions, Array.flatMap((entry) => asYesNo(entry))))
229
+ };
230
+ }));
231
+ if (Array.isReadonlyArrayNonEmpty(wires)) return wires;
232
+ return [request];
233
+ };
234
+ const wireRequestsFor = (request) => {
235
+ if (isRespan(request.model)) return yesNoRequestsFor(request);
236
+ return [request];
237
+ };
238
+ const merging = (collapse) => (request, responses) => ({
239
+ ...Array.headNonEmpty(responses),
240
+ answers: collapse(request, pipe(responses, Array.flatMap(({ answers }) => Record.toEntries(answers)), Record.fromEntries))
241
+ });
242
+ const mergeResponses = Function.dual(DATA_FIRST_ARITY, merging(withChoices));
243
+ const mergeYesNo = Function.dual(DATA_FIRST_ARITY, merging(collapseChoices));
244
+ export { buildRequest as a, refAt as c, locates as d, locationCandidates as f, sourceLines as g, selectedLocation as h, yesNoRequestsFor as i, truncateSnippet as l, locationQuestion as m, mergeYesNo as n, locationRefOf as o, locationOfLine as p, wireRequestsFor as r, parseVerdicts as s, mergeResponses as t, EVERY_LINE as u };
245
+
246
+ //# sourceMappingURL=wire-BbVK3Q_K.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire-BbVK3Q_K.mjs","names":["DATA_FIRST_ARITY","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","choiceQuestionsOf","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","Num","Bool","Rec","Arr","Fn"],"sources":["../src/location.ts","../src/request.ts","../src/wire-choice.ts","../src/wire.ts"],"sourcesContent":["import type { Location } from \"@oxlint/plugins\";\nimport {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { choiceOf, probabilityOfChoice } from \"./answer.ts\";\nimport type { Answer, ChoiceQuestion, LineRange, RequestMatch, RuleLocation } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\nconst DATA_FIRST_ARITY_3 = 3;\nconst CHOICE_OPTION_LIMIT = 254;\nconst FIRST_LINE = 1;\nconst MINIMUM_WIDTH = 1;\nconst UNKNOWN_CHOICE = \"unknown\";\n\nconst sourceLines = (text: string): readonly string[] =>\n Str.split(text, /\\r\\n|[\\n\\r\\u2028\\u2029]/u);\n\ntype LocatedMatch = RequestMatch & {\n readonly rule: { readonly question: string; readonly location: RuleLocation };\n};\n\nconst locates = (match: RequestMatch): match is LocatedMatch =>\n Predicate.isNotUndefined(match.rule.location) && !match.truncated;\n\ninterface NumberedLine {\n readonly text: string;\n readonly line: number;\n}\n\nconst EVERY_LINE: LineRange = { start: FIRST_LINE, end: Number.POSITIVE_INFINITY };\n\nconst isWithin = (line: number, within: LineRange): boolean =>\n Num.between(line, { minimum: within.start, maximum: within.end });\n\nconst rangeKey = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `L${String(start)}`,\n onFalse: () => `L${String(start)}-L${String(end)}`,\n });\n\nconst rangeLabel = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `Line ${String(start)}`,\n onFalse: () => `Lines ${String(start)} to ${String(end)}`,\n });\n\nconst rangeOf = (group: Arr.NonEmptyReadonlyArray<NumberedLine>): LineRange => ({\n start: Arr.headNonEmpty(group).line,\n end: Arr.lastNonEmpty(group).line,\n});\n\nconst numberedLines = (snippet: string): readonly NumberedLine[] =>\n pipe(\n sourceLines(snippet),\n Arr.map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) })),\n );\n\nconst locationCandidates: {\n (within: LineRange): (snippet: string) => Readonly<Record<string, LineRange>>;\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>> => {\n const lines = pipe(\n numberedLines(snippet),\n Arr.filter(({ text, line }) => Str.trim(text).length >= FIRST_LINE && isWithin(line, within)),\n );\n const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));\n return Rec.fromEntries(\n pipe(\n Arr.chunksOf(lines, width),\n Arr.map((group) => {\n const range = rangeOf(group);\n return [rangeKey(range), range];\n }),\n ),\n );\n },\n);\n\nconst locationQuestion: {\n (\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): (match: LocatedMatch) => ChoiceQuestion;\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion => ({\n type: \"choice\",\n instructions: `Consider only the numbered source in state.snippets.${ref}. If it violates this rule, select the line (or range containing that line) to annotate. Rule: ${match.rule.question} Location: ${match.rule.location.question} If multiple violations exist, select the earliest one. Select ${UNKNOWN_CHOICE} if no violation exists or its location is unclear.`,\n criteria: {\n ...Rec.fromEntries(\n pipe(\n Rec.toEntries(candidates),\n Arr.map(([key, range]) => [key, rangeLabel(range)]),\n ),\n ),\n [UNKNOWN_CHOICE]: \"No clear source location for this violation\",\n },\n }),\n);\n\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst validChoice: {\n (criteria: ChoiceCriteria): (answer: Answer | undefined) => boolean;\n (answer: Answer | undefined, criteria: ChoiceCriteria): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (answer: Answer | undefined, criteria: ChoiceCriteria): boolean =>\n Option.exists(\n choiceOf(answer),\n (chosen) => Rec.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen)),\n ),\n);\n\nconst selectedLocation: {\n (\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): (answer: Answer | undefined) => Option.Option<LineRange>;\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange> =>\n choiceOf(answer).pipe(\n Option.filter((chosen) =>\n Option.exists(probabilityOfChoice(chosen), (probability) =>\n Num.isGreaterThanOrEqualTo(probability, cutoff),\n ),\n ),\n Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice])),\n ),\n);\n\nconst locationOfLine: {\n (line: number): (snippet: string) => Location;\n (snippet: string, line: number): Location;\n} = Fn.dual(DATA_FIRST_ARITY, (snippet: string, line: number): Location => {\n const text = Option.getOrElse(Arr.get(sourceLines(snippet), Num.decrement(line)), () => \"\");\n return {\n start: {\n line,\n column: Option.getOrElse(Str.search(/\\S/u)(text), () => Num.decrement(FIRST_LINE)),\n },\n end: { line, column: Str.trimEnd(text).length },\n };\n});\n\nexport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n numberedLines,\n selectedLocation,\n sourceLines,\n validChoice,\n};\nexport type { ChoiceCriteria, LocatedMatch, NumberedLine };\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { questionFor, verdictOf } from \"./answer.ts\";\nimport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationQuestion,\n numberedLines,\n validChoice,\n} from \"./location.ts\";\nimport type { ChoiceCriteria } from \"./location.ts\";\nimport type {\n Answers,\n DecisionRequest,\n DecisionResponse,\n Question,\n RequestMatch,\n Verdict,\n Verdicts,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst FIRST_LINE = 1;\nconst LOCATION_SUFFIX = \"_location\";\nconst TRUNCATION_MARKER = \"/* ...truncated */\";\n\nconst refAt = (index: number): string => `s${String(index)}`;\n\nconst locationRefOf = (ref: string): string => `${ref}${LOCATION_SUFFIX}`;\n\nconst snippetRefOf = (questionId: string): string =>\n Bool.match(Str.endsWith(LOCATION_SUFFIX)(questionId), {\n onTrue: () => Str.slice(Num.decrement(FIRST_LINE), -LOCATION_SUFFIX.length)(questionId),\n onFalse: () => questionId,\n });\n\nconst truncateSnippet: {\n (maxChars: number): (text: string) => string;\n (text: string, maxChars: number): string;\n} = Fn.dual(DATA_FIRST_ARITY, (text: string, maxChars: number): string =>\n Bool.match(text.length <= maxChars, {\n onTrue: () => text,\n onFalse: () => `${Str.slice(Num.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`,\n }),\n);\n\nconst numbered = (snippet: string): string =>\n pipe(\n numberedLines(snippet),\n Arr.map(({ text, line }) => `L${String(line)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n\nconst contextNote = (match: RequestMatch, ref: string): string => {\n if (Predicate.isUndefined(match.context)) {\n return \"\";\n }\n return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;\n};\n\nconst mainQuestionFor = (match: RequestMatch, ref: string): readonly [string, Question] => [\n ref,\n questionFor(\n match.rule.answer,\n `Consider only snippet \"${ref}\" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`,\n ),\n];\n\nconst questionsFor = (\n match: RequestMatch,\n ref: string,\n): readonly (readonly [string, Question])[] => {\n if (!locates(match)) {\n return [mainQuestionFor(match, ref)];\n }\n return [\n mainQuestionFor(match, ref),\n [\n locationRefOf(ref),\n locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE)),\n ],\n ];\n};\n\nconst snippetFor = (match: RequestMatch): string => {\n if (locates(match)) {\n return numbered(match.snippet);\n }\n return match.snippet;\n};\n\nconst contextsOf = (\n matches: readonly RequestMatch[],\n): Readonly<{ contexts?: Readonly<Record<string, string>> }> => {\n const contexts = pipe(\n matches,\n Arr.flatMap((match, index) =>\n Option.toArray(\n Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text] as const),\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(contexts)) {\n return {};\n }\n return { contexts: Rec.fromEntries(contexts) };\n};\n\nconst buildRequest: {\n (matches: readonly RequestMatch[]): (model: string) => DecisionRequest;\n (model: string, matches: readonly RequestMatch[]): DecisionRequest;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (model: string, matches: readonly RequestMatch[]): DecisionRequest => ({\n model,\n state: {\n snippets: Rec.fromEntries(\n pipe(\n matches,\n Arr.map((match, index) => [refAt(index), snippetFor(match)]),\n ),\n ),\n ...contextsOf(matches),\n },\n questions: Rec.fromEntries(\n pipe(\n matches,\n Arr.flatMap((match, index) => questionsFor(match, refAt(index))),\n ),\n ),\n }),\n);\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceCriteria])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question.criteria] as const];\n }\n return [];\n }),\n );\n\nconst mainQuestionsOf = (request: DecisionRequest): readonly (readonly [string, Question])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.filter(([id]) => !Str.endsWith(LOCATION_SUFFIX)(id)),\n );\n\nconst resultOf = (\n answers: Answers,\n [ref, question]: readonly [string, Question],\n): readonly [string, Verdict] => [\n ref,\n Option.getOrThrowWith(\n verdictOf(question, answers[ref]),\n () => new Error(`response has no valid answer for \"${ref}\"`),\n ),\n];\n\nconst parseVerdicts: {\n (request: DecisionRequest): (response: DecisionResponse) => Verdicts;\n (response: DecisionResponse, request: DecisionRequest): Verdicts;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): Verdicts => {\n const { model, answers } = Option.getOrThrowWith(\n Option.liftPredicate(response, ({ model: served }) => Str.isNonEmpty(served)),\n () => new Error(\"response has no model id\"),\n );\n const results = Rec.fromEntries(\n pipe(\n mainQuestionsOf(request),\n Arr.map((entry) => resultOf(answers, entry)),\n ),\n );\n const complete = pipe(\n choiceQuestionsOf(request),\n Arr.every(([id, criteria]) => validChoice(answers[id], criteria)),\n );\n return { model, results, answers, complete };\n});\n\nexport { buildRequest, locationRefOf, parseVerdicts, refAt, snippetRefOf, truncateSnippet };\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Order,\n pipe,\n Record as Rec,\n String as Str,\n Function as Fn,\n} from \"effect\";\n\nimport { SEVERITY_ORDER, noulOf } from \"./answer.ts\";\nimport { CONFIDENT } from \"./schema.ts\";\nimport type { Answers, ChoiceAnswer, ChoiceQuestion, DecisionRequest } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst RESPAN_MODELS = [\"respan/\"] as const;\nconst OPTION_SEPARATOR = \"__\";\nconst CERTAIN = 1;\nconst NO_SEVERITY = \"none\";\n\nconst isRespan = (model: string): boolean =>\n pipe(\n RESPAN_MODELS,\n Arr.some((prefix) => Str.startsWith(prefix)(model)),\n );\n\nconst optionIdOf: {\n (label: string): (id: string) => string;\n (id: string, label: string): string;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (id: string, label: string): string => `${id}${OPTION_SEPARATOR}${label}`,\n);\n\nconst isSeverityScale = (criteria: ChoiceCriteria): boolean =>\n pipe(Rec.keys(criteria), Arr.join(\",\")) === pipe(SEVERITY_ORDER, Arr.join(\",\"));\n\nconst levelsAboveNone = (criteria: ChoiceCriteria): readonly (readonly [string, string | null])[] =>\n pipe(\n Rec.toEntries(criteria),\n Arr.filter(([label]) => label !== NO_SEVERITY),\n );\n\ninterface Score {\n readonly label: string;\n readonly yes: number;\n}\n\nconst byYes = Order.mapInput(Order.Number, ({ yes }: Score) => yes);\n\nconst scoreOf = (answers: Answers, id: string, label: string): Option.Option<Score> =>\n Option.map(noulOf(answers[optionIdOf(id, label)]), ({ noul }) => ({ label, yes: noul }));\n\nconst scoresOf = (\n answers: Answers,\n id: string,\n labels: readonly string[],\n): Option.Option<Arr.NonEmptyReadonlyArray<Score>> =>\n pipe(\n labels,\n Arr.map((label) => scoreOf(answers, id, label)),\n Option.all,\n Option.flatMap((scores) => Option.liftPredicate(scores, Arr.isArrayNonEmpty)),\n );\n\nconst probabilitiesOf = (scores: readonly Score[]): Readonly<Record<string, number>> =>\n Rec.fromEntries(\n pipe(\n scores,\n Arr.map(({ label, yes }) => [label, yes]),\n ),\n );\n\nconst choiceAnswer = (\n choice: string,\n probabilities: Readonly<Record<string, number>>,\n): ChoiceAnswer => ({\n type: \"choice\",\n choice,\n probabilities,\n});\n\nconst bestLabel = (scores: Arr.NonEmptyReadonlyArray<Score>): ChoiceAnswer =>\n choiceAnswer(Arr.max(scores, byYes).label, probabilitiesOf(scores));\n\nconst atLeast = (scores: Arr.NonEmptyReadonlyArray<Score>): Arr.NonEmptyReadonlyArray<Score> =>\n pipe(\n scores,\n Arr.map(({ label }, index) => ({\n label,\n yes: Math.max(\n ...pipe(\n scores.slice(index),\n Arr.map(({ yes }) => yes),\n ),\n ),\n })),\n );\n\nconst severityLevel = (scores: Arr.NonEmptyReadonlyArray<Score>): ChoiceAnswer => {\n const cumulative = atLeast(scores);\n const probabilities = {\n [NO_SEVERITY]: Num.subtract(CERTAIN, Arr.headNonEmpty(cumulative).yes),\n ...probabilitiesOf(cumulative),\n };\n const reached = pipe(\n cumulative,\n Arr.findLast(({ yes }) => yes >= CONFIDENT),\n );\n return choiceAnswer(\n Option.match(reached, { onNone: () => NO_SEVERITY, onSome: ({ label }) => label }),\n probabilities,\n );\n};\n\nconst labelsAsked = (criteria: ChoiceCriteria): readonly string[] => {\n if (isSeverityScale(criteria)) {\n return pipe(\n levelsAboveNone(criteria),\n Arr.map(([label]) => label),\n );\n }\n return Rec.keys(criteria);\n};\n\nconst choiceFromYesNo = (\n answers: Answers,\n [id, { criteria }]: readonly [string, ChoiceQuestion],\n): readonly (readonly [string, ChoiceAnswer])[] => {\n const collapse = Bool.match(isSeverityScale(criteria), {\n onTrue: () => severityLevel,\n onFalse: () => bestLabel,\n });\n return scoresOf(answers, id, labelsAsked(criteria)).pipe(\n Option.map((scores) => [id, collapse(scores)] as const),\n Option.toArray,\n );\n};\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceQuestion])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question] as const];\n }\n return [];\n }),\n );\n\nconst collapseChoices: {\n (answers: Answers): (request: DecisionRequest) => Answers;\n (request: DecisionRequest, answers: Answers): Answers;\n} = Fn.dual(DATA_FIRST_ARITY, (request: DecisionRequest, answers: Answers): Answers => ({\n ...answers,\n ...Rec.fromEntries(\n pipe(\n choiceQuestionsOf(request),\n Arr.flatMap((entry) => choiceFromYesNo(answers, entry)),\n ),\n ),\n}));\n\nconst withChoices: {\n (answers: Answers): (request: DecisionRequest) => Answers;\n (request: DecisionRequest, answers: Answers): Answers;\n} = Fn.dual(DATA_FIRST_ARITY, (request: DecisionRequest, answers: Answers): Answers => {\n if (!isRespan(request.model)) {\n return answers;\n }\n return collapseChoices(request, answers);\n});\n\nexport { collapseChoices, isRespan, isSeverityScale, levelsAboveNone, optionIdOf, withChoices };\nexport type { ChoiceCriteria };\n","import { Array as Arr, Option, Predicate, pipe, Record as Rec, Function as Fn } from \"effect\";\n\nimport { snippetRefOf } from \"./request.ts\";\nimport type {\n ChoiceQuestion,\n DecisionRequest,\n DecisionResponse,\n NoulQuestion,\n Question,\n} from \"./types.ts\";\nimport {\n collapseChoices,\n isRespan,\n withChoices,\n isSeverityScale,\n levelsAboveNone,\n optionIdOf,\n} from \"./wire-choice.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\ntype State = DecisionRequest[\"state\"];\n\ninterface WireRequest extends Readonly<Pick<DecisionRequest, \"model\">> {\n readonly state: DecisionRequest[\"state\"] | string;\n readonly questions: Readonly<Record<string, Question>>;\n}\n\nconst sectionsOf = (name: string, entries: Readonly<Record<string, string>>): readonly string[] =>\n pipe(\n Rec.toEntries(entries),\n Arr.map(([ref, text]) => `state.${name}.${ref}:\\n${text}`),\n );\n\nconst stateAsText = ({ snippets, contexts = {} }: State): string =>\n pipe(\n [...sectionsOf(\"snippets\", snippets), ...sectionsOf(\"contexts\", contexts)],\n Arr.join(\"\\n\\n\"),\n );\n\nconst only = (\n entries: Readonly<Record<string, string>>,\n ref: string,\n): Readonly<Record<string, string>> =>\n Option.match(Option.fromUndefinedOr(entries[ref]), {\n onNone: () => ({}),\n onSome: (text) => ({ [ref]: text }),\n });\n\nconst stateOf = ({ snippets, contexts }: State, ref: string): State => {\n if (Predicate.isUndefined(contexts)) {\n return { snippets: only(snippets, ref) };\n }\n return { snippets: only(snippets, ref), contexts: only(contexts, ref) };\n};\n\nconst optionText = (label: string, description: string | null): string =>\n Option.match(Option.fromNullishOr(description), {\n onNone: () => `\"${label}\"`,\n onSome: (text) => `\"${label}\" (${text})`,\n });\n\nconst labelQuestion = (\n instructions: string,\n label: string,\n description: string | null,\n): NoulQuestion => ({\n type: \"noul\",\n instructions: `${instructions} Does the label ${optionText(label, description)} fit?`,\n});\n\nconst levelQuestion = (\n instructions: string,\n label: string,\n description: string | null,\n): NoulQuestion => ({\n type: \"noul\",\n instructions: `${instructions} Is it at least as serious as ${optionText(label, description)}?`,\n});\n\nconst yesNoQuestionsOf = (\n id: string,\n { instructions, criteria }: ChoiceQuestion,\n): readonly (readonly [string, NoulQuestion])[] => {\n if (isSeverityScale(criteria)) {\n return pipe(\n levelsAboveNone(criteria),\n Arr.map(([label, description]) => [\n optionIdOf(id, label),\n levelQuestion(instructions, label, description),\n ]),\n );\n }\n return pipe(\n Rec.toEntries(criteria),\n Arr.map(([label, description]) => [\n optionIdOf(id, label),\n labelQuestion(instructions, label, description),\n ]),\n );\n};\n\nconst asYesNo = ([id, question]: readonly [string, Question]): readonly (readonly [\n string,\n Question,\n])[] => {\n if (question.type === \"choice\") {\n return yesNoQuestionsOf(id, question);\n }\n return [[id, question]];\n};\n\nconst yesNoRequestsFor = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const bySnippet = Arr.groupBy(Rec.toEntries(request.questions), ([id]) => snippetRefOf(id));\n const wires = pipe(\n Rec.values(bySnippet),\n Arr.map((questions): WireRequest => {\n const [[id]] = questions;\n return {\n model: request.model,\n state: stateAsText(stateOf(request.state, snippetRefOf(id))),\n questions: Rec.fromEntries(\n pipe(\n questions,\n Arr.flatMap((entry) => asYesNo(entry)),\n ),\n ),\n };\n }),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n};\n\nconst wireRequestsFor = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n if (isRespan(request.model)) {\n return yesNoRequestsFor(request);\n }\n return [request];\n};\n\ntype Collapse = (\n request: DecisionRequest,\n answers: DecisionResponse[\"answers\"],\n) => DecisionResponse[\"answers\"];\n\nconst merging =\n (collapse: Collapse) =>\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse => ({\n ...Arr.headNonEmpty(responses),\n answers: collapse(\n request,\n pipe(\n responses,\n Arr.flatMap(({ answers }) => Rec.toEntries(answers)),\n Rec.fromEntries,\n ),\n ),\n });\n\ninterface Merge {\n (\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): (request: DecisionRequest) => DecisionResponse;\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse;\n}\n\nconst mergeResponses: Merge = Fn.dual(DATA_FIRST_ARITY, merging(withChoices));\n\nconst mergeYesNo: Merge = Fn.dual(DATA_FIRST_ARITY, merging(collapseChoices));\n\nexport { mergeResponses, mergeYesNo, wireRequestsFor, yesNoRequestsFor };\nexport type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C;CAC1F,MAAM,QAAQ,KACZA,OAAI,OAAO,SAAS,GACpBC,MAAI,KAAK,cAA2B;EAClC,MAAM,CAAC,CAAC,OAAO;EACf,OAAO;GACL,OAAO,QAAQ;GACf,OAAO,YAAY,QAAQ,QAAQ,OAAO,aAAa,EAAE,CAAC,CAAC;GAC3D,WAAWD,OAAI,YACb,KACE,WACAC,MAAI,SAAS,UAAU,QAAQ,KAAK,CAAC,CACvC,CACF;EACF;CACF,CAAC,CACH;CACA,IAAIA,MAAI,wBAAwB,KAAK,GACnC,OAAO;CAET,OAAO,CAAC,OAAO;AACjB;AAEA,MAAM,mBAAmB,YAAqE;CAC5F,IAAI,SAAS,QAAQ,KAAK,GACxB,OAAO,iBAAiB,OAAO;CAEjC,OAAO,CAAC,OAAO;AACjB;AAOA,MAAM,WACH,cAEC,SACA,eACsB;CACtB,GAAGA,MAAI,aAAa,SAAS;CAC7B,SAAS,SACP,SACA,KACE,WACAA,MAAI,SAAS,EAAE,cAAcD,OAAI,UAAU,OAAO,CAAC,GACnDA,OAAI,WACN,CACF;AACF;AAYF,MAAM,iBAAwBE,SAAG,KAAK,kBAAkB,QAAQ,WAAW,CAAC;AAE5E,MAAM,aAAoBA,SAAG,KAAK,kBAAkB,QAAQ,eAAe,CAAC"}
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "@r_masseater/oxlint-plugin-decision",
3
- "version": "0.3.0",
4
- "description": "Oxlint JS plugin that lints code with plain-English rules answered by decision models on OpenRouter.",
3
+ "version": "0.5.0",
4
+ "description": "Oxlint JS plugin that lints code with plain-English rules answered by models on Cloudflare AI Gateway or decision models on OpenRouter.",
5
5
  "keywords": [
6
+ "ai-gateway",
7
+ "cloudflare",
6
8
  "decision-model",
7
9
  "lint",
8
10
  "openrouter",
@@ -10,14 +12,14 @@
10
12
  "oxlint-plugin",
11
13
  "tanstack-intent"
12
14
  ],
13
- "homepage": "https://github.com/masseater/lint-kit/tree/main/libs/oxlint-plugin-decision#readme",
15
+ "homepage": "https://github.com/masseater/masseater.dev/tree/main/libs/oxlint-plugin-decision#readme",
14
16
  "bugs": {
15
- "url": "https://github.com/masseater/lint-kit/issues"
17
+ "url": "https://github.com/masseater/masseater.dev/issues"
16
18
  },
17
19
  "license": "MIT",
18
20
  "repository": {
19
21
  "type": "git",
20
- "url": "git+https://github.com/masseater/lint-kit.git",
22
+ "url": "git+https://github.com/masseater/masseater.dev.git",
21
23
  "directory": "libs/oxlint-plugin-decision"
22
24
  },
23
25
  "files": [
@@ -33,6 +35,10 @@
33
35
  "types": "./dist/index.d.mts",
34
36
  "default": "./dist/index.mjs"
35
37
  },
38
+ "./openrouter-app": {
39
+ "types": "./dist/openrouter-app.d.mts",
40
+ "default": "./dist/openrouter-app.mjs"
41
+ },
36
42
  "./package.json": "./package.json"
37
43
  },
38
44
  "publishConfig": {
@@ -40,22 +46,24 @@
40
46
  "provenance": true
41
47
  },
42
48
  "dependencies": {
43
- "@effect/platform-node": "4.1.2",
44
- "@openrouter/sdk": "1.5.33",
45
- "effect": "4.1.2",
49
+ "@effect/ai-openrouter": "4.1.4",
46
50
  "synckit": "0.12.3"
47
51
  },
48
52
  "devDependencies": {
49
- "@effect/tsgo": "0.67.4",
50
- "@effect/vitest": "4.1.2",
51
- "@oxlint/plugins": "1.90.0",
53
+ "@effect/platform-node": "4.1.4",
54
+ "@effect/platform-node-shared": "4.1.4",
55
+ "@effect/tsgo": "0.68.1",
56
+ "@effect/vitest": "4.1.4",
57
+ "@oxlint/plugins": "1.93.0",
52
58
  "@types/node": "26.6.6",
53
- "@vitest/coverage-v8": "5.1.0",
54
- "oxlint": "1.90.0",
59
+ "effect": "4.1.4",
60
+ "oxlint": "1.93.0",
55
61
  "typescript": "7.1.0-beta",
56
- "vite-plus": "1.5.0"
62
+ "vite-plus": "1.6.0"
57
63
  },
58
64
  "peerDependencies": {
65
+ "@effect/platform-node-shared": "^4.1.2",
66
+ "effect": "^4.1.2",
59
67
  "oxlint": ">=1.87.0"
60
68
  },
61
69
  "engines": {