@r_masseater/oxlint-plugin-decision 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { A as resolveOptions, C as REPORT_LOC, D as checked, E as checkRules, N as isReported, O as modelIdsOf, S as PREFIX, T as TARGET_NODE_TYPES, _ as messageOf, a as locationCandidates, b as ModelSpecSchema, c as locationRefOf, d as selectedLocation, f as sourceLines, g as failsInCi, h as envOf, i as locates, j as snippetNodeFor, k as resolveModel, l as parseVerdicts, m as envNameOf, n as wireRequestsFor, o as locationOfLine, p as truncateSnippet, r as buildRequest, s as locationQuestion, u as refAt, v as runOrElse, w as STRICT, x as OptionsError, y as warnOnce } from "./wire-XOgoBBuu.mjs";
2
- import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Schema, String as String$1, pipe } from "effect";
1
+ import { A as resolveModel, C as ModelSpecSchema, D as checked, E as checkRules, N as isReported, O as modelIdsOf, S as warnOnce, T as STRICT, _ as failsInCi, a as parseVerdicts, b as runOrElse, c as EVERY_LINE, d as locationOfLine, f as locationQuestion, g as envOf, h as envNameOf, i as locationRefOf, j as resolveOptions, k as optionsError, l as locates, m as sourceLines, n as wireRequestsFor, o as refAt, p as selectedLocation, r as buildRequest, s as truncateSnippet, u as locationCandidates, v as messageOf, w as PREFIX, x as toJson, y as nowMs } from "./wire-XbLEwd0i.mjs";
2
+ import { Array, Boolean, Console, Effect, Function, Match, Option, Predicate, Record, Schema, String as String$1, Struct, pipe } from "effect";
3
3
  import { createSyncFn } from "synckit";
4
4
  // src/define.ts
5
5
  const defineDecisionRule = (rule) => rule;
@@ -8,10 +8,17 @@ const defineProvider = (provider) => provider;
8
8
  const BACKSTOP_MS = 6e4;
9
9
  const SYNCKIT_TIMEOUT = "Internal error: Atomics.wait() failed: timed-out";
10
10
  const workers = /* @__PURE__ */ new Map();
11
+ const WORKER_NAME = "openrouter-worker";
12
+ const BUILT_EXTENSION = ".mjs";
13
+ const MODULE_EXTENSION = /\.[cm]?[jt]s$/u;
14
+ const workerUrl = () => {
15
+ const extension = pipe(String$1.match(MODULE_EXTENSION)(import.meta.url), Option.flatMap(Array.head), Option.getOrElse(() => BUILT_EXTENSION));
16
+ return new URL(`${WORKER_NAME}${extension}`, import.meta.url);
17
+ };
11
18
  const workerCall = () => {
12
19
  const existing = workers.get("openrouter");
13
- if (existing) return existing;
14
- const created = createSyncFn(new URL("openrouter-worker.mjs", import.meta.url), { timeout: BACKSTOP_MS });
20
+ if (Predicate.isNotUndefined(existing)) return existing;
21
+ const created = createSyncFn(workerUrl(), { timeout: BACKSTOP_MS });
15
22
  workers.set("openrouter", created);
16
23
  return created;
17
24
  };
@@ -34,6 +41,7 @@ const openRouter = {
34
41
  })
35
42
  };
36
43
  // src/override.ts
44
+ const DATA_FIRST_ARITY_3$3 = 3;
37
45
  const RuleOverrideSchema = Schema.Struct({ model: Schema.optionalKey(ModelSpecSchema) });
38
46
  const RULE_OPTIONS_SCHEMA = [{
39
47
  type: "object",
@@ -51,18 +59,66 @@ const RULE_OPTIONS_SCHEMA = [{
51
59
  }] } }
52
60
  }];
53
61
  const decodeOverride = Schema.decodeUnknownResult(RuleOverrideSchema, STRICT);
