@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.
@@ -1,217 +1,45 @@
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
- import { runAsWorker } from "synckit";
4
- import { OpenRouterError } from "@openrouter/sdk/models/errors";
5
- import { Digest } from "effect/crypto";
6
- import { OpenRouter } from "@openrouter/sdk";
7
- import { HTTPClient } from "@openrouter/sdk/lib/http.js";
8
- import { NodeCrypto, NodeServices } from "@effect/platform-node";
9
- import { FetchHttpClient } from "effect/http";
10
- import { OtlpSerialization, OtlpTracer } from "effect/observability";
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
1
+ import { openRouterApp } from "./openrouter-app.mjs";
2
+ import { n as envNameOf } from "./runtime-CICpEidL.mjs";
3
+ import { t as serveDecisions } from "./serve-decisions-pOSYU_8a.mjs";
4
+ import { r as wireRequestsFor, t as mergeResponses } from "./wire-BbVK3Q_K.mjs";
5
+ import { Config, Effect, Option, Schedule, Schema, String as String$1 } from "effect";
6
+ import { make } from "@effect/ai-openrouter/OpenRouterClient";
7
+ import { HttpClient, HttpClientRequest } from "effect/http";
8
+ // src/decisions.ts
47
9
  const TOOL = "oxlint-plugin-decision";
