@r_masseater/oxlint-plugin-decision 0.0.4 → 0.1.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.
@@ -1,16 +1,52 @@
1
- import { M as AnswerSchema, _ as messageOf, l as parseVerdicts, m as envNameOf, n as wireRequestsFor, t as mergeResponses } from "./wire-BGb5iQa9.mjs";
2
- import { Array, Config, Crypto, Effect, FileSystem, Layer, Option, Path, Redacted, Schema, String as String$1, pipe } from "effect";
1
+ import { M as AnswerSchema, _ as messageOf, l as parseVerdicts, m as envNameOf, n as wireRequestsFor, t as mergeResponses } from "./wire-XOgoBBuu.mjs";
2
+ import { Array, Config, Effect, FileSystem, Layer, Option, Path, Redacted, Schema, String as String$1, pipe } from "effect";
3
3
  import { runAsWorker } from "synckit";
4
4
  import { OpenRouterError } from "@openrouter/sdk/models/errors";
5
+ import { Digest } from "effect/crypto";
5
6
  import { OpenRouter } from "@openrouter/sdk";
6
7
  import { HTTPClient } from "@openrouter/sdk/lib/http.js";
7
- import { NodeServices } from "@effect/platform-node";
8
+ import { NodeCrypto, NodeServices } from "@effect/platform-node";
8
9
  import { FetchHttpClient } from "effect/http";
9
10
  import { OtlpSerialization, OtlpTracer } from "effect/observability";
10
- //#region src/client.ts
11
+ // src/cache.ts
12
+ const CACHE_VERSION = 7;
13
+ const CACHE_DIR = [
14
+ "node_modules",
15
+ ".cache",
16
+ "oxlint-plugin-decision"
17
+ ];
18
+ const cacheFile = Effect.fn("cacheFile")(function* cacheFile(endpoint, request) {
19
+ const digest = yield* Digest.Digest;
20
+ const path = yield* Path.Path;
21
+ const payload = new TextEncoder().encode(JSON.stringify({
22
+ version: CACHE_VERSION,
23
+ endpoint,
24
+ request
25
+ }));
26
+ const hash = yield* digest.digestHex(Digest.sha256, payload);
27
+ return path.resolve(...CACHE_DIR, `${hash}.json`);
28
+ });
29
+ const CachedResponse = Schema.Struct({
30
+ model: Schema.NonEmptyString,
31
+ answers: Schema.Record(Schema.String, AnswerSchema)
32
+ });
33
+ const decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));
34
+ const isComplete = (response, request) => Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(Option.getOrElse(() => false));
35
+ const readCache = Effect.fn("readCache")(function* readCache(file, request) {
36
+ return (yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.option)).pipe(Option.flatMap((raw) => decodeCached(raw)), Option.filter((response) => isComplete(response, request)));
37
+ });
38
+ const writeCache = Effect.fn("writeCache")(function* writeCache(file, response) {
39
+ const fs = yield* FileSystem.FileSystem;
40
+ const path = yield* Path.Path;
41
+ const temp = `${file}.tmp-${String(Date.now())}`;
42
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
43
+ yield* fs.writeFileString(temp, JSON.stringify(response));
44
+ yield* fs.rename(temp, file);
45
+ });
46
+ // src/client.ts
11
47
  const TOOL = "oxlint-plugin-decision";
12
48
  const GITHUB = "https://github.com";
13
- const SELF = "masseater/oxlint-plugin-decision";
49
+ const SELF = "masseater/lint-kit";
14
50
  const GIT_SUFFIX = /\.git\/?$/u;
15
51
  const SEPARATORS = /[/:]/u;
16
52
  const SLUG_PARTS = 2;
@@ -89,58 +125,23 @@ const clientFor = (apiKey) => attribution.pipe(Effect.map((app) => new OpenRoute
89
125
  apiKey,
90
126
  ...app
91
127
  })));
92
- //#endregion
93
- //#region src/services.ts
128
+ // src/services.ts
94
129
  const tracing = OtlpTracer.layerFromConfig({ resource: { serviceName: "oxlint-plugin-decision" } }).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
95
- const workerServices = [NodeServices.layer, tracing];
96
- //#endregion
97
- //#region src/openrouter-worker.ts
98
- const CACHE_VERSION = 7;
99
- const HEX_RADIX = 16;
100
- const HEX_BYTE_WIDTH = 2;
130
+ const workerServices = [
131
+ NodeServices.layer,
132
+ NodeCrypto.layerDigest,
133
+ tracing
134
+ ];
135
+ // src/openrouter-worker.ts
101
136
  const RETRY_INITIAL_MS = 10;
102
137
  const RETRY_EXPONENT = 2;
103
138
  const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