54
- const overrideRule = (rule, raw, providers) => {
62
+ const overrideRule = Function.dual(DATA_FIRST_ARITY_3$3, (rule, raw, providers) => {
55
63
  if (Predicate.isUndefined(raw)) return rule;
56
64
  const { model } = checked(decodeOverride, raw, `options for rule "${rule.id}"`);
57
65
  return {
58
66
  ...rule,
59
67
  models: Option.match(Option.fromUndefinedOr(model), {
60
68
  onNone: () => rule.models,
61
- onSome: (spec) => modelIdsOf(spec).map((id) => resolveModel(id, providers))
69
+ onSome: (spec) => pipe(modelIdsOf(spec), Array.map((id) => resolveModel(id, providers)))
62
70
  })
63
71
  };
72
+ });
73
+ // src/nodes.ts
74
+ const FIRST_LINE$1 = 1;
75
+ const FIRST_COLUMN = 0;
76
+ const TARGET_NODE_TYPES = {
77
+ function: [
78
+ "FunctionDeclaration",
79
+ "FunctionExpression",
80
+ "ArrowFunctionExpression"
81
+ ],
82
+ call: ["CallExpression"],
83
+ jsx: ["JSXElement"],
84
+ file: ["Program"]
85
+ };
86
+ const NAMED_PARENTS = {
87
+ VariableDeclarator: "init",
88
+ Property: "value",
89
+ MethodDefinition: "value",
90
+ PropertyDefinition: "value"
91
+ };
92
+ const NAMED_PARENT_TYPES = new Set(Record.keys(NAMED_PARENTS));
93
+ const isNamedParentType = (type) => NAMED_PARENT_TYPES.has(type);
94
+ const ANONYMOUS_FUNCTIONS = /* @__PURE__ */ new Set(["FunctionExpression", "ArrowFunctionExpression"]);
95
+ const holdsAsName = (parent, node) => {
96
+ if (!isNamedParentType(parent.type)) return false;
97
+ const field = NAMED_PARENTS[parent.type];
98
+ return ANONYMOUS_FUNCTIONS.has(node.type) && parent[field] === node;
99
+ };
100
+ const snippetNodeFor = (node) => Option.fromNullishOr(node.parent).pipe(Option.filter((parent) => holdsAsName(parent, node)), Option.getOrElse(() => node));
101
+ const headOf = (text, line, column) => {
102
+ const [first] = String$1.split(text, "\n");
103
+ return {
104
+ start: {
105
+ line,
106
+ column
107
+ },
108
+ end: {
109
+ line,
110
+ column: column + first.length
111
+ }
112
+ };
113
+ };
114
+ const REPORT_LOC = {
115
+ function: (node, text) => headOf(text, node.loc.start.line, node.loc.start.column),
116
+ call: (node) => node.loc,
117
+ jsx: (node) => Option.getOrElse(Option.fromNullishOr(node.openingElement), () => node).loc,
118
+ file: (_node, text) => headOf(text, FIRST_LINE$1, FIRST_COLUMN)
64
119
  };
65
120
  // src/context.ts
121
+ const DATA_FIRST_ARITY_3$2 = 3;
66
122
  const DEFAULT_LINES = 5;
67
123
  const FIRST_LINE = 1;
68
124
  const LAST = 1;
@@ -89,7 +145,7 @@ const linesAround = (context, node, { before = DEFAULT_LINES, after = DEFAULT_LI
89
145
  const lines = sourceLines(context.sourceCode.text);
90
146
  const first = Math.max(FIRST_LINE, node.loc.start.line - before);
91
147
  const last = Math.min(lines.length, node.loc.end.line + after);
92
- return lines.slice(first - FIRST_LINE, last).map((text, index) => `L${String(first + index)}| ${text}`).join("\n");
148
+ return pipe(lines, Array.drop(first - FIRST_LINE), Array.take(last - first + FIRST_LINE), Array.map((text, index) => `L${String(first + index)}| ${text}`), Array.join("\n"));
93
149
  };
94
150
  const DECLARING_PARENTS = /* @__PURE__ */ new Set([
95
151
  "VariableDeclaration",
@@ -103,7 +159,7 @@ const declarationOf = (node) => Option.fromNullishOr(node.parent).pipe(Option.fi
103
159
  const leadingOf = (text, comments, until) => Option.match(Array.last(comments), {
104
160
  onNone: () => [],
105
161
  onSome: (last) => {
106
- if (String$1.isNonEmpty(text.slice(last.end, until).trim())) return [];
162
+ if (String$1.isNonEmpty(String$1.trim(String$1.slice(last.end, until)(text)))) return [];
107
163
  return [...leadingOf(text, Array.dropRight(comments, LAST), last.start), last];
108
164
  }
109
165
  });
@@ -111,31 +167,71 @@ const commentedTextOf = (context, node) => {
111
167
  const { text } = context.sourceCode;
112
168
  const named = snippetNodeFor(node);
113
169
  const [start] = declarationOf(named).range;
114
- const before = context.sourceCode.getAllComments().filter((comment) => comment.type !== "Shebang" && comment.end <= start);
170
+ const before = pipe(context.sourceCode.getAllComments(), Array.filter((comment) => comment.type !== "Shebang" && comment.end <= start));
115
171
  return Array.match(leadingOf(text, before, start), {
116
172
  onEmpty: () => Option.none(),
117
- onNonEmpty: ([first]) => Option.some(text.slice(first.start, named.range[END]))
173
+ onNonEmpty: ([first]) => Option.some(String$1.slice(first.start, named.range[END])(text))
118
174
  });
119
175
  };
120
176
  const isCommented = ({ context: wanted }) => Predicate.isNotUndefined(wanted) && wanted.scope === "comment";
121
- const commentedSnippetOf = (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node));
122
- const lacksComment = (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node));
123
- const contextOf = (context, node, rule) => {
177
+ const commentedSnippetOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => Option.flatMap(Option.liftPredicate(rule, isCommented), () => commentedTextOf(context, node)));
178
+ const lacksComment = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => isCommented(rule) && Option.isNone(commentedTextOf(context, node)));
179
+ const contextOf = Function.dual(DATA_FIRST_ARITY_3$2, (context, node, rule) => {
124
180
  if (rule.scope === "lines") return Option.some(linesAround(context, node, rule));
125
181
  if (rule.scope === "enclosing") return Option.some(enclosingText(context, node, rule.kind));
126
182
  return Option.liftPredicate(context.sourceCode.text, () => rule.scope === "file");
127
- };
183
+ });
128
184
  // src/name.ts
185
+ const DATA_FIRST_ARITY_3$1 = 3;
129
186
  const heldName = (node) => Option.flatMap(Option.fromNullishOr(node.parent), (parent) => Match.value(parent).pipe(Match.when({ type: "VariableDeclarator" }, (holder) => Option.liftPredicate(holder.id, () => holder.init === node)), Match.when({ type: Match.is("Property", "MethodDefinition", "PropertyDefinition") }, (holder) => Option.liftPredicate(holder.key, () => holder.value === node)), Match.orElse(() => Option.none())));
130
187
  const nameNodeOf = (node) => Match.value(node).pipe(Match.when({ type: Match.is("FunctionDeclaration", "FunctionExpression") }, (fn) => Option.orElse(Option.fromNullishOr(fn.id), () => heldName(fn))), Match.when({ type: "ArrowFunctionExpression" }, heldName), Match.when({ type: Match.is("CallExpression", "NewExpression") }, (call) => Option.some(call.callee)), Match.when({ type: "JSXElement" }, (element) => Option.some(element.openingElement.name)), Match.orElse(() => Option.none()));
131
- const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => context.sourceCode.text.slice(name.start, name.end)));
132
- const isSelected = (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
188
+ const nameOf = (node, context) => Option.getOrUndefined(Option.map(nameNodeOf(node), (name) => String$1.slice(name.start, name.end)(context.sourceCode.text)));
189
+ const isSelected = Function.dual(DATA_FIRST_ARITY_3$1, (context, node, { select }) => Option.match(Option.fromUndefinedOr(select), {
133
190
  onNone: () => true,
134
191
  onSome: (selects) => selects(node, {
135
192
  name: nameOf(node, context),
136
193
  context
137
194
  })
195
+ }));
196
+ // src/explain-text.ts
197
+ const DECIMALS$1 = 2;
198
+ const fixed = (value) => value.toFixed(DECIMALS$1);
199
+ const cachedText = (cached) => Option.match(Option.fromUndefinedOr(cached), {
200
+ onNone: () => "unknown",
201
+ onSome: (hit) => Boolean.match(hit, {
202
+ onTrue: () => "yes",
203
+ onFalse: () => "no"
204
+ })
138
205
  });
206
+ const probabilitiesText = (probabilities) => Option.match(Array.match(Record.toEntries(probabilities), {
207
+ onEmpty: () => Option.none(),
208
+ onNonEmpty: (entries) => Option.some(pipe(entries, Array.map(([label, value]) => `${label}=${fixed(value)}`), Array.join(" ")))
209
+ }), {
210
+ onNone: () => "(no answer)",
211
+ onSome: (text) => text
212
+ });
213
+ const verdictText = (explanation) => {
214
+ if (Predicate.isNotUndefined(explanation.error)) return `error: ${explanation.error}`;
215
+ const outcome = Boolean.match(explanation.reported, {
216
+ onTrue: () => "reported",
217
+ onFalse: () => "not reported"
218
+ });
219
+ const cutoff = `cutoff ${fixed(explanation.cutoff)}`;
220
+ return Option.match(Option.fromUndefinedOr(explanation.verdict), {
221
+ onNone: () => `no verdict, ${cutoff}, ${outcome}`,
222
+ onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`
223
+ });
224
+ };
225
+ const servedText = (served) => Option.match(Option.fromUndefinedOr(served), {
226
+ onNone: () => "",
227
+ onSome: (id) => ` (served ${id})`
228
+ });
229
+ const asText = (explanation) => pipe([
230
+ `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,
231
+ ` state: ${String(explanation.state.chars)} chars ${toJson(explanation.state.head)}`,
232
+ ...pipe(explanation.questions, Array.map(({ id, question, probabilities }) => ` ${id}: ${probabilitiesText(probabilities)}\n ${question}`)),
233
+ ` verdict: ${verdictText(explanation)}`
234
+ ], Array.join("\n"));
139
235
  // src/explain.ts
140
236
  const EXPLAIN_ENV = "OXLINT_DECISION_EXPLAIN";
141
237
  const OFF_VALUES = /* @__PURE__ */ new Set([
@@ -145,18 +241,17 @@ const OFF_VALUES = /* @__PURE__ */ new Set([
145
241
  "no"
146
242
  ]);
147
243
  const STATE_HEAD_CHARS = 60;
148
- const DECIMALS$1 = 2;
149
244
  const OPTION_SEPARATOR = "__";
150
245
  const FIRST = 1;
151
246
  const START = 0;
152
247
  const COLUMN_BASE = 1;
153
248
  const SEPARATOR = /^[/\\]/u;
154
- const relativeTo = (root, filename) => Boolean.match(String$1.isNonEmpty(root) && filename.startsWith(root) && SEPARATOR.test(filename.slice(root.length)), {
155
- onTrue: () => filename.slice(root.length + FIRST),
249
+ const relativeTo = (root, filename) => Boolean.match(String$1.isNonEmpty(root) && String$1.startsWith(root)(filename) && SEPARATOR.test(String$1.slice(root.length)(filename)), {
250
+ onTrue: () => String$1.slice(root.length + FIRST)(filename),
156
251
  onFalse: () => filename
157
252
  });
158
253
  const fromSetting = (setting) => Match.value(setting).pipe(Match.when("json", () => "json"), Match.when(true, () => "text"), Match.when("text", () => "text"), Match.orElse(() => "off"));
159
- const fromEnv = (value) => Match.value(value.toLowerCase()).pipe(Match.when("json", () => "json"), Match.when((lower) => OFF_VALUES.has(lower), () => "off"), Match.orElse(() => "text"));
254
+ const fromEnv = (value) => Match.value(String$1.toLowerCase(value)).pipe(Match.when("json", () => "json"), Match.when((lower) => OFF_VALUES.has(lower), () => "off"), Match.orElse(() => "text"));
160
255
  const explainModeOf = (setting) => Option.match(envOf(EXPLAIN_ENV), {
161
256
  onNone: () => fromSetting(setting),
162
257
  onSome: fromEnv
@@ -167,12 +262,12 @@ const probabilitiesIn = (answer) => {
167
262
  return Option.none();
168
263
  };
169
264
  const probabilitiesOf = (answer) => Option.fromUndefinedOr(answer).pipe(Option.flatMap(probabilitiesIn), Option.getOrElse(() => ({})));
170
- const asksAbout = (ref, id) => id.split(OPTION_SEPARATOR, FIRST).includes(ref);
171
- const sentFor = (sent, ref) => sent.flatMap((wire) => Object.entries(wire.questions).filter(([id]) => asksAbout(ref, id)));
172
- const stateTextOf = (sent, ref, snippet) => Array.findFirst(sent, (wire) => Object.keys(wire.questions).some((id) => asksAbout(ref, id))).pipe(Option.map(({ state }) => state), Option.filter(Predicate.isString), Option.getOrElse(() => snippet));
265
+ const asksAbout = (ref, id) => pipe(String$1.split(id, OPTION_SEPARATOR), Array.take(FIRST), Array.contains(ref));
266
+ const sentFor = (sent, ref) => pipe(sent, Array.flatMap((wire) => pipe(Record.toEntries(wire.questions), Array.filter(([id]) => asksAbout(ref, id)))));
267
+ const stateTextOf = (sent, ref, snippet) => Array.findFirst(sent, (wire) => pipe(Record.keys(wire.questions), Array.some((id) => asksAbout(ref, id)))).pipe(Option.map(({ state }) => state), Option.filter(Predicate.isString), Option.getOrElse(() => snippet));
173
268
  const summaryOf = (text) => ({
174
269
  chars: text.length,
175
- head: text.replaceAll(/\s+/gu, " ").trim().slice(START, STATE_HEAD_CHARS)
270
+ head: String$1.slice(START, STATE_HEAD_CHARS)(String$1.trim(String$1.replaceAll(/\s+/gu, " ")(text)))
176
271
  });
177
272
  const baseOf = ({ pass, sent }, match, { ref, loc }) => {
178
273
  const questions = sentFor(sent, ref);
@@ -185,53 +280,16 @@ const baseOf = ({ pass, sent }, match, { ref, loc }) => {
185
280
  cutoff: match.rule.cutoff,
186
281
  durationMs: pass.durationMs,
187
282
  state: summaryOf(stateTextOf(sent, ref, match.snippet)),
188
- questions: questions.map(([id, question]) => ({
283
+ questions: pipe(questions, Array.map(([id, question]) => ({
189
284
  id,
190
285
  question: question.instructions,
191
286
  probabilities: probabilitiesOf(answers[id])
192
- }))
287
+ })))
193
288
  });
194
289
  };
195
- const fixed = (value) => value.toFixed(DECIMALS$1);
196
- const cachedText = (cached) => Option.match(Option.fromUndefinedOr(cached), {
197
- onNone: () => "unknown",
198
- onSome: (hit) => Boolean.match(hit, {
199
- onTrue: () => "yes",
200
- onFalse: () => "no"
201
- })
202
- });
203
- const probabilitiesText = (probabilities) => Option.match(Array.match(Object.entries(probabilities), {
204
- onEmpty: () => Option.none(),
205
- onNonEmpty: (entries) => Option.some(entries.map(([label, value]) => `${label}=${fixed(value)}`).join(" "))
206
- }), {
207
- onNone: () => "(no answer)",
208
- onSome: (text) => text
209
- });
210
- const verdictText = (explanation) => {
211
- if (Predicate.isNotUndefined(explanation.error)) return `error: ${explanation.error}`;
212
- const outcome = Boolean.match(explanation.reported, {
213
- onTrue: () => "reported",
214
- onFalse: () => "not reported"
215
- });
216
- const cutoff = `cutoff ${fixed(explanation.cutoff)}`;
217
- return Option.match(Option.fromUndefinedOr(explanation.verdict), {
218
- onNone: () => `no verdict, ${cutoff}, ${outcome}`,
219
- onSome: ({ answer, probability }) => `${answer} ${fixed(probability)}, ${cutoff}, ${outcome}`
220
- });
221
- };
222
- const servedText = (served) => Option.match(Option.fromUndefinedOr(served), {
223
- onNone: () => "",
224
- onSome: (id) => ` (served ${id})`
225
- });
226
- const asText = (explanation) => [
227
- `${PREFIX} explain: ${explanation.file}:${String(explanation.line)}:${String(explanation.column)} [${explanation.rule}] ${explanation.model}${servedText(explanation.served)} cached=${cachedText(explanation.cached)} ${String(explanation.durationMs)}ms`,
228
- ` state: ${String(explanation.state.chars)} chars ${JSON.stringify(explanation.state.head)}`,
229
- ...explanation.questions.map(({ id, question, probabilities }) => ` ${id}: ${probabilitiesText(probabilities)}\n ${question}`),
230
- ` verdict: ${verdictText(explanation)}`
231
- ].join("\n");
232
290
  const printerFor = (mode) => (explanation) => {
233
291
  const line = Boolean.match(mode === "json", {
234
- onTrue: () => JSON.stringify(explanation),
292
+ onTrue: () => toJson(explanation),
235
293
  onFalse: () => asText(explanation)
236
294
  });
237
295
  Effect.runFork(Console.error(line));
@@ -282,9 +340,11 @@ const SILENT = {
282
340
  };
283
341
  const explainerFor = (pass) => Match.value(explainModeOf(pass.setting)).pipe(Match.when("off", () => SILENT), Match.orElse((mode) => explaining(pass, mode)));
284
342
  // src/locate.ts
343
+ const DATA_FIRST_ARITY_3 = 3;
344
+ const DATA_FIRST_ARITY$1 = 2;
285
345
  const MINIMUM_TIMEOUT_MS = 1;
286
- const remainingMs = (deadline) => Math.max(MINIMUM_TIMEOUT_MS, deadline - Date.now());
287
- const verdictsOf = (result, request) => {
346
+ const remainingMs = (deadline) => Math.max(MINIMUM_TIMEOUT_MS, deadline - nowMs());
347
+ const verdictsOf = Function.dual(DATA_FIRST_ARITY$1, (result, request) => {
288
348
  if (!result.ok) return result;
289
349
  return runOrElse(Effect.sync(() => ({
290
350
  ok: true,
@@ -294,12 +354,12 @@ const verdictsOf = (result, request) => {
294
354
  ok: false,
295
355
  reason: messageOf(cause)
296
356
  }));
297
- };
298
- const inputOf = (asking, request) => ({
357
+ });
358
+ const inputOf = Function.dual(DATA_FIRST_ARITY$1, (asking, request) => ({
299
359
  request,
300
360
  timeoutMs: remainingMs(asking.deadline),
301
361
  env: asking.env
302
- });
362
+ }));
303
363
  const fetchVerdicts = (asking, request) => verdictsOf(asking.model.provider.decide(inputOf(asking, request)), request);
304
364
  const isRange = (location) => Option.exists(location, ({ start, end }) => start !== end);
305
365
  const refineOnce = ({ asking, match, ref, state }, within) => {
@@ -334,23 +394,23 @@ const refine = (refinement, first) => {
334
394
  failure: Option.none()
335
395
  };
336
396
  };
337
- const locateMatch = (asking, match, { ref, verdicts, request }) => {
397
+ const locateMatch = Function.dual(DATA_FIRST_ARITY_3, (asking, match, { ref, verdicts, request }) => {
338
398
  if (!locates(match)) return {
339
399
  loc: match.loc,
340
400
  failure: Option.none()
341
401
  };
342
- const first = selectedLocation(verdicts.answers[locationRefOf(ref)], locationCandidates(match.snippet), match.rule.location.cutoff);
402
+ const first = selectedLocation(verdicts.answers[locationRefOf(ref)], locationCandidates(match.snippet, EVERY_LINE), match.rule.location.cutoff);
343
403
  return refine({
344
404
  asking,
345
405
  match,
346
406
  ref,
347
407
  state: request.state
348
408
  }, first);
349
- };
409
+ });
350
410
  // src/report.ts
351
411
  const DECIMALS = 2;
352
412
  const degrade = (pass, reason) => {
353
- if (failsInCi(pass.options)) throw new OptionsError(`${reason} (${pass.filename})`);
413
+ if (failsInCi(pass.options)) throw optionsError(`${reason} (${pass.filename})`);
354
414
  warnOnce(reason, `${reason} (${pass.filename})`);
355
415
  };
356
416
  const reportFailure = (pass, failure) => {
@@ -478,9 +538,9 @@ const reportAnswer = ({ pass, asking, request }, { decided, durationMs }) => {
478
538
  });
479
539
  };
480
540
  const decideWith = (provider, prepared) => {
481
- const inputs = prepared.map(({ asking, request }) => inputOf(asking, request));
541
+ const inputs = pipe(prepared, Array.map(({ asking, request }) => inputOf(asking, request)));
482
542
  return Option.match(Option.fromUndefinedOr(provider.decideAll), {
483
- onNone: () => inputs.map((input) => provider.decide(input)),
543
+ onNone: () => pipe(inputs, Array.map((input) => provider.decide(input))),
484
544
  onSome: (decideAll) => decideAll(inputs)
485
545
  });
486
546
  };
@@ -491,10 +551,10 @@ const reportProvider = (prepared) => {
491
551
  const durationMs = Math.round(performance.now() - started);
492
552
  const answers = Boolean.match(results.length === prepared.length, {
493
553
  onTrue: () => results,
494
- onFalse: () => prepared.map(() => ({
554
+ onFalse: () => pipe(prepared, Array.map(() => ({
495
555
  ok: false,
496
556
  reason: `provider ${provider.name} returned ${String(results.length)} results for ${String(prepared.length)} requests`
497
- }))
557
+ })))
498
558
  });
499
559
  for (const [one, decided] of Array.zip(prepared, answers)) reportAnswer(one, {
500
560
  decided,
@@ -502,24 +562,28 @@ const reportProvider = (prepared) => {
502
562
  });
503
563
  };
504
564
  const reportModels = (passes) => {
505
- const byProvider = Array.groupBy(passes.map((pass) => prepare(pass)), ({ pass }) => pass.model.provider.name);
506
- for (const prepared of Object.values(byProvider)) reportProvider(prepared);
565
+ const byProvider = Array.groupBy(pipe(passes, Array.map((pass) => prepare(pass))), ({ pass }) => pass.model.provider.name);
566
+ for (const prepared of Record.values(byProvider)) reportProvider(prepared);
507
567
  };
508
568
  // src/visitor.ts
569
+ const DATA_FIRST_ARITY = 2;
509
570
  const raisedMissing = /* @__PURE__ */ new Set();
510
- const missingEnvOf = (options, provider) => provider.requiredEnv.map((name) => envNameOf(options.env, name)).filter((name) => Option.isNone(envOf(name)));
571
+ const missingEnvOf = (options, provider) => pipe(provider.requiredEnv, Array.map((name) => envNameOf(options.env, name)), Array.filter((name) => Option.isNone(envOf(name))));
511
572
  const isAvailable = (options, { provider }) => {
512
573
  const missingNames = missingEnvOf(options, provider);
513
574
  if (Array.isReadonlyArrayEmpty(missingNames)) return true;
514
- const missing = missingNames.join(", ");
575
+ const missing = pipe(missingNames, Array.join(", "));
515
576
  if (!failsInCi(options)) warnOnce(`missing:${provider.name}`, `${missing} is not set, skipping ${provider.name} models`);
516
577
  else if (!raisedMissing.has(provider.name)) {
517
578
  raisedMissing.add(provider.name);
518
- throw new OptionsError(`${missing} is not set`);
579
+ throw optionsError(`${missing} is not set`);
519
580
  }
520
581
  return false;
521
582
  };
522
- const availableModels = (batch) => [...new Map(Object.values(batch.rules).flatMap((rule) => rule.models).map((model) => [model.id, model])).values()].filter((model) => isAvailable(batch.options, model));
583
+ const availableModels = (batch) => {
584
+ const models = pipe(Record.values(batch.rules), Array.flatMap((rule) => rule.models), Array.map((model) => [model.id, model]));
585
+ return pipe(Array.fromIterable(new Map(models).values()), Array.filter((model) => isAvailable(batch.options, model)));
586
+ };
523
587
  const snippetOf = (context, node) => {
524
588
  if (node.type === "Program") return context.sourceCode.text;
525
589
  return context.sourceCode.getText(node);
@@ -545,11 +609,11 @@ const matchOf = (context, node, { rule, options }) => {
545
609
  };
546
610
  const contextOfRule = (batch, id) => Option.getOrThrow(Option.fromUndefinedOr(batch.contexts[id]));
547
611
  const finish = (batch) => {
548
- const [first] = Object.values(batch.contexts);
612
+ const [first] = Record.values(batch.contexts);
549
613
  if (Predicate.isUndefined(first)) return;
550
- const deadline = Date.now() + batch.options.timeoutMs;
551
- const passes = availableModels(batch).flatMap((model) => {
552
- const matches = batch.matches.filter(({ rule }) => rule.models.some(({ id }) => id === model.id));
614
+ const deadline = nowMs() + batch.options.timeoutMs;
615
+ const passes = pipe(availableModels(batch), Array.flatMap((model) => {
616
+ const matches = pipe(batch.matches, Array.filter(({ rule }) => pipe(rule.models, Array.some(({ id }) => id === model.id))));
553
617
  return Array.match(matches, {
554
618
  onEmpty: () => [],
555
619
  onNonEmpty: (some) => [{
@@ -561,11 +625,11 @@ const finish = (batch) => {
561
625
  deadline
562
626
  }]
563
627
  });
564
- });
628
+ }));
565
629
  reportModels(passes);
566
630
  };
567
631
  const ruleIn = (batch, id) => Option.getOrThrow(Array.findFirst(batch.options.rules, (rule) => rule.id === id));
568
- const sharedFile = (optionsFor, ruleFor) => {
632
+ const sharedFile = Function.dual(DATA_FIRST_ARITY, (optionsFor, ruleFor) => {
569
633
  let current = Option.none();
570
634
  const start = (context) => {
571
635
  const batch = {
@@ -601,16 +665,16 @@ const sharedFile = (optionsFor, ruleFor) => {
601
665
  if (Option.isNone(current)) return;
602
666
  const batch = current.value;
603
667
  batch.exits += 1;
604
- if (batch.exits >= Object.keys(batch.contexts).length) current = Option.none();
668
+ if (batch.exits >= Record.keys(batch.contexts).length) current = Option.none();
605
669
  if (!batch.exiting) {
606
670
  batch.exiting = true;
607
671
  finish(batch);
608
672
  }
609
673
  }
610
674
  };
611
- };
675
+ });
612
676
  const isSkipped = (context, node, rule) => !isSelected(context, node, rule) || lacksComment(context, node, rule);
613
- const visitorFor = (shared, { id, target }) => (context) => {
677
+ const visitorFor = Function.dual(DATA_FIRST_ARITY, (shared, { id, target }) => (context) => {
614
678
  let file = Option.none();
615
679
  const collect = (node) => {
616
680
  if (Option.isNone(file)) return;
@@ -623,7 +687,7 @@ const visitorFor = (shared, { id, target }) => (context) => {
623
687
  };
624
688
  const nodeTypes = TARGET_NODE_TYPES[target];
625
689
  return {
626
- ...Object.fromEntries(nodeTypes.map((type) => [type, collect])),
690
+ ...Record.fromEntries(pipe(nodeTypes, Array.map((type) => [type, collect]))),
627
691
  Program: (node) => {
628
692
  file = Option.some(shared.join(context, id));
629
693
  if (target === "file") collect(node);
@@ -633,7 +697,7 @@ const visitorFor = (shared, { id, target }) => (context) => {
633
697
  shared.leave();
634
698
  }
635
699
  };
636
- };
700
+ });
637
701
  // src/plugin.ts
638
702
  const DEFAULT_NAME = "decision";
639
703
  const metaOf = (rule) => ({
@@ -645,16 +709,15 @@ const metaOf = (rule) => ({
645
709
  unlocated: `${PREFIX}: {{reason}} while refining the location of [{{id}}]; the finding is reported at the file level`
646
710
  }
647
711
  });
648
- const SETUP_ONLY = /* @__PURE__ */ new Set([
712
+ const optionsOf = (setup) => Struct.omit(setup, [
649
713
  "name",
650
714
  "rules",
651
715
  "providers"
652
716
  ]);
653
- const optionsOf = (setup) => Object.fromEntries(Object.entries(setup).filter(([key]) => !SETUP_ONLY.has(key)));
654
717
  const memoized = (resolve) => {
655
718
  const resolved = /* @__PURE__ */ new Map();
656
719
  return (settings) => {
657
- const key = JSON.stringify([settings]);
720
+ const key = toJson([settings]);
658
721
  const cached = resolved.get(key);
659
722
  if (Predicate.isNotUndefined(cached)) return cached;
660
723
  const fresh = resolve(settings);
@@ -667,7 +730,7 @@ const memoizedRules = (providers) => {
667
730
  return (rule, options) => {
668
731
  const known = resolved.get(rule) ?? /* @__PURE__ */ new Map();
669
732
  resolved.set(rule, known);
670
- const key = JSON.stringify([options]);
733
+ const key = toJson([options]);
671
734
  const cached = known.get(key);
672
735
  if (Predicate.isNotUndefined(cached)) return cached;
673
736
  const fresh = overrideRule(rule, options, providers);
@@ -677,7 +740,7 @@ const memoizedRules = (providers) => {
677
740
  };
678
741
  const createDecisionPlugin = (setup) => {
679
742
  const name = setup.name ?? DEFAULT_NAME;
680
- const providers = Object.fromEntries([openRouter, ...setup.providers ?? []].map((provider) => [provider.name, provider]));
743
+ const providers = Record.fromEntries(pipe([openRouter, ...setup.providers ?? []], Array.map((provider) => [provider.name, provider])));
681
744
  const rules = checkRules(setup.rules);
682
745
  const options = optionsOf(setup);
683
746
  const resolve = memoized((settings) => resolveOptions({
@@ -688,10 +751,10 @@ const createDecisionPlugin = (setup) => {
688
751
  const shared = sharedFile((settings) => resolve(settings[name]), memoizedRules(providers));
689
752
  return {
690
753
  meta: { name },
691
- rules: Object.fromEntries(rules.map((rule) => [rule.id, {
754
+ rules: Record.fromEntries(pipe(rules, Array.map((rule) => [rule.id, {
692
755
  meta: metaOf(rule),
693
756
  createOnce: visitorFor(shared, rule)
694
- }]))
757
+ }])))
695
758
  };
696
759
  };
697
760
  export { createDecisionPlugin, defineDecisionRule, defineProvider, openRouter };