48
- const GITHUB = "https://github.com";
49
- const SELF = "masseater/lint-kit";
50
- const GIT_SUFFIX = /\.git\/?$/u;
51
- const SEPARATORS = /[/:]/u;
52
- const SLUG_PARTS = 2;
53
- const GITDIR = /^gitdir:\s*(?<dir>.+)$/mu;
54
- const ORIGIN_URL = /\[remote "origin"\][^[]*?\burl\s*=\s*(?<url>\S+)/u;
55
- const hiddenApp = () => new HTTPClient().addHook("beforeRequest", (request) => {
56
- request.headers.set("X-OpenRouter-App-Visibility", "hidden");
57
- });
58
- const isSet = (name) => Config.option(Config.NonEmptyString(name)).pipe(Effect.map(Option.isSome), Effect.orElseSucceed(() => false));
59
- const contextOf = Effect.gen(function* contextOf() {
60
- if (yield* isSet("GITHUB_ACTIONS")) return "github-actions";
61
- if (yield* isSet("CLAUDE_CODE_REMOTE")) return "claude-code-cloud";
62
- if (yield* isSet("CLAUDECODE")) return "claude-code";
63
- return "local";
64
- });
65
- const slugOf = (url) => {
66
- const parts = url.trim().replace(GIT_SUFFIX, "").split(SEPARATORS).filter((part) => String$1.isNonEmpty(part));
67
- if (parts.length < SLUG_PARTS) return Option.none();
68
- return Option.some(Array.takeRight(parts, SLUG_PARTS).join("/"));
69
- };
70
- const captured = (match, name) => match.pipe(Option.flatMap((found) => Option.fromNullishOr(found.groups)), Option.flatMap((groups) => Option.fromNullishOr(groups[name])));
71
- const linkedGitDir = Effect.fn("linkedGitDir")(function* linkedGitDir(dir, dotGit) {
72
- const fs = yield* FileSystem.FileSystem;
73
- const path = yield* Path.Path;
74
- const text = yield* fs.readFileString(dotGit);
75
- return captured(String$1.match(GITDIR)(text), "dir").pipe(Option.map((found) => path.resolve(dir, found.trim())));
76
- });
77
- const gitDirAt = Effect.fn("gitDirAt")(function* gitDirAt(dir) {
78
- const fs = yield* FileSystem.FileSystem;
79
- const dotGit = (yield* Path.Path).join(dir, ".git");
80
- const info = yield* fs.stat(dotGit).pipe(Effect.option);
81
- if (Option.isNone(info)) return Option.none();
82
- if (info.value.type === "Directory") return Option.some(dotGit);
83
- return yield* linkedGitDir(dir, dotGit);
84
- });
85
- const gitDirFrom = (dir) => Effect.gen(function* walk() {
86
- const path = yield* Path.Path;
87
- const here = yield* gitDirAt(dir);
88
- const parent = path.dirname(dir);
89
- if (Option.isSome(here) || parent === dir) return here;
90
- return yield* gitDirFrom(parent);
91
- });
92
- const commonDirOf = Effect.fn("commonDirOf")(function* commonDirOf(gitDir) {
93
- const fs = yield* FileSystem.FileSystem;
94
- const path = yield* Path.Path;
95
- const common = yield* fs.readFileString(path.join(gitDir, "commondir")).pipe(Effect.option);
96
- return Option.match(common, {
97
- onNone: () => gitDir,
98
- onSome: (relative) => path.resolve(gitDir, relative.trim())
99
- });
100
- });
101
- const remoteSlug = Effect.gen(function* remoteSlug() {
102
- const fs = yield* FileSystem.FileSystem;
103
- const path = yield* Path.Path;
104
- const gitDir = yield* gitDirFrom(path.resolve("."));
105
- if (Option.isNone(gitDir)) return Option.none();
106
- const config = yield* fs.readFileString(path.join(yield* commonDirOf(gitDir.value), "config"));
107
- return captured(String$1.match(ORIGIN_URL)(config), "url").pipe(Option.flatMap(slugOf));
108
- }).pipe(Effect.orElseSucceed(() => Option.none()));
109
- const repoOf = Effect.gen(function* repoOf() {
110
- const fromActions = yield* Config.option(Config.NonEmptyString("GITHUB_REPOSITORY")).pipe(Effect.orElseSucceed(() => Option.none()));
111
- if (Option.isSome(fromActions)) return fromActions;
112
- return yield* remoteSlug;
113
- });
114
- const attribution = Effect.gen(function* attribution() {
115
- const context = yield* contextOf;
116
- const repo = yield* repoOf;
117
- const slug = Option.getOrElse(repo, () => SELF);
118
- return {
119
- httpReferer: `${GITHUB}/${slug}/${TOOL}/${context}`,
120
- appTitle: `${Option.getOrElse(repo, () => "unknown")} ${context} ${TOOL}`,
121
- httpClient: hiddenApp()
122
- };
123
- }).pipe(Effect.cached, Effect.runSync);
124
- const clientFor = (apiKey) => attribution.pipe(Effect.map((app) => new OpenRouter({
125
- apiKey,
126
- ...app
127
- })));
128
- // src/services.ts
129
- const tracing = OtlpTracer.layerFromConfig({ resource: { serviceName: "oxlint-plugin-decision" } }).pipe(Layer.provide(OtlpSerialization.layerJson), Layer.provide(FetchHttpClient.layer));
130
- const workerServices = [
131
- NodeServices.layer,
132
- NodeCrypto.layerDigest,
133
- tracing
134
- ];
135
- // src/openrouter-worker.ts
10
+ const API_PATH = "/api/v1";
136
11
  const RETRY_INITIAL_MS = 10;
137
12
  const RETRY_EXPONENT = 2;
138
- const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
139
- const API_SUFFIX = /\/api\/v1\/*$|\/+$/u;
140
- const reasonFor = (error) => {
141
- if (error instanceof OpenRouterError) return `http ${String(error.statusCode)}: ${error.message}`;
142
- return `network: ${messageOf(error)}`;
143
- };
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, "")));
145
- const send = Effect.fn("send")(function* send(endpoint, decisionsRequest, { timeoutMs, env }) {
13
+ const attribution = openRouterApp(TOOL).pipe(Effect.cached, Effect.runSync);
14
+ const ErrorBody = Schema.Struct({ error: Schema.Struct({ message: Schema.String }) });
15
+ const decodeErrorBody = Schema.decodeOption(Schema.fromJsonString(ErrorBody));
16
+ const serverMessageOf = (body, fallback) => Option.fromUndefinedOr(body).pipe(Option.flatMap(decodeErrorBody), Option.match({
17
+ onNone: () => fallback,
18
+ onSome: ({ error }) => error.message
19
+ }));
20
+ const reasonFor = ({ _tag, message, http }) => Option.fromUndefinedOr(http).pipe(Option.flatMap(({ response, body }) => Option.map(Option.fromUndefinedOr(response), ({ status }) => `http ${String(status)}: ${serverMessageOf(body, _tag)}`)), Option.getOrElse(() => `network: ${message}`));
21
+ const send = Effect.fn("send")(function* send(endpoint, decisionsRequest, { env }) {
146
22
  const apiKey = yield* Config.Redacted(envNameOf(env, "OPENROUTER_API_KEY"));
147
- const client = yield* clientFor(Redacted.value(apiKey));
148
- return yield* Effect.tryPromise({
149
- try: (signal) => client.alpha.decisions.create({ decisionsRequest }, {
150
- serverURL: endpoint,
151
- retries: {
152
- strategy: "backoff",
153
- backoff: {
154
- initialInterval: RETRY_INITIAL_MS,
155
- maxInterval: timeoutMs,
156
- exponent: RETRY_EXPONENT,
157
- maxElapsedTime: timeoutMs
158
- },
159
- retryConnectionErrors: false
160
- },
161
- retryCodes: ["429", "5XX"],
162
- signal
163
- }),
164
- catch: reasonFor
165
- });
166
- });
167
- const ask = Effect.fn("ask")(function* ask(endpoint, { request, timeoutMs, env }) {
168
- const responses = yield* Effect.forEach(wireRequestsFor(request), (wire) => send(endpoint, wire, {
169
- timeoutMs,
170
- env
171
- }), { concurrency: "unbounded" }).pipe(Effect.timeoutOrElse({
172
- duration: timeoutMs,
173
- orElse: () => Effect.fail("timeout")
174
- }));
175
- return mergeResponses(request, responses);
23
+ const headers = yield* attribution;
24
+ const [body] = yield* (yield* make({
25
+ apiKey,
26
+ apiUrl: `${endpoint}${API_PATH}`,
27
+ transformClient: (http) => http.pipe(HttpClient.mapRequest(HttpClientRequest.setHeaders(headers)), HttpClient.retryTransient({
28
+ retryOn: "response-only",
29
+ schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT)
30
+ }))
31
+ })).createDecisions(decisionsRequest).pipe(Effect.mapError(({ reason }) => reasonFor(reason)));
32
+ return body;
176
33
  });
177
- const askAndStore = Effect.fn("askAndStore")(function* askAndStore(endpoint, file, input) {
178
- const response = yield* ask(endpoint, input);
179
- if (isComplete(response, input.request)) yield* writeCache(file, response).pipe(Effect.ignore);
180
- return response;
181
- });
182
- const decide = Effect.fn("decide")(function* decide(input) {
183
- yield* Effect.annotateCurrentSpan({ model: input.request.model });
184
- const endpoint = yield* serverUrlOf(input.env);
185
- const file = yield* cacheFile(endpoint, input.request);
186
- const cached = yield* readCache(file, input.request);
187
- yield* Effect.annotateCurrentSpan({ cached: Option.isSome(cached) });
188
- if (Option.isSome(cached)) return {
189
- response: cached.value,
190
- cached: true
191
- };
192
- return {
193
- response: yield* askAndStore(endpoint, file, input),
194
- cached: false
195
- };
34
+ // src/openrouter-worker.ts
35
+ const DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
36
+ const API_SUFFIX = /\/api\/v1\/*$|\/+$/u;
37
+ serveDecisions({
38
+ endpoint: (env) => Config.String(envNameOf(env, "OPENROUTER_BASE_URL")).pipe(Config.withDefault(DEFAULT_BASE_URL), Config.map((url) => String$1.replace(API_SUFFIX, "")(String$1.trim(url)))),
39
+ wires: wireRequestsFor,
40
+ combine: mergeResponses,
41
+ send
196
42
  });
197
- const reasonOf = (error) => {
198
- if (typeof error === "string") return error;
199
- return messageOf(error);
200
- };
201
- const decideOne = (input) => decide(input).pipe(Effect.match({
202
- onSuccess: ({ response, cached }) => ({
203
- ok: true,
204
- response,
205
- cached
206
- }),
207
- onFailure: (error) => ({
208
- ok: false,
209
- reason: reasonOf(error)
210
- })
211
- }));
212
- const decideEach = (inputs) => Effect.all(pipe(inputs, Array.map((input) => decideOne(input))), { concurrency: "unbounded" }).pipe(Effect.provide(workerServices));
213
- const run = (inputs) => Effect.runPromise(decideEach(inputs));
214
- runAsWorker(run);
215
43
  export {};
216
44
 
217
45
  //# sourceMappingURL=openrouter-worker.mjs.map
@@ -1 +1 @@
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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Y,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":["makeOpenRouter","Str"],"sources":["../src/decisions.ts","../src/openrouter-worker.ts"],"sourcesContent":["import { make as makeOpenRouter } from \"@effect/ai-openrouter/OpenRouterClient\";\nimport { Config, Effect, Option, Schedule, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/http\";\n\nimport { openRouterApp } from \"./openrouter-app.ts\";\nimport { envNameOf } from \"./runtime.ts\";\nimport type { DecideInput } from \"./types.ts\";\nimport type { WireRequest } from \"./wire.ts\";\n\nconst TOOL = \"oxlint-plugin-decision\";\nconst API_PATH = \"/api/v1\";\nconst RETRY_INITIAL_MS = 10;\nconst RETRY_EXPONENT = 2;\n\nconst attribution = openRouterApp(TOOL).pipe(Effect.cached, Effect.runSync);\n\nconst ErrorBody = Schema.Struct({ error: Schema.Struct({ message: Schema.String }) });\n\nconst decodeErrorBody = Schema.decodeOption(Schema.fromJsonString(ErrorBody));\n\ninterface HttpFailure {\n readonly response?: { readonly status: number } | undefined;\n readonly body?: string | undefined;\n}\n\ninterface FailureReason {\n readonly _tag: string;\n readonly message: string;\n readonly http?: HttpFailure | undefined;\n}\n\nconst serverMessageOf = (body: string | undefined, fallback: string): string =>\n Option.fromUndefinedOr(body).pipe(\n Option.flatMap(decodeErrorBody),\n Option.match({ onNone: () => fallback, onSome: ({ error }) => error.message }),\n );\n\nconst reasonFor = ({ _tag, message, http }: FailureReason): string =>\n Option.fromUndefinedOr(http).pipe(\n Option.flatMap(({ response, body }) =>\n Option.map(\n Option.fromUndefinedOr(response),\n ({ status }) => `http ${String(status)}: ${serverMessageOf(body, _tag)}`,\n ),\n ),\n Option.getOrElse(() => `network: ${message}`),\n );\n\nconst send = Effect.fn(\"send\")(function* send(\n endpoint: string,\n decisionsRequest: WireRequest,\n { env }: Pick<DecideInput, \"env\">,\n) {\n const apiKey = yield* Config.Redacted(envNameOf(env, \"OPENROUTER_API_KEY\"));\n const headers = yield* attribution;\n const client = yield* makeOpenRouter({\n apiKey,\n apiUrl: `${endpoint}${API_PATH}`,\n transformClient: (http) =>\n http.pipe(\n HttpClient.mapRequest(HttpClientRequest.setHeaders(headers)),\n HttpClient.retryTransient({\n retryOn: \"response-only\",\n schedule: Schedule.exponential(RETRY_INITIAL_MS, RETRY_EXPONENT),\n }),\n ),\n });\n const [body] = yield* client\n .createDecisions(decisionsRequest)\n .pipe(Effect.mapError(({ reason }) => reasonFor(reason)));\n return body;\n});\n\n/** @internal */\nexport { send };\n","import { Config, String as Str } from \"effect\";\n\nimport { send } from \"./decisions.ts\";\nimport { envNameOf } from \"./runtime.ts\";\nimport { serveDecisions } from \"./serve-decisions.ts\";\nimport { mergeResponses, wireRequestsFor } from \"./wire.ts\";\n\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\";\nconst API_SUFFIX = /\\/api\\/v1\\/*$|\\/+$/u;\n\nserveDecisions({\n endpoint: (env) =>\n Config.String(envNameOf(env, \"OPENROUTER_BASE_URL\")).pipe(\n Config.withDefault(DEFAULT_BASE_URL),\n Config.map((url) => Str.replace(API_SUFFIX, \"\")(Str.trim(url))),\n ),\n wires: wireRequestsFor,\n combine: mergeResponses,\n send,\n});\n"],"mappings":";;;;;;;;AASA,MAAM,OAAO;AACb,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AAEvB,MAAM,cAAc,cAAc,IAAI,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,OAAO;AAE1E,MAAM,YAAY,OAA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,YAAY,gBAAgB,GACnC,OAAO,KAAK,QAAQC,SAAI,QAAQ,YAAY,EAAE,CAAC,CAACA,SAAI,KAAK,GAAG,CAAC,CAAC,CAChE;CACF,OAAO;CACP,SAAS;CACT;AACF,CAAC"}
@@ -0,0 +1,271 @@
1
+ import { Array, Cause, Config, Console, DateTime, Effect, Exit, Function, Option, Predicate, Record, Result, Schema, String as String$1, pipe } from "effect";
2
+ // src/schema.ts
3
+ const NONE = 0;
4
+ const MINIMUM_LABELS = 2;
5
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));
6
+ const Probability = Schema.Finite.check(Schema.isBetween({
7
+ minimum: 0,
8
+ maximum: 1
9
+ }));
10
+ const CONFIDENT = .8;
11
+ const Cutoff = Schema.Finite.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
+ ]);
49
+ const Label = Schema.NonEmptyString;
50
+ const BooleanAnswer = Schema.Struct({ kind: Schema.Literal("boolean") });
51
+ const ClassifyAnswer = Schema.Struct({
52
+ kind: Schema.Literal("classify"),
53
+ labels: Schema.Record(Label, Schema.String).check(Schema.isMinProperties(MINIMUM_LABELS)),
54
+ report: Schema.NonEmptyArray(Label)
55
+ }).check(Schema.makeFilter(({ labels, report }) => pipe(report, Array.every((label) => Record.has(labels, label))), { message: "every label in report must be one of labels" }));
56
+ const SeverityAnswer = Schema.Struct({
57
+ kind: Schema.Literal("severity"),
58
+ minimum: Schema.optionalKey(SeveritySchema)
59
+ });
60
+ const RuleAnswerSchema = Schema.Union([
61
+ BooleanAnswer,
62
+ ClassifyAnswer,
63
+ SeverityAnswer
64
+ ]);
65
+ // src/answer.ts
66
+ const DATA_FIRST_ARITY$2 = 2;
67
+ const YES = "yes";
68
+ const DEFAULT_MINIMUM = "warn";
69
+ const SEVERITY_CRITERIA = {
70
+ none: "No problem",
71
+ info: "Worth noting, but not a problem",
72
+ warn: "Likely a problem",
73
+ error: "Clearly a problem"
74
+ };
75
+ const SEVERITY_ORDER = Record.keys(SEVERITY_CRITERIA);
76
+ const BOOLEAN_ANSWER = { kind: "boolean" };
77
+ const decodeAnswer = Schema.decodeUnknownResult(RuleAnswerSchema);
78
+ const decodeRuleAnswer = (answer) => {
79
+ const decoded = decodeAnswer(answer);
80
+ if (Result.isSuccess(decoded)) return Result.succeed(decoded.success);
81
+ return Result.fail(decoded.failure.message);
82
+ };
83
+ const NoulAnswerSchema = Schema.Struct({
84
+ type: Schema.Literal("noul"),
85
+ noul: Probability
86
+ });
87
+ const ChoiceAnswerSchema = Schema.Struct({
88
+ type: Schema.Literal("choice"),
89
+ choice: Schema.String,
90
+ probabilities: Schema.optional(Schema.Record(Schema.String, Probability))
91
+ });
92
+ const AnswerSchema = Schema.Union([NoulAnswerSchema, ChoiceAnswerSchema]);
93
+ const decodeNoul = Schema.decodeOption(NoulAnswerSchema);
94
+ const decodeChoice = Schema.decodeOption(ChoiceAnswerSchema);
95
+ const isNoul = (answer) => answer.type === "noul";
96
+ const isChoice = (answer) => answer.type === "choice";
97
+ const noulOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.filter(isNoul), Option.flatMap(decodeNoul));
98
+ const choiceOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.filter(isChoice), Option.flatMap(decodeChoice));
99
+ const probabilityOfChoice = ({ choice, probabilities }) => Option.fromUndefinedOr(probabilities).pipe(Option.flatMap((byLabel) => Option.fromUndefinedOr(byLabel[choice])));
100
+ const questionFor = Function.dual(DATA_FIRST_ARITY$2, (answer, instructions) => {
101
+ switch (answer.kind) {
102
+ case "classify": return {
103
+ type: "choice",
104
+ instructions: `${instructions} Select the label that fits best.`,
105
+ criteria: answer.labels
106
+ };
107
+ case "severity": return {
108
+ type: "choice",
109
+ instructions: `${instructions} Rate how serious the problem is, and select none if there is no problem.`,
110
+ criteria: SEVERITY_CRITERIA
111
+ };
112
+ case "boolean": return {
113
+ type: "noul",
114
+ instructions
115
+ };
116
+ default: return {
117
+ type: "noul",
118
+ instructions
119
+ };
120
+ }
121
+ });
122
+ const choiceVerdictOf = (criteria, answer) => choiceOf(answer).pipe(Option.filter(({ choice }) => Record.has(criteria, choice)), Option.flatMap((chosen) => Option.map(probabilityOfChoice(chosen), (probability) => ({
123
+ answer: chosen.choice,
124
+ probability
125
+ }))));
126
+ const verdictOf = Function.dual(DATA_FIRST_ARITY$2, (question, answer) => {
127
+ if (question.type === "choice") return choiceVerdictOf(question.criteria, answer);
128
+ return noulOf(answer).pipe(Option.map(({ noul }) => ({
129
+ answer: YES,
130
+ probability: noul
131
+ })));
132
+ });
133
+ const severityMatches = ({ minimum = DEFAULT_MINIMUM }, label) => SEVERITY_ORDER.indexOf(label) >= SEVERITY_ORDER.indexOf(minimum);
134
+ const answerMatches = (answer, label) => {
135
+ switch (answer.kind) {
136
+ case "classify": return answer.report.includes(label);
137
+ case "severity": return severityMatches(answer, label);
138
+ case "boolean": return label === YES;
139
+ default: return false;
140
+ }
141
+ };
142
+ const isReported = Function.dual(DATA_FIRST_ARITY$2, (rule, verdict) => verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer));
143
+ // src/options.ts
144
+ const DATA_FIRST_ARITY_3 = 3;
145
+ const DATA_FIRST_ARITY$1 = 2;
146
+ const PREFIX = "oxlint-plugin-decision";
147
+ const PROVIDER_SEPARATOR = "/";
148
+ const ONE_RULE = 1;
149
+ const DEFAULTS = {
150
+ ci: "fail",
151
+ timeoutMs: 1e4,
152
+ maxSnippetChars: 4e3,
153
+ model: "cloudflare/@cf/qwen/qwen3.8-27b",
154
+ env: {},
155
+ explain: false
156
+ };
157
+ const isSelector = (input) => Predicate.isFunction(input);
158
+ const RULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
159
+ const ModelSpecSchema = Schema.Union([Schema.NonEmptyString, Schema.NonEmptyArray(Schema.NonEmptyString)]);
160
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
161
+ const RuleId = Schema.NonEmptyString.check(Schema.isPattern(RULE_ID, { message: "id must be lowercase words joined by hyphens" }));
162
+ const OptionsSchema = Schema.Struct({
163
+ ci: Schema.optionalKey(CiBehaviorSchema),
164
+ timeoutMs: Schema.optionalKey(PositiveInt),
165
+ maxSnippetChars: Schema.optionalKey(PositiveInt),
166
+ model: Schema.optionalKey(ModelSpecSchema),
167
+ env: Schema.optionalKey(Schema.Record(Schema.NonEmptyString, Schema.NonEmptyString)),
168
+ explain: Schema.optionalKey(ExplainSettingSchema)
169
+ });
170
+ const RuleSchema = Schema.Struct({
171
+ id: RuleId,
172
+ target: TargetSchema,
173
+ question: Schema.NonEmptyString,
174
+ cutoff: Cutoff,
175
+ message: Schema.optionalKey(Schema.NonEmptyString),
176
+ select: Schema.optionalKey(Schema.declare(isSelector)),
177
+ location: Schema.optionalKey(Schema.Struct({
178
+ question: Schema.NonEmptyString,
179
+ cutoff: Cutoff
180
+ })),
181
+ model: Schema.optionalKey(ModelSpecSchema),
182
+ context: Schema.optionalKey(RuleContextSchema),
183
+ answer: Schema.optionalKey(Schema.Unknown)
184
+ });
185
+ const STRICT = { onExcessProperty: "error" };
186
+ const decodeOptions = Schema.decodeUnknownResult(OptionsSchema, STRICT);
187
+ const decodeRule = Schema.decodeUnknownResult(RuleSchema, STRICT);
188
+ const taggedError = Schema.TaggedError;
189
+ var OptionsError = class extends taggedError()("OptionsError", { message: Schema.String }) {};
190
+ const optionsError = (message) => OptionsError.make({ message: `${PREFIX}: ${message}` });
191
+ const modelIdsOf = (spec) => Array.dedupe(Array.ensure(spec));
192
+ const splitModelId = (id) => {
193
+ const [provider, ...rest] = String$1.split(id, PROVIDER_SEPARATOR);
194
+ const model = pipe(rest, Array.join(PROVIDER_SEPARATOR));
195
+ return Option.liftPredicate([provider, model], ([left, right]) => String$1.isNonEmpty(left) && String$1.isNonEmpty(right));
196
+ };
197
+ const resolveModel = Function.dual(DATA_FIRST_ARITY$1, (id, providers) => splitModelId(id).pipe(Option.flatMap(([name, model]) => Option.map(Option.fromUndefinedOr(providers[name]), (provider) => ({
198
+ id,
199
+ provider,
200
+ model
201
+ }))), Option.getOrThrowWith(() => optionsError(`model "${id}" must be "<provider>/<model>" with a provider from: ${pipe(Record.keys(providers), Array.join(", "))}`))));
202
+ const duplicateIdOf = (rules) => Array.findFirst(Record.toEntries(Array.groupBy(rules, ({ id }) => id)), ([, same]) => same.length > ONE_RULE).pipe(Option.map(([id]) => id));
203
+ const answerOf = (rule) => {
204
+ if (Predicate.isUndefined(rule.answer)) return BOOLEAN_ANSWER;
205
+ return Result.getOrThrowWith(decodeRuleAnswer(rule.answer), (issue) => optionsError(`rule "${rule.id}" has an invalid answer: ${issue}`));
206
+ };
207
+ const checked = Function.dual(DATA_FIRST_ARITY_3, (decode, input, what) => Result.getOrThrowWith(decode(input), (issue) => optionsError(`invalid ${what}: ${issue.message}`)));
208
+ const checkRule = (rule) => {
209
+ checked(decodeRule, rule, `rule "${rule.id}"`);
210
+ if (Predicate.isNotUndefined(rule.location) && rule.target !== "file") throw optionsError("location is supported only for file rules");
211
+ answerOf(rule);
212
+ return rule;
213
+ };
214
+ const checkRules = (rules) => {
215
+ if (!Array.isReadonlyArrayNonEmpty(rules)) throw optionsError("rules must list at least one rule");
216
+ Option.map(duplicateIdOf(rules), (duplicate) => {
217
+ throw optionsError(`rule id "${duplicate}" is used more than once`);
218
+ });
219
+ return pipe(rules, Array.map((rule) => checkRule(rule)));
220
+ };
221
+ const resolveRule = (fallback, providers) => (rule) => ({
222
+ ...rule,
223
+ answer: answerOf(rule),
224
+ models: pipe(modelIdsOf(rule.model ?? fallback), Array.map((id) => resolveModel(id, providers)))
225
+ });
226
+ const settingsFrom = (settings) => {
227
+ if (Predicate.isUndefined(settings)) return {};
228
+ return checked(decodeOptions, settings, "settings");
229
+ };
230
+ const resolveOptions = Function.dual(DATA_FIRST_ARITY_3, ({ options, settings }, rules, providers) => {
231
+ const fromCode = checked(decodeOptions, options, "createDecisionPlugin options");
232
+ const { model, ...merged } = {
233
+ ...DEFAULTS,
234
+ ...fromCode,
235
+ ...settingsFrom(settings)
236
+ };
237
+ return {
238
+ ci: merged.ci,
239
+ timeoutMs: merged.timeoutMs,
240
+ maxSnippetChars: merged.maxSnippetChars,
241
+ env: merged.env,
242
+ explain: merged.explain,
243
+ rules: pipe(checkRules(rules), Array.map((rule) => resolveRule(model, providers)(rule)))
244
+ };
245
+ });
246
+ // src/runtime.ts
247
+ const DATA_FIRST_ARITY = 2;
248
+ const encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
249
+ const toJson = (value) => Option.getOrElse(encodeJson(value), () => String(value));
250
+ const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
251
+ const runOrElse = Function.dual(DATA_FIRST_ARITY, (effect, fallback) => Exit.match(Effect.runSyncExit(effect), {
252
+ onSuccess: (value) => value,
253
+ onFailure: (cause) => fallback(Cause.squash(cause))
254
+ }));
255
+ const envOf = (name) => runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(Option.map((value) => String$1.trim(value)), Option.filter(String$1.isNonEmpty));
256
+ const envNameOf = Function.dual(DATA_FIRST_ARITY, (env, name) => env[name] ?? name);
257
+ const failsInCi = (options) => options.ci === "fail" && Option.isSome(envOf("CI"));
258
+ const warned = /* @__PURE__ */ new Set();
259
+ const warnOnce = Function.dual(DATA_FIRST_ARITY, (reason, message) => {
260
+ if (warned.has(reason)) return;
261
+ warned.add(reason);
262
+ Effect.runFork(Console.warn(`${PREFIX}: ${message}`));
263
+ });
264
+ const messageOf = (error) => {
265
+ if (error instanceof Error) return error.message;
266
+ return String(error);
267
+ };
268
+ const captured = Function.dual(DATA_FIRST_ARITY, (match, name) => match.pipe(Option.flatMap((found) => Option.fromNullishOr(found.groups)), Option.flatMap((groups) => Option.fromNullishOr(groups[name]))));
269
+ export { noulOf as C, CONFIDENT as D, verdictOf as E, isReported as S, questionFor as T, resolveModel as _, messageOf as a, SEVERITY_ORDER as b, toJson as c, PREFIX as d, STRICT as f, optionsError as g, modelIdsOf as h, failsInCi as i, warnOnce as l, checked as m, envNameOf as n, nowMs as o, checkRules as p, envOf as r, runOrElse as s, captured as t, ModelSpecSchema as u, resolveOptions as v, probabilityOfChoice as w, choiceOf as x, AnswerSchema as y };
270
+
271
+ //# sourceMappingURL=runtime-CICpEidL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-CICpEidL.mjs","names":["Arr","Rec","DATA_FIRST_ARITY","Rec","Fn","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","Fn","Str"],"sources":["../src/schema.ts","../src/answer.ts","../src/options.ts","../src/runtime.ts"],"sourcesContent":["import { Schema, Array as Arr, Record as Rec, pipe } from \"effect\";\n\nconst NONE = 0;\nconst MINIMUM_LABELS = 2;\n\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(NONE));\n\nconst Probability = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }));\n\nconst CONFIDENT = 0.8;\n\nconst Cutoff = Schema.Finite.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(\n ({ labels, report }) =>\n pipe(\n report,\n Arr.every((label) => Rec.has(labels, label)),\n ),\n {\n message: \"every label in report must be one of labels\",\n },\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, Record as Rec, Function as Fn } 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 DATA_FIRST_ARITY = 2;\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[] = Rec.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} satisfies Partial<Record<keyof ChoiceAnswer, Schema.Top>>);\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: {\n (instructions: string): (answer: RuleAnswer) => Question;\n (answer: RuleAnswer, instructions: string): Question;\n} = Fn.dual(DATA_FIRST_ARITY, (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 }) => Rec.has(criteria, choice)),\n Option.flatMap((chosen) =>\n Option.map(probabilityOfChoice(chosen), (probability) => ({\n answer: chosen.choice,\n probability,\n })),\n ),\n );\n\nconst verdictOf: {\n (answer: Answer | undefined): (question: Question) => Option.Option<Verdict>;\n (question: Question, answer: Answer | undefined): Option.Option<Verdict>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (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);\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 (verdict: Verdict): (rule: { readonly answer: RuleAnswer; readonly cutoff: number }) => boolean;\n (rule: { readonly answer: RuleAnswer; readonly cutoff: number }, verdict: Verdict): boolean;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (rule: { readonly answer: RuleAnswer; readonly cutoff: number }, verdict: Verdict): boolean =>\n verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer),\n);\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 {\n Array as Arr,\n Option,\n Predicate,\n Result,\n Schema,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} 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 DecisionOptions,\n DecisionProvider,\n DecisionRule,\n ModelRef,\n ModelSpec,\n ResolvedOptions,\n ResolvedRule,\n RuleAnswer,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY_3 = 3;\n\nconst DATA_FIRST_ARITY = 2;\n\nconst PREFIX = \"oxlint-plugin-decision\";\nconst PROVIDER_SEPARATOR = \"/\";\nconst ONE_RULE = 1;\n\nconst DEFAULTS = {\n ci: \"fail\",\n timeoutMs: 10_000,\n maxSnippetChars: 4000,\n model: \"cloudflare/@cf/qwen/qwen3.8-27b\",\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\nconst taggedError = Schema.TaggedError;\n\nclass OptionsError extends taggedError<OptionsError, { readonly brand: unique symbol }>()(\n \"OptionsError\",\n { message: Schema.String },\n) {}\n\nconst optionsError = (message: string): Error =>\n OptionsError.make({ message: `${PREFIX}: ${message}` });\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 = pipe(rest, Arr.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 (providers: Readonly<Record<string, DecisionProvider>>): (id: string) => ModelRef;\n (id: string, providers: Readonly<Record<string, DecisionProvider>>): ModelRef;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (id: string, providers: Readonly<Record<string, DecisionProvider>>): 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 optionsError(\n `model \"${id}\" must be \"<provider>/<model>\" with a provider from: ${pipe(Rec.keys(providers), Arr.join(\", \"))}`,\n ),\n ),\n ),\n);\n\nconst duplicateIdOf = (rules: readonly DecisionRule[]): Option.Option<string> =>\n Arr.findFirst(\n Rec.toEntries(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(decodeRuleAnswer(rule.answer), (issue) =>\n 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: {\n (input: unknown, what: string): <Value>(decode: Decode<Value>) => Value;\n <Value>(decode: Decode<Value>, input: unknown, what: string): Value;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n <Value>(decode: Decode<Value>, input: unknown, what: string): Value =>\n Result.getOrThrowWith(decode(input), (issue) =>\n optionsError(`invalid ${what}: ${issue.message}`),\n ),\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 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 optionsError(\"rules must list at least one rule\");\n }\n Option.map(duplicateIdOf(rules), (duplicate) => {\n throw optionsError(`rule id \"${duplicate}\" is used more than once`);\n });\n return pipe(\n rules,\n Arr.map((rule) => checkRule(rule)),\n );\n};\n\nconst resolveRule =\n (fallback: ModelSpec, providers: Readonly<Record<string, DecisionProvider>>) =>\n (rule: DecisionRule): ResolvedRule => ({\n ...rule,\n answer: answerOf(rule),\n models: pipe(\n modelIdsOf(rule.model ?? fallback),\n Arr.map((id) => resolveModel(id, providers)),\n ),\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 (\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): (sources: Sources) => ResolvedOptions;\n (\n sources: Sources,\n rules: readonly DecisionRule[],\n providers: Readonly<Record<string, DecisionProvider>>,\n ): ResolvedOptions;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\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: pipe(\n checkRules(rules),\n Arr.map((rule) => resolveRule(model, providers)(rule)),\n ),\n };\n },\n);\n\nexport type { Decode, Sources };\nexport {\n checkRules,\n optionsError,\n PREFIX,\n ModelSpecSchema,\n STRICT,\n checked,\n modelIdsOf,\n resolveModel,\n resolveOptions,\n};\n","import {\n Cause,\n DateTime,\n Config,\n Console,\n Effect,\n Exit,\n Option,\n Schema,\n String as Str,\n Function as Fn,\n} from \"effect\";\n\nimport { PREFIX } from \"./options.ts\";\nimport type { ResolvedOptions } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst encodeJson = Schema.encodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nconst toJson = (value: unknown): string => Option.getOrElse(encodeJson(value), () => String(value));\n\nconst nowMs = (): number => DateTime.toEpochMillis(DateTime.nowUnsafe());\n\nconst runOrElse: {\n <Value>(\n fallback: (error: unknown) => Value,\n ): <Failure>(effect: Effect.Effect<Value, Failure>) => Value;\n <Value, Failure>(\n effect: Effect.Effect<Value, Failure>,\n fallback: (error: unknown) => Value,\n ): Value;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n <Value, Failure>(\n effect: Effect.Effect<Value, Failure>,\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);\n\nconst envOf = (name: string): Option.Option<string> =>\n runOrElse(Config.option(Config.NonEmptyString(name)), () => Option.none()).pipe(\n Option.map((value) => Str.trim(value)),\n Option.filter(Str.isNonEmpty),\n );\n\nconst envNameOf: {\n (name: string): (env: Readonly<Record<string, string>>) => string;\n (env: Readonly<Record<string, string>>, name: string): string;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (env: Readonly<Record<string, string>>, name: string): string => env[name] ?? name,\n);\n\nconst failsInCi = (options: ResolvedOptions): boolean =>\n options.ci === \"fail\" && Option.isSome(envOf(\"CI\"));\n\nconst warned = new Set<string>();\n\nconst warnOnce: {\n (message: string): (reason: string) => void;\n (reason: string, message: string): void;\n} = Fn.dual(DATA_FIRST_ARITY, (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\nconst captured: {\n (name: string): (match: Option.Option<RegExpMatchArray>) => Option.Option<string>;\n (match: Option.Option<RegExpMatchArray>, name: string): Option.Option<string>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (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);\n\nexport { captured, envNameOf, envOf, failsInCi, messageOf, nowMs, runOrElse, toJson, warnOnce };\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,MAAM,SAAS,OAAO,OAAO,MAC3B,OAAO,UACL;CAAE,SAAS;CAAW,SAAS;AAAE,GACjC,EAAE,SAAS,0BAA0B,UAAU,QAAQ,CACzD,CACF;AAEA,MAAM,eAAe,OAAO,SAAS;CAAC;CAAY;CAAQ;CAAO;AAAM,CAAC;AAExE,MAAM,mBAAmB,OAAO,SAAS,CAAC,QAAQ,MAAM,CAAC;AAEzD,MAAM,uBAAuB,OAAO,MAAM,CAAC,OAAO,SAAS,OAAO,SAAS,CAAC,QAAQ,MAAM,CAAC,CAAC,CAAC;AAE7F,MAAM,sBAAsB,OAAO,SAAS;CAAC;CAAY;CAAS;AAAO,CAAC;AAE1E,MAAM,oBAAoB,OAAO,MAAM;CACrC,OAAO,OAAO,EAAE,OAAO,OAAO,SAAS;EAAC;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