104
139
  const API_SUFFIX = /\/api\/v1\/*$|\/+$/u;
105
- const CACHE_DIR = [
106
- "node_modules",
107
- ".cache",
108
- "oxlint-plugin-decision"
109
- ];
110
140
  const reasonFor = (error) => {
111
141
  if (error instanceof OpenRouterError) return `http ${String(error.statusCode)}: ${error.message}`;
112
142
  return `network: ${messageOf(error)}`;
113
143
  };
114
144
  const serverUrlOf = (env) => Config.String(envNameOf(env, "OPENROUTER_BASE_URL")).pipe(Config.withDefault(DEFAULT_BASE_URL), Config.map((url) => url.trim().replace(API_SUFFIX, "")));
115
- const toHex = (bytes) => bytes.map((byte) => byte.toString(HEX_RADIX).padStart(HEX_BYTE_WIDTH, "0")).join("");
116
- const cacheFile = Effect.fn("cacheFile")(function* cacheFile(endpoint, request) {
117
- const crypto = yield* Crypto.Crypto;
118
- const path = yield* Path.Path;
119
- const payload = new TextEncoder().encode(JSON.stringify({
120
- version: CACHE_VERSION,
121
- endpoint,
122
- request
123
- }));
124
- const digest = yield* crypto.digest("SHA-256", payload);
125
- return path.resolve(...CACHE_DIR, `${toHex([...digest])}.json`);
126
- });
127
- const CachedResponse = Schema.Struct({
128
- model: Schema.NonEmptyString,
129
- answers: Schema.Record(Schema.String, AnswerSchema)
130
- });
131
- const decodeCached = Schema.decodeOption(Schema.fromJsonString(CachedResponse));
132
- const isComplete = (response, request) => Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(Option.getOrElse(() => false));
133
- const readCache = Effect.fn("readCache")(function* readCache(file, request) {
134
- return (yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.option)).pipe(Option.flatMap((raw) => decodeCached(raw)), Option.filter((response) => isComplete(response, request)));
135
- });
136
- const writeCache = Effect.fn("writeCache")(function* writeCache(file, response) {
137
- const fs = yield* FileSystem.FileSystem;
138
- const path = yield* Path.Path;
139
- const temp = `${file}.tmp-${String(Date.now())}`;
140
- yield* fs.makeDirectory(path.dirname(file), { recursive: true });
141
- yield* fs.writeFileString(temp, JSON.stringify(response));
142
- yield* fs.rename(temp, file);
143
- });
144
145
  const send = Effect.fn("send")(function* send(endpoint, decisionsRequest, { timeoutMs, env }) {
145
146
  const apiKey = yield* Config.Redacted(envNameOf(env, "OPENROUTER_API_KEY"));
146
147
  const client = yield* clientFor(Redacted.value(apiKey));
@@ -211,7 +212,6 @@ const decideOne = (input) => decide(input).pipe(Effect.match({
211
212
  const decideEach = (inputs) => Effect.all(pipe(inputs, Array.map((input) => decideOne(input))), { concurrency: "unbounded" }).pipe(Effect.provide(workerServices));
212
213
  const run = (inputs) => Effect.runPromise(decideEach(inputs));
213
214
  runAsWorker(run);
214
- //#endregion
215
215
  export {};
216
216
 
217
217
  //# sourceMappingURL=openrouter-worker.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"openrouter-worker.mjs","names":["Str","Arr","Arr"],"sources":["../src/client.ts","../src/services.ts","../src/openrouter-worker.ts"],"sourcesContent":["import { OpenRouter } from \"@openrouter/sdk\";\nimport { HTTPClient } from \"@openrouter/sdk/lib/http.js\";\nimport { Array as Arr, Config, Effect, FileSystem, Option, Path, String as Str } from \"effect\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst GITHUB = \"https://github.com\";\nconst SELF = \"masseater/oxlint-plugin-decision\";\nconst GIT_SUFFIX = /\\.git\\/?$/u;\nconst SEPARATORS = /[/:]/u;\nconst SLUG_PARTS = 2;\nconst GITDIR = /^gitdir:\\s*(?<dir>.+)$/mu;\nconst ORIGIN_URL = /\\[remote \"origin\"\\][^[]*?\\burl\\s*=\\s*(?<url>\\S+)/u;\n\nconst hiddenApp = (): HTTPClient =>\n new HTTPClient().addHook(\"beforeRequest\", (request) => {\n request.headers.set(\"X-OpenRouter-App-Visibility\", \"hidden\");\n });\n\nconst isSet = (name: string): Effect.Effect<boolean> =>\n Config.option(Config.NonEmptyString(name)).pipe(\n Effect.map(Option.isSome),\n Effect.orElseSucceed(() => false),\n );\n\nconst contextOf = Effect.gen(function* contextOf() {\n if (yield* isSet(\"GITHUB_ACTIONS\")) {\n return \"github-actions\";\n }\n if (yield* isSet(\"CLAUDE_CODE_REMOTE\")) {\n return \"claude-code-cloud\";\n }\n if (yield* isSet(\"CLAUDECODE\")) {\n return \"claude-code\";\n }\n return \"local\";\n});\n\nconst slugOf = (url: string): Option.Option<string> => {\n const parts = url\n .trim()\n .replace(GIT_SUFFIX, \"\")\n .split(SEPARATORS)\n .filter((part) => Str.isNonEmpty(part));\n if (parts.length < SLUG_PARTS) {\n return Option.none();\n }\n return Option.some(Arr.takeRight(parts, SLUG_PARTS).join(\"/\"));\n};\n\nconst captured = (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string> =>\n match.pipe(\n Option.flatMap((found) => Option.fromNullishOr(found.groups)),\n Option.flatMap((groups) => Option.fromNullishOr(groups[name])),\n );\n\nconst linkedGitDir = Effect.fn(\"linkedGitDir\")(function* linkedGitDir(dir: string, dotGit: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const text = yield* fs.readFileString(dotGit);\n return captured(Str.match(GITDIR)(text), \"dir\").pipe(\n Option.map((found) => path.resolve(dir, found.trim())),\n );\n});\n\ntype ClientServices = FileSystem.FileSystem | Path.Path;\n\nconst gitDirAt = Effect.fn(\"gitDirAt\")(function* gitDirAt(dir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const dotGit = path.join(dir, \".git\");\n const info = yield* fs.stat(dotGit).pipe(Effect.option);\n if (Option.isNone(info)) {\n return Option.none<string>();\n }\n if (info.value.type === \"Directory\") {\n return Option.some(dotGit);\n }\n return yield* linkedGitDir(dir, dotGit);\n});\n\nconst gitDirFrom = (dir: string): Effect.Effect<Option.Option<string>, unknown, ClientServices> =>\n Effect.gen(function* walk() {\n const path = yield* Path.Path;\n const here = yield* gitDirAt(dir);\n const parent = path.dirname(dir);\n if (Option.isSome(here) || parent === dir) {\n return here;\n }\n return yield* gitDirFrom(parent);\n });\n\nconst commonDirOf = Effect.fn(\"commonDirOf\")(function* commonDirOf(gitDir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const common = yield* fs.readFileString(path.join(gitDir, \"commondir\")).pipe(Effect.option);\n return Option.match(common, {\n onNone: () => gitDir,\n onSome: (relative) => path.resolve(gitDir, relative.trim()),\n });\n});\n\nconst remoteSlug = Effect.gen(function* remoteSlug() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const gitDir = yield* gitDirFrom(path.resolve(\".\"));\n if (Option.isNone(gitDir)) {\n return Option.none<string>();\n }\n const config = yield* fs.readFileString(path.join(yield* commonDirOf(gitDir.value), \"config\"));\n return captured(Str.match(ORIGIN_URL)(config), \"url\").pipe(Option.flatMap(slugOf));\n}).pipe(Effect.orElseSucceed(() => Option.none<string>()));\n\nconst repoOf = Effect.gen(function* repoOf() {\n const fromActions = yield* Config.option(Config.NonEmptyString(\"GITHUB_REPOSITORY\")).pipe(\n Effect.orElseSucceed(() => Option.none<string>()),\n );\n if (Option.isSome(fromActions)) {\n return fromActions;\n }\n return yield* remoteSlug;\n});\n\nconst attribution = Effect.gen(function* attribution() {\n const context = yield* contextOf;\n const repo = yield* repoOf;\n const slug = Option.getOrElse(repo, () => SELF);\n return {\n httpReferer: `${GITHUB}/${slug}/${TOOL}/${context}`,\n appTitle: `${Option.getOrElse(repo, () => \"unknown\")} ${context} ${TOOL}`,\n httpClient: hiddenApp(),\n };\n}).pipe(Effect.cached, Effect.runSync);\n\nconst clientFor = (apiKey: string): Effect.Effect<OpenRouter, never, ClientServices> =>\n attribution.pipe(Effect.map((app) => new OpenRouter({ apiKey, ...app })));\n\nexport { clientFor };\nexport type { ClientServices };\n","import { NodeServices } from \"@effect/platform-node\";\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: [typeof NodeServices.layer, typeof tracing] = [NodeServices.layer, tracing];\n\nexport { workerServices };\n","import { OpenRouterError } from \"@openrouter/sdk/models/errors\";\nimport {\n Array as Arr,\n Config,\n Crypto,\n Effect,\n FileSystem,\n Option,\n Path,\n Redacted,\n Schema,\n pipe,\n} from \"effect\";\nimport { runAsWorker } from \"synckit\";\n\nimport { AnswerSchema } from \"./answer.ts\";\nimport { clientFor } from \"./client.ts\";\nimport type { ClientServices } from \"./client.ts\";\nimport { parseVerdicts } from \"./request.ts\";\nimport { envNameOf, messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult, DecisionRequest, DecisionResponse } from \"./types.ts\";\nimport { mergeResponses, wireRequestsFor } from \"./wire.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst CACHE_VERSION = 7;\nconst HEX_RADIX = 16;\nconst HEX_BYTE_WIDTH = 2;\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\";\nconst API_SUFFIX = /\\/api\\/v1\\/*$|\\/+$/u;\nconst CACHE_DIR = [\"node_modules\", \".cache\", \"oxlint-plugin-decision\"] as const;\n\nconst reasonFor = (error: unknown): string => {\n if (error instanceof OpenRouterError) {\n return `http ${String(error.statusCode)}: ${error.message}`;\n }\n return `network: ${messageOf(error)}`;\n};\n\nconst serverUrlOf = (env: Readonly<Record<string, string>>): Config.Config<string> =>\n Config.String(envNameOf(env, \"OPENROUTER_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_BASE_URL),\n Config.map((url) => url.trim().replace(API_SUFFIX, \"\")),\n );\n\nconst toHex = (bytes: readonly number[]): string =>\n bytes.map((byte) => byte.toString(HEX_RADIX).padStart(HEX_BYTE_WIDTH, \"0\")).join(\"\");\n\nconst cacheFile = Effect.fn(\"cacheFile\")(function* cacheFile(\n endpoint: string,\n request: DecisionRequest,\n) {\n const crypto = yield* Crypto.Crypto;\n const path = yield* Path.Path;\n const payload = new TextEncoder().encode(\n JSON.stringify({ version: CACHE_VERSION, endpoint, request }),\n );\n const digest = yield* crypto.digest(\"SHA-256\", payload);\n return path.resolve(...CACHE_DIR, `${toHex([...digest])}.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 = (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\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 temp = `${file}.tmp-${String(Date.now())}`;\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, JSON.stringify(response));\n yield* fs.rename(temp, file);\n});\n\nconst send = Effect.fn(\"send\")(function* send(\n endpoint: string,\n decisionsRequest: WireRequest,\n { timeoutMs, env }: Pick<DecideInput, \"timeoutMs\" | \"env\">,\n) {\n const apiKey = yield* Config.Redacted(envNameOf(env, \"OPENROUTER_API_KEY\"));\n const client = yield* clientFor(Redacted.value(apiKey));\n return yield* Effect.tryPromise({\n try: (signal) =>\n client.alpha.decisions.create(\n { decisionsRequest },\n {\n serverURL: endpoint,\n retries: {\n strategy: \"backoff\",\n backoff: {\n initialInterval: RETRY_INITIAL_MS,\n maxInterval: timeoutMs,\n exponent: RETRY_EXPONENT,\n maxElapsedTime: timeoutMs,\n },\n retryConnectionErrors: false,\n },\n retryCodes: [\"429\", \"5XX\"],\n signal,\n },\n ),\n catch: reasonFor,\n });\n});\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n wireRequestsFor(request),\n (wire) => send(endpoint, wire, { timeoutMs, env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return mergeResponses(request, responses);\n});\n\nconst askAndStore = Effect.fn(\"askAndStore\")(function* askAndStore(\n endpoint: string,\n file: string,\n input: DecideInput,\n) {\n const response = yield* ask(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(input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* serverUrlOf(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(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 input: DecideInput,\n): Effect.Effect<\n DecideResult,\n never,\n ClientServices | Crypto.Crypto | FileSystem.FileSystem | Path.Path\n> =>\n decide(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 inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\nconst run = (\n inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> => Effect.runPromise(decideEach(inputs));\n\nrunAsWorker(run);\n"],"mappings":";;;;;;;;;;AAIA,MAAM,OAAO;AACb,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,SAAS;AACf,MAAM,aAAa;AAEnB,MAAM,kBACJ,IAAI,WAAW,CAAC,CAAC,QAAQ,kBAAkB,YAAY;CACrD,QAAQ,QAAQ,IAAI,+BAA+B,QAAQ;AAC7D,CAAC;AAEH,MAAM,SAAS,SACb,OAAO,OAAO,OAAO,eAAe,IAAI,CAAC,CAAC,CAAC,KACzC,OAAO,IAAI,OAAO,MAAM,GACxB,OAAO,oBAAoB,KAAK,CAClC;AAEF,MAAM,YAAY,OAAO,IAAI,UAAU,YAAY;CACjD,IAAI,OAAO,MAAM,gBAAgB,GAC/B,OAAO;CAET,IAAI,OAAO,MAAM,oBAAoB,GACnC,OAAO;CAET,IAAI,OAAO,MAAM,YAAY,GAC3B,OAAO;CAET,OAAO;AACT,CAAC;AAED,MAAM,UAAU,QAAuC;CACrD,MAAM,QAAQ,IACX,KAAK,CAAC,CACN,QAAQ,YAAY,EAAE,CAAC,CACvB,MAAM,UAAU,CAAC,CACjB,QAAQ,SAASA,SAAI,WAAW,IAAI,CAAC;CACxC,IAAI,MAAM,SAAS,YACjB,OAAO,OAAO,KAAK;CAErB,OAAO,OAAO,KAAKC,MAAI,UAAU,OAAO,UAAU,CAAC,CAAC,KAAK,GAAG,CAAC;AAC/D;AAEA,MAAM,YAAY,OA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nD,OAAO,OAAO,oBAAoB,EAAE,QAAQ,OAAO,OAAO,MAAM,EAAE,CAAC;CACnE,IAAI,OAAO,OAAO,MAAM,GACtB,OAAO;EAAE,UAAU,OAAO;EAAO,QAAQ;CAAK;CAEhD,OAAO;EAAE,UAAU,OAAO,YAAY,UAAU,MAAM,KAAK;EAAG,QAAQ;CAAM;AAC9E,CAAC;AAED,MAAM,YAAY,UAA2B;CAC3C,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,OAAO,UAAU,KAAK;AACxB;AAEA,MAAM,aACJ,UAMA,OAAO,KAAK,CAAC,CAAC,KACZ,OAAO,MAAM;CACX,YAAY,EAAE,UAAU,cAA4B;EAAE,IAAI;EAAM;EAAU;CAAO;CACjF,YAAY,WAAyB;EAAE,IAAI;EAAO,QAAQ,SAAS,KAAK;CAAE;AAC5E,CAAC,CACH;AAEF,MAAM,cACJ,WAEA,OAAO,IACL,KACE,QACAE,MAAI,KAAK,UAAU,UAAU,KAAK,CAAC,CACrC,GACA,EAAE,aAAa,YAAY,CAC7B,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC;AAEvC,MAAM,OACJ,WACqD,OAAO,WAAW,WAAW,MAAM,CAAC;AAE3F,YAAY,GAAG"}
1
+ {"version":3,"file":"openrouter-worker.mjs","names":["Str","Arr","Arr"],"sources":["../src/cache.ts","../src/client.ts","../src/services.ts","../src/openrouter-worker.ts"],"sourcesContent":["import { Effect, FileSystem, Option, Path, Schema } 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 CACHE_VERSION = 7;\nconst CACHE_DIR = [\"node_modules\", \".cache\", \"oxlint-plugin-decision\"] as const;\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 payload = new TextEncoder().encode(\n JSON.stringify({ version: CACHE_VERSION, endpoint, request }),\n );\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 = (response: DecisionResponse, request: DecisionRequest): boolean =>\n Option.liftThrowable(() => parseVerdicts(response, request).complete)().pipe(\n Option.getOrElse(() => false),\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 temp = `${file}.tmp-${String(Date.now())}`;\n yield* fs.makeDirectory(path.dirname(file), { recursive: true });\n yield* fs.writeFileString(temp, JSON.stringify(response));\n yield* fs.rename(temp, file);\n});\n\ntype CacheServices = Digest.Digest | FileSystem.FileSystem | Path.Path;\n\nexport { cacheFile, isComplete, readCache, writeCache };\nexport type { CacheServices };\n","import { OpenRouter } from \"@openrouter/sdk\";\nimport { HTTPClient } from \"@openrouter/sdk/lib/http.js\";\nimport { Array as Arr, Config, Effect, FileSystem, Option, Path, String as Str } from \"effect\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst GITHUB = \"https://github.com\";\nconst SELF = \"masseater/lint-kit\";\nconst GIT_SUFFIX = /\\.git\\/?$/u;\nconst SEPARATORS = /[/:]/u;\nconst SLUG_PARTS = 2;\nconst GITDIR = /^gitdir:\\s*(?<dir>.+)$/mu;\nconst ORIGIN_URL = /\\[remote \"origin\"\\][^[]*?\\burl\\s*=\\s*(?<url>\\S+)/u;\n\nconst hiddenApp = (): HTTPClient =>\n new HTTPClient().addHook(\"beforeRequest\", (request) => {\n request.headers.set(\"X-OpenRouter-App-Visibility\", \"hidden\");\n });\n\nconst isSet = (name: string): Effect.Effect<boolean> =>\n Config.option(Config.NonEmptyString(name)).pipe(\n Effect.map(Option.isSome),\n Effect.orElseSucceed(() => false),\n );\n\nconst contextOf = Effect.gen(function* contextOf() {\n if (yield* isSet(\"GITHUB_ACTIONS\")) {\n return \"github-actions\";\n }\n if (yield* isSet(\"CLAUDE_CODE_REMOTE\")) {\n return \"claude-code-cloud\";\n }\n if (yield* isSet(\"CLAUDECODE\")) {\n return \"claude-code\";\n }\n return \"local\";\n});\n\nconst slugOf = (url: string): Option.Option<string> => {\n const parts = url\n .trim()\n .replace(GIT_SUFFIX, \"\")\n .split(SEPARATORS)\n .filter((part) => Str.isNonEmpty(part));\n if (parts.length < SLUG_PARTS) {\n return Option.none();\n }\n return Option.some(Arr.takeRight(parts, SLUG_PARTS).join(\"/\"));\n};\n\nconst captured = (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string> =>\n match.pipe(\n Option.flatMap((found) => Option.fromNullishOr(found.groups)),\n Option.flatMap((groups) => Option.fromNullishOr(groups[name])),\n );\n\nconst linkedGitDir = Effect.fn(\"linkedGitDir\")(function* linkedGitDir(dir: string, dotGit: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const text = yield* fs.readFileString(dotGit);\n return captured(Str.match(GITDIR)(text), \"dir\").pipe(\n Option.map((found) => path.resolve(dir, found.trim())),\n );\n});\n\ntype ClientServices = FileSystem.FileSystem | Path.Path;\n\nconst gitDirAt = Effect.fn(\"gitDirAt\")(function* gitDirAt(dir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const dotGit = path.join(dir, \".git\");\n const info = yield* fs.stat(dotGit).pipe(Effect.option);\n if (Option.isNone(info)) {\n return Option.none<string>();\n }\n if (info.value.type === \"Directory\") {\n return Option.some(dotGit);\n }\n return yield* linkedGitDir(dir, dotGit);\n});\n\nconst gitDirFrom = (dir: string): Effect.Effect<Option.Option<string>, unknown, ClientServices> =>\n Effect.gen(function* walk() {\n const path = yield* Path.Path;\n const here = yield* gitDirAt(dir);\n const parent = path.dirname(dir);\n if (Option.isSome(here) || parent === dir) {\n return here;\n }\n return yield* gitDirFrom(parent);\n });\n\nconst commonDirOf = Effect.fn(\"commonDirOf\")(function* commonDirOf(gitDir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const common = yield* fs.readFileString(path.join(gitDir, \"commondir\")).pipe(Effect.option);\n return Option.match(common, {\n onNone: () => gitDir,\n onSome: (relative) => path.resolve(gitDir, relative.trim()),\n });\n});\n\nconst remoteSlug = Effect.gen(function* remoteSlug() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const gitDir = yield* gitDirFrom(path.resolve(\".\"));\n if (Option.isNone(gitDir)) {\n return Option.none<string>();\n }\n const config = yield* fs.readFileString(path.join(yield* commonDirOf(gitDir.value), \"config\"));\n return captured(Str.match(ORIGIN_URL)(config), \"url\").pipe(Option.flatMap(slugOf));\n}).pipe(Effect.orElseSucceed(() => Option.none<string>()));\n\nconst repoOf = Effect.gen(function* repoOf() {\n const fromActions = yield* Config.option(Config.NonEmptyString(\"GITHUB_REPOSITORY\")).pipe(\n Effect.orElseSucceed(() => Option.none<string>()),\n );\n if (Option.isSome(fromActions)) {\n return fromActions;\n }\n return yield* remoteSlug;\n});\n\nconst attribution = Effect.gen(function* attribution() {\n const context = yield* contextOf;\n const repo = yield* repoOf;\n const slug = Option.getOrElse(repo, () => SELF);\n return {\n httpReferer: `${GITHUB}/${slug}/${TOOL}/${context}`,\n appTitle: `${Option.getOrElse(repo, () => \"unknown\")} ${context} ${TOOL}`,\n httpClient: hiddenApp(),\n };\n}).pipe(Effect.cached, Effect.runSync);\n\nconst clientFor = (apiKey: string): Effect.Effect<OpenRouter, never, ClientServices> =>\n attribution.pipe(Effect.map((app) => new OpenRouter({ apiKey, ...app })));\n\nexport { clientFor };\nexport type { ClientServices };\n","import { NodeCrypto, NodeServices } from \"@effect/platform-node\";\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: [typeof NodeServices.layer, typeof NodeCrypto.layerDigest, typeof tracing] = [\n NodeServices.layer,\n NodeCrypto.layerDigest,\n tracing,\n];\n\nexport { workerServices };\n","import { OpenRouterError } from \"@openrouter/sdk/models/errors\";\nimport { Array as Arr, Config, Effect, Option, Redacted, pipe } from \"effect\";\nimport { runAsWorker } from \"synckit\";\n\nimport { cacheFile, isComplete, readCache, writeCache } from \"./cache.ts\";\nimport type { CacheServices } from \"./cache.ts\";\nimport { clientFor } from \"./client.ts\";\nimport type { ClientServices } from \"./client.ts\";\nimport { envNameOf, messageOf } from \"./runtime.ts\";\nimport { workerServices } from \"./services.ts\";\nimport type { DecideInput, DecideResult } from \"./types.ts\";\nimport { mergeResponses, wireRequestsFor } from \"./wire.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\";\nconst API_SUFFIX = /\\/api\\/v1\\/*$|\\/+$/u;\n\nconst reasonFor = (error: unknown): string => {\n if (error instanceof OpenRouterError) {\n return `http ${String(error.statusCode)}: ${error.message}`;\n }\n return `network: ${messageOf(error)}`;\n};\n\nconst serverUrlOf = (env: Readonly<Record<string, string>>): Config.Config<string> =>\n Config.String(envNameOf(env, \"OPENROUTER_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_BASE_URL),\n Config.map((url) => url.trim().replace(API_SUFFIX, \"\")),\n );\n\nconst send = Effect.fn(\"send\")(function* send(\n endpoint: string,\n decisionsRequest: WireRequest,\n { timeoutMs, env }: Pick<DecideInput, \"timeoutMs\" | \"env\">,\n) {\n const apiKey = yield* Config.Redacted(envNameOf(env, \"OPENROUTER_API_KEY\"));\n const client = yield* clientFor(Redacted.value(apiKey));\n return yield* Effect.tryPromise({\n try: (signal) =>\n client.alpha.decisions.create(\n { decisionsRequest },\n {\n serverURL: endpoint,\n retries: {\n strategy: \"backoff\",\n backoff: {\n initialInterval: RETRY_INITIAL_MS,\n maxInterval: timeoutMs,\n exponent: RETRY_EXPONENT,\n maxElapsedTime: timeoutMs,\n },\n retryConnectionErrors: false,\n },\n retryCodes: [\"429\", \"5XX\"],\n signal,\n },\n ),\n catch: reasonFor,\n });\n});\n\nconst ask = Effect.fn(\"ask\")(function* ask(\n endpoint: string,\n { request, timeoutMs, env }: DecideInput,\n) {\n const responses = yield* Effect.forEach(\n wireRequestsFor(request),\n (wire) => send(endpoint, wire, { timeoutMs, env }),\n { concurrency: \"unbounded\" },\n ).pipe(\n Effect.timeoutOrElse({\n duration: timeoutMs,\n orElse: () => Effect.fail(\"timeout\"),\n }),\n );\n return mergeResponses(request, responses);\n});\n\nconst askAndStore = Effect.fn(\"askAndStore\")(function* askAndStore(\n endpoint: string,\n file: string,\n input: DecideInput,\n) {\n const response = yield* ask(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(input: DecideInput) {\n yield* Effect.annotateCurrentSpan({ model: input.request.model });\n const endpoint = yield* serverUrlOf(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(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 input: DecideInput,\n): Effect.Effect<DecideResult, never, ClientServices | CacheServices> =>\n decide(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 inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Effect.Effect<Arr.NonEmptyReadonlyArray<DecideResult>> =>\n Effect.all(\n pipe(\n inputs,\n Arr.map((input) => decideOne(input)),\n ),\n { concurrency: \"unbounded\" },\n ).pipe(Effect.provide(workerServices));\n\nconst run = (\n inputs: Arr.NonEmptyReadonlyArray<DecideInput>,\n): Promise<Arr.NonEmptyReadonlyArray<DecideResult>> => Effect.runPromise(decideEach(inputs));\n\nrunAsWorker(run);\n"],"mappings":";;;;;;;;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,YAAY;CAAC;CAAgB;CAAU;AAAwB;AAErE,MAAM,YAAY,OAAO,GAAG,WAAW,CAAC,CAAC,UAAU,UACjD,UACA,SACA;CACA,MAAM,SAAS,OAAO,OAAO;CAC7B,MAAM,OAAO,OAAO,KAAK;CACzB,MAAM,UAAU,IAAI,YAAY,CAAC,CAAC,OAChC,KAAK,UAAU;EAAE,SAAS;EAAe;EAAU;CAAQ,CAAC,CAC9D;CACA,MAAM,OAAO,OAAO,OAAO,UAAU,OAAO,QAAQ,OAAO;CAC3D,OAAO,KAAK,QAAQ,GAAG,WAAW,GAAG,KAAK,MAAM;AAClD,CAAC;AAED,MAAM,iBAAiB,OAAO,OAAO;CACnC,OAAO,OAAO;CACd,SAAS,OAAO,OAAO,OAAO,QAAQ,YAAY;AACpD,CAAC;AAED,MAAM,eAAe,OAAO,aAAa,OAAO,eAAe,cAAc,CAAC;AAE9E,MAAM,cAAc,UAA4B,YAC9C,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AAY,MAAM,GAAG;CAC7C,MAAM,OAAO,OAAO,UAAU,UAAU,MAAM,OAAO;CACrD,MAAM,SAAS,OAAO,UAAU,MAAM,MAAM,OAAO;CACnD,OAAO,OAAO,oBAAoB,EAAE,QAAQ,OAAO,OAAO,MAAM,EAAE,CAAC;CACnE,IAAI,OAAO,OAAO,MAAM,GACtB,OAAO;EAAE,UAAU,OAAO;EAAO,QAAQ;CAAK;CAEhD,OAAO;EAAE,UAAU,OAAO,YAAY,UAAU,MAAM,KAAK;EAAG,QAAQ;CAAM;AAC9E,CAAC;AAED,MAAM,YAAY,UAA2B;CAC3C,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,OAAO,UAAU,KAAK;AACxB;AAEA,MAAM,aACJ,UAEA,OAAO,KAAK,CAAC,CAAC,KACZ,OAAO,MAAM;CACX,YAAY,EAAE,UAAU,cAA4B;EAAE,IAAI;EAAM;EAAU;CAAO;CACjF,YAAY,WAAyB;EAAE,IAAI;EAAO,QAAQ,SAAS,KAAK;CAAE;AAC5E,CAAC,CACH;AAEF,MAAM,cACJ,WAEA,OAAO,IACL,KACE,QACAE,MAAI,KAAK,UAAU,UAAU,KAAK,CAAC,CACrC,GACA,EAAE,aAAa,YAAY,CAC7B,CAAC,CAAC,KAAK,OAAO,QAAQ,cAAc,CAAC;AAEvC,MAAM,OACJ,WACqD,OAAO,WAAW,WAAW,MAAM,CAAC;AAE3F,YAAY,GAAG"}
@@ -1,19 +1,51 @@
1
1
  import { Array, Boolean, Cause, Config, Console, Effect, Exit, Number as Number$1, Option, Order, Predicate, Result, Schema, String as String$1, pipe } from "effect";
2
- //#region src/answer.ts
3
- const YES = "yes";
4
- const DEFAULT_MINIMUM = "warn";
2
+ // src/schema.ts
3
+ const NONE = 0;
5
4
  const MINIMUM_LABELS = 2;
6
- const SEVERITY_CRITERIA = {
7
- none: "No problem",
8
- info: "Worth noting, but not a problem",
9
- warn: "Likely a problem",
10
- error: "Clearly a problem"
11
- };
12
- const SEVERITY_ORDER = Object.keys(SEVERITY_CRITERIA);
13
- const Probability$1 = Schema.Number.check(Schema.isBetween({
5
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));
6
+ const Probability = Schema.Number.check(Schema.isBetween({
14
7
  minimum: 0,
15
8
  maximum: 1
16
9
  }));
10
+ const CONFIDENT = .8;
11
+ const Cutoff = Schema.Number.check(Schema.isBetween({
12
+ minimum: CONFIDENT,
13
+ maximum: 1
14
+ }, { message: `cutoff must be between ${CONFIDENT} and 1` }));
15
+ const TargetSchema = Schema.Literals([
16
+ "function",
17
+ "call",
18
+ "jsx",
19
+ "file"
20
+ ]);
21
+ const CiBehaviorSchema = Schema.Literals(["skip", "fail"]);
22
+ const ExplainSettingSchema = Schema.Union([Schema.Boolean, Schema.Literals(["text", "json"])]);
23
+ const EnclosingKindSchema = Schema.Literals([
24
+ "function",
25
+ "class",
26
+ "block"
27
+ ]);
28
+ const RuleContextSchema = Schema.Union([
29
+ Schema.Struct({ scope: Schema.Literals([
30
+ "node",
31
+ "file",
32
+ "comment"
33
+ ]) }),
34
+ Schema.Struct({
35
+ scope: Schema.Literal("lines"),
36
+ before: Schema.optionalKey(NonNegativeInt),
37
+ after: Schema.optionalKey(NonNegativeInt)
38
+ }),
39
+ Schema.Struct({
40
+ scope: Schema.Literal("enclosing"),
41
+ kind: EnclosingKindSchema
42
+ })
43
+ ]);
44
+ const SeveritySchema = Schema.Literals([
45
+ "info",
46
+ "warn",
47
+ "error"
48
+ ]);
17
49
  const Label = Schema.NonEmptyString;
18
50
  const BooleanAnswer = Schema.Struct({ kind: Schema.Literal("boolean") });
19
51
  const ClassifyAnswer = Schema.Struct({
@@ -23,17 +55,23 @@ const ClassifyAnswer = Schema.Struct({
23
55
  }).check(Schema.makeFilter(({ labels, report }) => report.every((label) => Object.hasOwn(labels, label)), { message: "every label in report must be one of labels" }));
24
56
  const SeverityAnswer = Schema.Struct({
25
57
  kind: Schema.Literal("severity"),
26
- minimum: Schema.optionalKey(Schema.Literals([
27
- "info",
28
- "warn",
29
- "error"
30
- ]))
58
+ minimum: Schema.optionalKey(SeveritySchema)
31
59
  });
32
60
  const RuleAnswerSchema = Schema.Union([
33
61
  BooleanAnswer,
34
62
  ClassifyAnswer,
35
63
  SeverityAnswer
36
64
  ]);
65
+ // src/answer.ts
66
+ const YES = "yes";
67
+ const DEFAULT_MINIMUM = "warn";
68
+ const SEVERITY_CRITERIA = {
69
+ none: "No problem",
70
+ info: "Worth noting, but not a problem",
71
+ warn: "Likely a problem",
72
+ error: "Clearly a problem"
73
+ };
74
+ const SEVERITY_ORDER = Object.keys(SEVERITY_CRITERIA);
37
75
  const BOOLEAN_ANSWER = { kind: "boolean" };
38
76
  const decodeAnswer = Schema.decodeUnknownResult(RuleAnswerSchema);
39
77
  const decodeRuleAnswer = (answer) => {
@@ -43,12 +81,12 @@ const decodeRuleAnswer = (answer) => {
43
81
  };
44
82
  const NoulAnswerSchema = Schema.Struct({
45
83
  type: Schema.Literal("noul"),
46
- noul: Probability$1
84
+ noul: Probability
47
85
  });
48
86
  const ChoiceAnswerSchema = Schema.Struct({
49
87
  type: Schema.Literal("choice"),
50
88
  choice: Schema.String,
51
- probabilities: Schema.optional(Schema.Record(Schema.String, Probability$1))
89
+ probabilities: Schema.optional(Schema.Record(Schema.String, Probability))
52
90
  });
53
91
  const AnswerSchema = Schema.Union([NoulAnswerSchema, ChoiceAnswerSchema]);
54
92
  const decodeNoul = Schema.decodeOption(NoulAnswerSchema);
@@ -91,8 +129,7 @@ const verdictOf = (question, answer) => {
91
129
  probability: noul
92
130
  })));
93
131
  };
94
- const rankOf = (label) => SEVERITY_ORDER.indexOf(label);
95
- const severityMatches = ({ minimum = DEFAULT_MINIMUM }, label) => rankOf(label) >= rankOf(minimum);
132
+ const severityMatches = ({ minimum = DEFAULT_MINIMUM }, label) => SEVERITY_ORDER.indexOf(label) >= SEVERITY_ORDER.indexOf(minimum);
96
133
  const answerMatches = (answer, label) => {
97
134
  switch (answer.kind) {
98
135
  case "classify": return answer.report.includes(label);
@@ -102,8 +139,7 @@ const answerMatches = (answer, label) => {
102
139
  }
103
140
  };
104
141
  const isReported = (rule, verdict) => verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer);
105
- //#endregion
106
- //#region src/options.ts
142
+ // src/options.ts
107
143
  const PREFIX = "oxlint-plugin-decision";
108
144
  const PROVIDER_SEPARATOR = "/";
109
145
  const FIRST_LINE$1 = 1;
@@ -144,65 +180,26 @@ const DEFAULTS = {
144
180
  const isSelector = (input) => Predicate.isFunction(input);
145
181
  const RULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
146
182
  const ModelSpecSchema = Schema.Union([Schema.NonEmptyString, Schema.NonEmptyArray(Schema.NonEmptyString)]);
147
- const NONE = 0;
148
- const ONE = 1;
149
- const EVEN_ODDS = .5;
150
- const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));
151
- const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(ONE));
183
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
152
184
  const RuleId = Schema.NonEmptyString.check(Schema.isPattern(RULE_ID, { message: "id must be lowercase words joined by hyphens" }));
153
- const Probability = Schema.Number.check(Schema.isBetween({
154
- minimum: NONE,
155
- maximum: ONE
156
- }));
157
- const LocationCutoff = Schema.Number.check(Schema.isBetween({
158
- minimum: EVEN_ODDS,
159
- maximum: ONE,
160
- exclusiveMinimum: true
161
- }));
162
- const RuleContextSchema = Schema.Union([
163
- Schema.Struct({ scope: Schema.Literals([
164
- "node",
165
- "file",
166
- "comment"
167
- ]) }),
168
- Schema.Struct({
169
- scope: Schema.Literal("lines"),
170
- before: Schema.optionalKey(NonNegativeInt),
171
- after: Schema.optionalKey(NonNegativeInt)
172
- }),
173
- Schema.Struct({
174
- scope: Schema.Literal("enclosing"),
175
- kind: Schema.Literals([
176
- "function",
177
- "class",
178
- "block"
179
- ])
180
- })
181
- ]);
182
- const ExplainSetting = Schema.Union([Schema.Boolean, Schema.Literals(["text", "json"])]);
183
185
  const OptionsSchema = Schema.Struct({
184
- ci: Schema.optionalKey(Schema.Literals(["skip", "fail"])),
186
+ ci: Schema.optionalKey(CiBehaviorSchema),
185
187
  timeoutMs: Schema.optionalKey(PositiveInt),
186
188
  maxSnippetChars: Schema.optionalKey(PositiveInt),
187
189
  model: Schema.optionalKey(ModelSpecSchema),
188
190
  env: Schema.optionalKey(Schema.Record(Schema.NonEmptyString, Schema.NonEmptyString)),
189
- explain: Schema.optionalKey(ExplainSetting)
191
+ explain: Schema.optionalKey(ExplainSettingSchema)
190
192
  });
191
193
  const RuleSchema = Schema.Struct({
192
194
  id: RuleId,
193
- target: Schema.Literals([
194
- "function",
195
- "call",
196
- "jsx",
197
- "file"
198
- ]),
195
+ target: TargetSchema,
199
196
  question: Schema.NonEmptyString,
200
- cutoff: Probability,
197
+ cutoff: Cutoff,
201
198
  message: Schema.optionalKey(Schema.NonEmptyString),
202
199
  select: Schema.optionalKey(Schema.declare(isSelector)),
203
200
  location: Schema.optionalKey(Schema.Struct({
204
201
  question: Schema.NonEmptyString,
205
- cutoff: LocationCutoff
202
+ cutoff: Cutoff
206
203
  })),
207
204
  model: Schema.optionalKey(ModelSpecSchema),
208
205
  context: Schema.optionalKey(RuleContextSchema),
@@ -291,8 +288,7 @@ const REPORT_LOC = {
291
288
  jsx: (node) => Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,
292
289
  file: (_node, text) => headOf(text, FIRST_LINE$1, FIRST_COLUMN)
293
290
  };
294
- //#endregion
295
- //#region src/runtime.ts
291
+ // src/runtime.ts
296
292
  const runOrElse = (effect, fallback) => Exit.match(Effect.runSyncExit(effect), {
297
293
  onSuccess: (value) => value,
298
294
  onFailure: (cause) => fallback(Cause.squash(cause))
@@ -310,8 +306,7 @@ const messageOf = (error) => {
310
306
  if (error instanceof Error) return error.message;
311
307
  return String(error);
312
308
  };
313
- //#endregion
314
- //#region src/request.ts
309
+ // src/request.ts
315
310
  const CHOICE_OPTION_LIMIT = 254;
316
311
  const FIRST_LINE = 1;
317
312
  const MINIMUM_WIDTH = 1;
@@ -427,12 +422,10 @@ const parseVerdicts = (response, request) => {
427
422
  complete: choiceQuestionsOf$1(request).every(([id, criteria]) => validChoice(answers[id], criteria))
428
423
  };
429
424
  };
430
- //#endregion
431
- //#region src/wire.ts
425
+ // src/wire.ts
432
426
  const RESPAN_MODELS = ["respan/"];
433
427
  const OPTION_SEPARATOR = "__";
434
428
  const CERTAIN = 1;
435
- const LIKELY = .5;
436
429
  const NO_SEVERITY = "none";
437
430
  const sectionsOf = (name, entries) => Object.entries(entries).map(([ref, text]) => `state.${name}.${ref}:\n${text}`);
438
431
  const stateAsText = ({ snippets, contexts = {} }) => [...sectionsOf("snippets", snippets), ...sectionsOf("contexts", contexts)].join("\n\n");
@@ -510,7 +503,7 @@ const severityLevel = (scores) => {
510
503
  [NO_SEVERITY]: Number$1.subtract(CERTAIN, Array.headNonEmpty(cumulative).yes),
511
504
  ...probabilitiesOf(cumulative)
512
505
  };
513
- const reached = pipe(cumulative, Array.findLast(({ yes }) => yes >= LIKELY));
506
+ const reached = pipe(cumulative, Array.findLast(({ yes }) => yes >= CONFIDENT));
514
507
  return choiceAnswer(Option.match(reached, {
515
508
  onNone: () => NO_SEVERITY,
516
509
  onSome: ({ label }) => label
@@ -542,7 +535,6 @@ const mergeResponses = (request, responses) => ({
542
535
  ...Array.headNonEmpty(responses),
543
536
  answers: withChoices(request, Object.fromEntries(responses.flatMap(({ answers }) => Object.entries(answers))))
544
537
  });
545
- //#endregion
546
538
  export { resolveOptions as A, REPORT_LOC as C, checked as D, checkRules as E, AnswerSchema as M, isReported as N, modelIdsOf as O, PREFIX as S, TARGET_NODE_TYPES as T, messageOf as _, locationCandidates as a, ModelSpecSchema as b, locationRefOf as c, selectedLocation as d, sourceLines as f, failsInCi as g, envOf as h, locates as i, snippetNodeFor as j, resolveModel as k, parseVerdicts as l, envNameOf as m, wireRequestsFor as n, locationOfLine as o, truncateSnippet as p, buildRequest as r, locationQuestion as s, mergeResponses as t, refAt as u, runOrElse as v, STRICT as w, OptionsError as x, warnOnce as y };
547
539
 
548
- //# sourceMappingURL=wire-BGb5iQa9.mjs.map
540
+ //# sourceMappingURL=wire-XOgoBBuu.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire-XOgoBBuu.mjs","names":["FIRST_LINE","Arr","Str","Str","Bool","Num","Arr","choiceQuestionsOf","Str","Arr","Num","Bool"],"sources":["../src/schema.ts","../src/answer.ts","../src/options.ts","../src/runtime.ts","../src/request.ts","../src/wire.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\nconst NONE = 0;\nconst MINIMUM_LABELS = 2;\n\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));\n\nconst Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }));\n\nconst CONFIDENT = 0.8;\n\nconst Cutoff = Schema.Number.check(\n Schema.isBetween(\n { minimum: CONFIDENT, maximum: 1 },\n { message: `cutoff must be between ${CONFIDENT} and 1` },\n ),\n);\n\nconst TargetSchema = Schema.Literals([\"function\", \"call\", \"jsx\", \"file\"]);\n\nconst CiBehaviorSchema = Schema.Literals([\"skip\", \"fail\"]);\n\nconst ExplainSettingSchema = Schema.Union([Schema.Boolean, Schema.Literals([\"text\", \"json\"])]);\n\nconst EnclosingKindSchema = Schema.Literals([\"function\", \"class\", \"block\"]);\n\nconst RuleContextSchema = Schema.Union([\n Schema.Struct({ scope: Schema.Literals([\"node\", \"file\", \"comment\"]) }),\n Schema.Struct({\n scope: Schema.Literal(\"lines\"),\n before: Schema.optionalKey(NonNegativeInt),\n after: Schema.optionalKey(NonNegativeInt),\n }),\n Schema.Struct({ scope: Schema.Literal(\"enclosing\"), kind: EnclosingKindSchema }),\n]);\n\nconst SeveritySchema = Schema.Literals([\"info\", \"warn\", \"error\"]);\n\nconst Label = Schema.NonEmptyString;\n\nconst BooleanAnswer = Schema.Struct({ kind: Schema.Literal(\"boolean\") });\n\nconst ClassifyAnswer = Schema.Struct({\n kind: Schema.Literal(\"classify\"),\n labels: Schema.Record(Label, Schema.String).check(Schema.isMinProperties(MINIMUM_LABELS)),\n report: Schema.NonEmptyArray(Label),\n}).check(\n Schema.makeFilter(({ labels, report }) => report.every((label) => Object.hasOwn(labels, label)), {\n message: \"every label in report must be one of labels\",\n }),\n);\n\nconst SeverityAnswer = Schema.Struct({\n kind: Schema.Literal(\"severity\"),\n minimum: Schema.optionalKey(SeveritySchema),\n});\n\nconst RuleAnswerSchema = Schema.Union([BooleanAnswer, ClassifyAnswer, SeverityAnswer]);\n\nexport {\n CONFIDENT,\n CiBehaviorSchema,\n Cutoff,\n EnclosingKindSchema,\n ExplainSettingSchema,\n Probability,\n RuleAnswerSchema,\n RuleContextSchema,\n SeveritySchema,\n TargetSchema,\n};\n","import { Option, Result, Schema } from \"effect\";\n\nimport { Probability, RuleAnswerSchema } from \"./schema.ts\";\nimport type {\n Answer,\n ChoiceAnswer,\n NoulAnswer,\n Question,\n RuleAnswer,\n Severity,\n Verdict,\n} from \"./types.ts\";\n\nconst YES = \"yes\";\nconst DEFAULT_MINIMUM: Severity = \"warn\";\n\nconst SEVERITY_CRITERIA = {\n none: \"No problem\",\n info: \"Worth noting, but not a problem\",\n warn: \"Likely a problem\",\n error: \"Clearly a problem\",\n} as const;\n\nconst SEVERITY_ORDER: readonly string[] = Object.keys(SEVERITY_CRITERIA);\n\nconst BOOLEAN_ANSWER: RuleAnswer = { kind: \"boolean\" };\n\nconst decodeAnswer = Schema.decodeUnknownResult(RuleAnswerSchema);\n\nconst decodeRuleAnswer = (answer: unknown): Result.Result<RuleAnswer, string> => {\n const decoded = decodeAnswer(answer);\n if (Result.isSuccess(decoded)) {\n return Result.succeed(decoded.success);\n }\n return Result.fail(decoded.failure.message);\n};\n\nconst NoulAnswerSchema = Schema.Struct({ type: Schema.Literal(\"noul\"), noul: Probability });\n\nconst ChoiceAnswerSchema = Schema.Struct({\n type: Schema.Literal(\"choice\"),\n choice: Schema.String,\n probabilities: Schema.optional(Schema.Record(Schema.String, Probability)),\n});\n\nconst AnswerSchema = Schema.Union([NoulAnswerSchema, ChoiceAnswerSchema]);\n\nconst decodeNoul = Schema.decodeOption(NoulAnswerSchema);\n\nconst decodeChoice = Schema.decodeOption(ChoiceAnswerSchema);\n\nconst isNoul = (answer: Answer): answer is NoulAnswer => answer.type === \"noul\";\n\nconst isChoice = (answer: Answer): answer is ChoiceAnswer => answer.type === \"choice\";\n\nconst noulOf = (answer: Answer | undefined): Option.Option<NoulAnswer> =>\n Option.fromUndefinedOr(answer).pipe(Option.filter(isNoul), Option.flatMap(decodeNoul));\n\nconst choiceOf = (answer: Answer | undefined): Option.Option<ChoiceAnswer> =>\n Option.fromUndefinedOr(answer).pipe(Option.filter(isChoice), Option.flatMap(decodeChoice));\n\nconst probabilityOfChoice = ({ choice, probabilities }: ChoiceAnswer): Option.Option<number> =>\n Option.fromUndefinedOr(probabilities).pipe(\n Option.flatMap((byLabel) => Option.fromUndefinedOr(byLabel[choice])),\n );\n\nconst questionFor = (answer: RuleAnswer, instructions: string): Question => {\n switch (answer.kind) {\n case \"classify\": {\n return {\n type: \"choice\",\n instructions: `${instructions} Select the label that fits best.`,\n criteria: answer.labels,\n };\n }\n case \"severity\": {\n return {\n type: \"choice\",\n instructions: `${instructions} Rate how serious the problem is, and select none if there is no problem.`,\n criteria: SEVERITY_CRITERIA,\n };\n }\n case \"boolean\": {\n return { type: \"noul\", instructions };\n }\n default: {\n return { type: \"noul\", instructions };\n }\n }\n};\n\nconst choiceVerdictOf = (\n criteria: Readonly<Record<string, unknown>>,\n answer: Answer | undefined,\n): Option.Option<Verdict> =>\n choiceOf(answer).pipe(\n Option.filter(({ choice }) => Object.hasOwn(criteria, choice)),\n Option.flatMap((chosen) =>\n Option.map(probabilityOfChoice(chosen), (probability) => ({\n answer: chosen.choice,\n probability,\n })),\n ),\n );\n\nconst verdictOf = (question: Question, answer: Answer | undefined): Option.Option<Verdict> => {\n if (question.type === \"choice\") {\n return choiceVerdictOf(question.criteria, answer);\n }\n return noulOf(answer).pipe(Option.map(({ noul }) => ({ answer: YES, probability: noul })));\n};\n\nconst severityMatches = (\n { minimum = DEFAULT_MINIMUM }: { readonly minimum?: Severity },\n label: string,\n): boolean => SEVERITY_ORDER.indexOf(label) >= SEVERITY_ORDER.indexOf(minimum);\n\nconst answerMatches = (answer: RuleAnswer, label: string): boolean => {\n switch (answer.kind) {\n case \"classify\": {\n return answer.report.includes(label);\n }\n case \"severity\": {\n return severityMatches(answer, label);\n }\n case \"boolean\": {\n return label === YES;\n }\n default: {\n return false;\n }\n }\n};\n\nconst isReported = (\n rule: { readonly answer: RuleAnswer; readonly cutoff: number },\n verdict: Verdict,\n): boolean => verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer);\n\nexport {\n AnswerSchema,\n BOOLEAN_ANSWER,\n SEVERITY_ORDER,\n choiceOf,\n decodeRuleAnswer,\n isReported,\n noulOf,\n probabilityOfChoice,\n questionFor,\n verdictOf,\n};\n","import type { Location } from \"@oxlint/plugins\";\nimport { Array as Arr, Option, Predicate, Result, Schema, String as Str } from \"effect\";\n\nimport { BOOLEAN_ANSWER, decodeRuleAnswer } from \"./answer.ts\";\nimport {\n CiBehaviorSchema,\n Cutoff,\n ExplainSettingSchema,\n RuleContextSchema,\n TargetSchema,\n} from \"./schema.ts\";\nimport type {\n AstNode,\n DecisionOptions,\n DecisionProvider,\n DecisionRule,\n ModelRef,\n ModelSpec,\n ResolvedOptions,\n ResolvedRule,\n RuleAnswer,\n Target,\n} from \"./types.ts\";\n\nconst PREFIX = \"oxlint-plugin-decision\";\nconst PROVIDER_SEPARATOR = \"/\";\nconst FIRST_LINE = 1;\nconst ONE_RULE = 1;\nconst FIRST_COLUMN = 0;\n\nconst 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 isNamedParentType = (type: string): type is keyof typeof NAMED_PARENTS =>\n Object.hasOwn(NAMED_PARENTS, 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\nconst snippetNodeFor = (node: AstNode): AstNode =>\n Option.fromNullishOr(node.parent).pipe(\n Option.filter((parent) => holdsAsName(parent, node)),\n Option.getOrElse((): AstNode => node),\n );\n\nconst DEFAULTS = {\n ci: \"fail\",\n timeoutMs: 10_000,\n maxSnippetChars: 4000,\n model: \"openrouter/~typesafe/jev-latest\",\n env: {},\n explain: false,\n} as const satisfies Required<DecisionOptions>;\n\nconst isSelector = (input: unknown): input is DecisionRule[\"select\"] => Predicate.isFunction(input);\n\nconst RULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\n\nconst ModelSpecSchema = Schema.Union([\n Schema.NonEmptyString,\n Schema.NonEmptyArray(Schema.NonEmptyString),\n]);\n\nconst ONE = 1;\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(ONE));\n\nconst RuleId = Schema.NonEmptyString.check(\n Schema.isPattern(RULE_ID, { message: \"id must be lowercase words joined by hyphens\" }),\n);\n\nconst OptionsSchema = Schema.Struct({\n ci: Schema.optionalKey(CiBehaviorSchema),\n timeoutMs: Schema.optionalKey(PositiveInt),\n maxSnippetChars: Schema.optionalKey(PositiveInt),\n model: Schema.optionalKey(ModelSpecSchema),\n env: Schema.optionalKey(Schema.Record(Schema.NonEmptyString, Schema.NonEmptyString)),\n explain: Schema.optionalKey(ExplainSettingSchema),\n});\n\nconst RuleSchema = Schema.Struct({\n id: RuleId,\n target: TargetSchema,\n question: Schema.NonEmptyString,\n cutoff: Cutoff,\n message: Schema.optionalKey(Schema.NonEmptyString),\n select: Schema.optionalKey(Schema.declare(isSelector)),\n location: Schema.optionalKey(Schema.Struct({ question: Schema.NonEmptyString, cutoff: Cutoff })),\n model: Schema.optionalKey(ModelSpecSchema),\n context: Schema.optionalKey(RuleContextSchema),\n answer: Schema.optionalKey(Schema.Unknown),\n});\n\nconst STRICT = { onExcessProperty: \"error\" } as const;\n\nconst decodeOptions = Schema.decodeUnknownResult(OptionsSchema, STRICT);\nconst decodeRule = Schema.decodeUnknownResult(RuleSchema, STRICT);\n\nclass OptionsError extends Error {\n public constructor(message: string) {\n super(`${PREFIX}: ${message}`);\n this.name = \"OptionsError\";\n }\n}\n\nconst modelIdsOf = (spec: ModelSpec): readonly string[] => Arr.dedupe(Arr.ensure(spec));\n\nconst splitModelId = (id: string): Option.Option<readonly [string, string]> => {\n const [provider, ...rest] = Str.split(id, PROVIDER_SEPARATOR);\n const model = rest.join(PROVIDER_SEPARATOR);\n return Option.liftPredicate(\n [provider, model] as const,\n ([left, right]) => Str.isNonEmpty(left) && Str.isNonEmpty(right),\n );\n};\n\nconst resolveModel = (\n id: string,\n providers: Readonly<Record<string, DecisionProvider>>,\n): ModelRef =>\n splitModelId(id).pipe(\n Option.flatMap(([name, model]) =>\n Option.map(Option.fromUndefinedOr(providers[name]), (provider) => ({\n id,\n provider,\n model,\n })),\n ),\n Option.getOrThrowWith(\n () =>\n new OptionsError(\n `model \"${id}\" must be \"<provider>/<model>\" with a provider from: ${Object.keys(providers).join(\", \")}`,\n ),\n ),\n );\n\nconst duplicateIdOf = (rules: readonly DecisionRule[]): Option.Option<string> =>\n Arr.findFirst(\n Object.entries(Arr.groupBy(rules, ({ id }) => id)),\n ([, same]) => same.length > ONE_RULE,\n ).pipe(Option.map(([id]) => id));\n\nconst answerOf = (rule: DecisionRule): RuleAnswer => {\n if (Predicate.isUndefined(rule.answer)) {\n return BOOLEAN_ANSWER;\n }\n return Result.getOrThrowWith(\n decodeRuleAnswer(rule.answer),\n (issue) => new OptionsError(`rule \"${rule.id}\" has an invalid answer: ${issue}`),\n );\n};\n\ntype Decode<Value> = (input: unknown) => Result.Result<Value, Schema.SchemaError>;\n\nconst checked = <Value>(decode: Decode<Value>, input: unknown, what: string): Value =>\n Result.getOrThrowWith(\n decode(input),\n (issue) => new OptionsError(`invalid ${what}: ${issue.message}`),\n );\n\nconst checkRule = (rule: DecisionRule): DecisionRule => {\n checked(decodeRule, rule, `rule \"${rule.id}\"`);\n if (Predicate.isNotUndefined(rule.location) && rule.target !== \"file\") {\n throw new OptionsError(\"location is supported only for file rules\");\n }\n answerOf(rule);\n return rule;\n};\n\nconst checkRules = (rules: readonly DecisionRule[]): readonly DecisionRule[] => {\n if (!Arr.isReadonlyArrayNonEmpty(rules)) {\n throw new OptionsError(\"rules must list at least one rule\");\n }\n Option.map(duplicateIdOf(rules), (duplicate) => {\n throw new OptionsError(`rule id \"${duplicate}\" is used more than once`);\n });\n return rules.map((rule) => checkRule(rule));\n};\n\nconst resolveRule =\n (fallback: ModelSpec, providers: Readonly<Record<string, DecisionProvider>>) =>\n (rule: DecisionRule): ResolvedRule => ({\n ...rule,\n answer: answerOf(rule),\n models: modelIdsOf(rule.model ?? fallback).map((id) => resolveModel(id, providers)),\n });\n\ninterface Sources {\n readonly options: DecisionOptions;\n readonly settings?: unknown;\n}\n\nconst settingsFrom = (settings: unknown): DecisionOptions => {\n if (Predicate.isUndefined(settings)) {\n return {};\n }\n return checked(decodeOptions, settings, \"settings\");\n};\n\nconst resolveOptions = (\n { options, settings }: Sources,\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n): ResolvedOptions => {\n const fromCode = checked(decodeOptions, options, \"createDecisionPlugin options\");\n const { model, ...merged } = { ...DEFAULTS, ...fromCode, ...settingsFrom(settings) };\n return {\n ci: merged.ci,\n timeoutMs: merged.timeoutMs,\n maxSnippetChars: merged.maxSnippetChars,\n env: merged.env,\n explain: merged.explain,\n rules: checkRules(rules).map((rule) => resolveRule(model, providers)(rule)),\n };\n};\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\nconst 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\nexport type { Decode, Sources };\nexport {\n checkRules,\n OptionsError,\n PREFIX,\n REPORT_LOC,\n ModelSpecSchema,\n STRICT,\n TARGET_NODE_TYPES,\n checked,\n modelIdsOf,\n resolveModel,\n resolveOptions,\n snippetNodeFor,\n};\n","import { Cause, Config, Console, Effect, Exit, Option, String as Str } from \"effect\";\n\nimport { PREFIX } from \"./options.ts\";\nimport type { ResolvedOptions } from \"./types.ts\";\n\nconst runOrElse = <Value>(\n effect: Effect.Effect<Value, unknown>,\n fallback: (error: unknown) => Value,\n): Value =>\n Exit.match(Effect.runSyncExit(effect), {\n onSuccess: (value) => value,\n onFailure: (cause) => fallback(Cause.squash(cause)),\n });\n\nconst envOf = (name: string): Option.Option<string> =>\n runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(\n Option.map((value) => value.trim()),\n Option.filter(Str.isNonEmpty),\n );\n\nconst envNameOf = (env: Readonly<Record<string, string>>, name: string): string =>\n env[name] ?? name;\n\nconst failsInCi = (options: ResolvedOptions): boolean =>\n options.ci === \"fail\" && Option.isSome(envOf(\"CI\"));\n\nconst warned = new Set<string>();\n\nconst warnOnce = (reason: string, message: string): void => {\n if (warned.has(reason)) {\n return;\n }\n warned.add(reason);\n Effect.runFork(Console.warn(`${PREFIX}: ${message}`));\n};\n\nconst messageOf = (error: unknown): string => {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n};\n\nexport { envNameOf, envOf, failsInCi, messageOf, runOrElse, warnOnce };\n","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} from \"effect\";\n\nimport { choiceOf, probabilityOfChoice, questionFor, verdictOf } from \"./answer.ts\";\nimport type {\n Answer,\n Answers,\n ChoiceQuestion,\n DecisionRequest,\n DecisionResponse,\n LineRange,\n Question,\n RequestMatch,\n RuleLocation,\n Verdict,\n Verdicts,\n} from \"./types.ts\";\n\nconst CHOICE_OPTION_LIMIT = 254;\nconst FIRST_LINE = 1;\nconst MINIMUM_WIDTH = 1;\nconst UNKNOWN_CHOICE = \"unknown\";\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(questionId.endsWith(LOCATION_SUFFIX), {\n onTrue: () => questionId.slice(Num.decrement(FIRST_LINE), -LOCATION_SUFFIX.length),\n onFalse: () => questionId,\n });\n\nconst truncateSnippet = (text: string, maxChars: number): string =>\n Bool.match(text.length <= maxChars, {\n onTrue: () => text,\n onFalse: () => `${text.slice(Num.decrement(FIRST_LINE), maxChars)}${TRUNCATION_MARKER}`,\n });\n\nconst sourceLines = (text: string): readonly string[] => text.split(/\\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 sourceLines(snippet).map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) }));\n\nconst locationCandidates = (\n snippet: string,\n within: LineRange = EVERY_LINE,\n): Readonly<Record<string, LineRange>> => {\n const lines = numberedLines(snippet).filter(\n ({ text, line }) => text.trim().length >= FIRST_LINE && isWithin(line, within),\n );\n const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));\n return Object.fromEntries(\n Arr.chunksOf(lines, width).map((group) => {\n const range = rangeOf(group);\n return [rangeKey(range), range];\n }),\n );\n};\n\nconst locationQuestion = (\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 ...Object.fromEntries(\n Object.entries(candidates).map(([key, range]) => [key, rangeLabel(range)]),\n ),\n [UNKNOWN_CHOICE]: \"No clear source location for this violation\",\n },\n});\n\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst validChoice = (answer: Answer | undefined, criteria: ChoiceCriteria): boolean =>\n Option.exists(\n choiceOf(answer),\n (chosen) =>\n Object.hasOwn(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen)),\n );\n\nconst selectedLocation = (\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\nconst locationOfLine = (snippet: string, line: number): Location => {\n const text = Option.getOrElse(Arr.get(sourceLines(snippet), Num.decrement(line)), () => \"\");\n return {\n start: { line, column: Math.max(Num.decrement(FIRST_LINE), text.search(/\\S/u)) },\n end: { line, column: text.trimEnd().length },\n };\n};\n\nconst numbered = (snippet: string): string =>\n numberedLines(snippet)\n .map(({ text, line }) => `L${String(line)}| ${text}`)\n .join(\"\\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 [locationRefOf(ref), locationQuestion(match, ref, locationCandidates(match.snippet))],\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 = matches.flatMap((match, index) =>\n Option.toArray(\n Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text] as const),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(contexts)) {\n return {};\n }\n return { contexts: Object.fromEntries(contexts) };\n};\n\nconst buildRequest = (model: string, matches: readonly RequestMatch[]): DecisionRequest => ({\n model,\n state: {\n snippets: Object.fromEntries(matches.map((match, index) => [refAt(index), snippetFor(match)])),\n ...contextsOf(matches),\n },\n questions: Object.fromEntries(\n matches.flatMap((match, index) => questionsFor(match, refAt(index))),\n ),\n});\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceCriteria])[] =>\n Object.entries(request.questions).flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question.criteria] as const];\n }\n return [];\n });\n\nconst mainQuestionsOf = (request: DecisionRequest): readonly (readonly [string, Question])[] =>\n Object.entries(request.questions).filter(([id]) => !id.endsWith(LOCATION_SUFFIX));\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 = (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 = Object.fromEntries(\n mainQuestionsOf(request).map((entry) => resultOf(answers, entry)),\n );\n const complete = choiceQuestionsOf(request).every(([id, criteria]) =>\n validChoice(answers[id], criteria),\n );\n return { model, results, answers, complete };\n};\n\nexport {\n buildRequest,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n locationRefOf,\n parseVerdicts,\n refAt,\n selectedLocation,\n snippetRefOf,\n sourceLines,\n truncateSnippet,\n};\nexport type { LocatedMatch };\n","import type { DecisionsRequest } from \"@openrouter/sdk/models\";\nimport {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Order,\n Predicate,\n pipe,\n} from \"effect\";\n\nimport { SEVERITY_ORDER, noulOf } from \"./answer.ts\";\nimport { snippetRefOf } from \"./request.ts\";\nimport { CONFIDENT } from \"./schema.ts\";\nimport type {\n Answers,\n ChoiceAnswer,\n ChoiceQuestion,\n DecisionRequest,\n DecisionResponse,\n NoulQuestion,\n Question,\n} from \"./types.ts\";\n\ntype State = DecisionRequest[\"state\"];\n\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\ninterface WireRequest extends Readonly<Pick<DecisionsRequest, \"model\" | \"state\" | \"questions\">> {\n readonly state: DecisionRequest[\"state\"] | string;\n readonly questions: Readonly<Record<string, Question>>;\n}\n\nconst RESPAN_MODELS = [\"respan/\"] as const;\nconst OPTION_SEPARATOR = \"__\";\nconst CERTAIN = 1;\nconst NO_SEVERITY = \"none\";\n\nconst sectionsOf = (name: string, entries: Readonly<Record<string, string>>): readonly string[] =>\n Object.entries(entries).map(([ref, text]) => `state.${name}.${ref}:\\n${text}`);\n\nconst stateAsText = ({ snippets, contexts = {} }: State): string =>\n [...sectionsOf(\"snippets\", snippets), ...sectionsOf(\"contexts\", contexts)].join(\"\\n\\n\");\n\nconst isRespan = (model: string): boolean =>\n RESPAN_MODELS.some((prefix) => model.startsWith(prefix));\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 optionIdOf = (id: string, label: string): string => `${id}${OPTION_SEPARATOR}${label}`;\n\nconst isSeverityScale = (criteria: ChoiceCriteria): boolean =>\n Object.keys(criteria).join(\",\") === SEVERITY_ORDER.join(\",\");\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 levelsAboveNone = (criteria: ChoiceCriteria): readonly (readonly [string, string | null])[] =>\n Object.entries(criteria).filter(([label]) => label !== NO_SEVERITY);\n\nconst yesNoQuestionsOf = (\n id: string,\n { instructions, criteria }: ChoiceQuestion,\n): readonly (readonly [string, NoulQuestion])[] => {\n if (isSeverityScale(criteria)) {\n return levelsAboveNone(criteria).map(([label, description]) => [\n optionIdOf(id, label),\n levelQuestion(instructions, label, description),\n ]);\n }\n return Object.entries(criteria).map(([label, description]) => [\n optionIdOf(id, label),\n labelQuestion(instructions, label, description),\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 perSnippet = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const wires = Object.values(\n Arr.groupBy(Object.entries(request.questions), ([id]) => snippetRefOf(id)),\n ).map((questions): WireRequest => {\n const [[id]] = questions;\n return {\n model: request.model,\n state: stateAsText(stateOf(request.state, snippetRefOf(id))),\n questions: Object.fromEntries(questions.flatMap((entry) => asYesNo(entry))),\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 perSnippet(request);\n }\n return [request];\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 Option.flatMap(Option.all(labels.map((label) => scoreOf(answers, id, label))), (scores) =>\n Option.liftPredicate(scores, Arr.isArrayNonEmpty),\n );\n\nconst probabilitiesOf = (scores: readonly Score[]): Readonly<Record<string, number>> =>\n Object.fromEntries(scores.map(({ label, yes }) => [label, yes]));\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(...scores.slice(index).map(({ yes }) => yes)),\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 levelsAboveNone(criteria).map(([label]) => label);\n }\n return Object.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 Object.entries(request.questions).flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question] as const];\n }\n return [];\n });\n\nconst withChoices = (request: DecisionRequest, answers: Answers): Answers => {\n if (!isRespan(request.model)) {\n return answers;\n }\n return {\n ...answers,\n ...Object.fromEntries(\n choiceQuestionsOf(request).flatMap((entry) => choiceFromYesNo(answers, entry)),\n ),\n };\n};\n\nconst mergeResponses = (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n): DecisionResponse => ({\n ...Arr.headNonEmpty(responses),\n answers: withChoices(\n request,\n Object.fromEntries(responses.flatMap(({ answers }) => Object.entries(answers))),\n ),\n});\n\nexport { mergeResponses, wireRequestsFor };\nexport type { WireRequest };\n"],"mappings":";;AAEA,MAAM,OAAO;AACb,MAAM,iBAAiB;AAEvB,MAAM,iBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,IAAI,CAAC;AAE3E,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAE,CAAC,CAAC;AAEpF,MAAM,YAAY;AAElB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