@r_masseater/oxlint-plugin-decision 0.4.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,508 +0,0 @@
1
- import { Array, Boolean, Cause, Config, Console, DateTime, Effect, Exit, Function, Number as Number$1, Option, Order, 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$6 = 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$6, (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$6, (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$6, (rule, verdict) => verdict.probability >= rule.cutoff && answerMatches(rule.answer, verdict.answer));
143
- // src/options.ts
144
- const DATA_FIRST_ARITY_3$1 = 3;
145
- const DATA_FIRST_ARITY$5 = 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: "openrouter/~typesafe/jev-latest",
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$5, (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$1, (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$1, ({ 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$4 = 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$4, (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$4, (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$4, (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
- // src/location.ts
269
- const DATA_FIRST_ARITY$3 = 2;
270
- const DATA_FIRST_ARITY_3 = 3;
271
- const CHOICE_OPTION_LIMIT = 254;
272
- const FIRST_LINE$1 = 1;
273
- const MINIMUM_WIDTH = 1;
274
- const UNKNOWN_CHOICE = "unknown";
275
- const sourceLines = (text) => String$1.split(text, /\r\n|[\n\r\u2028\u2029]/u);
276
- const locates = (match) => Predicate.isNotUndefined(match.rule.location) && !match.truncated;
277
- const EVERY_LINE = {
278
- start: FIRST_LINE$1,
279
- end: Number.POSITIVE_INFINITY
280
- };
281
- const isWithin = (line, within) => Number$1.between(line, {
282
- minimum: within.start,
283
- maximum: within.end
284
- });
285
- const rangeKey = ({ start, end }) => Boolean.match(start === end, {
286
- onTrue: () => `L${String(start)}`,
287
- onFalse: () => `L${String(start)}-L${String(end)}`
288
- });
289
- const rangeLabel = ({ start, end }) => Boolean.match(start === end, {
290
- onTrue: () => `Line ${String(start)}`,
291
- onFalse: () => `Lines ${String(start)} to ${String(end)}`
292
- });
293
- const rangeOf = (group) => ({
294
- start: Array.headNonEmpty(group).line,
295
- end: Array.lastNonEmpty(group).line
296
- });
297
- const numberedLines = (snippet) => pipe(sourceLines(snippet), Array.map((text, index) => ({
298
- text,
299
- line: Number$1.sum(index, FIRST_LINE$1)
300
- })));
301
- const locationCandidates = Function.dual(DATA_FIRST_ARITY$3, (snippet, within) => {
302
- const lines = pipe(numberedLines(snippet), Array.filter(({ text, line }) => String$1.trim(text).length >= FIRST_LINE$1 && isWithin(line, within)));
303
- const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));
304
- return Record.fromEntries(pipe(Array.chunksOf(lines, width), Array.map((group) => {
305
- const range = rangeOf(group);
306
- return [rangeKey(range), range];
307
- })));
308
- });
309
- const locationQuestion = Function.dual(DATA_FIRST_ARITY_3, (match, ref, candidates) => ({
310
- type: "choice",
311
- 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.`,
312
- criteria: {
313
- ...Record.fromEntries(pipe(Record.toEntries(candidates), Array.map(([key, range]) => [key, rangeLabel(range)]))),
314
- [UNKNOWN_CHOICE]: "No clear source location for this violation"
315
- }
316
- }));
317
- const validChoice = Function.dual(DATA_FIRST_ARITY$3, (answer, criteria) => Option.exists(choiceOf(answer), (chosen) => Record.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen))));
318
- const selectedLocation = Function.dual(DATA_FIRST_ARITY_3, (answer, candidates, cutoff) => choiceOf(answer).pipe(Option.filter((chosen) => Option.exists(probabilityOfChoice(chosen), (probability) => Number$1.isGreaterThanOrEqualTo(probability, cutoff))), Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice]))));
319
- const locationOfLine = Function.dual(DATA_FIRST_ARITY$3, (snippet, line) => {
320
- const text = Option.getOrElse(Array.get(sourceLines(snippet), Number$1.decrement(line)), () => "");
321
- return {
322
- start: {
323
- line,
324
- column: Option.getOrElse(String$1.search(/\S/u)(text), () => Number$1.decrement(FIRST_LINE$1))
325
- },
326
- end: {
327
- line,
328
- column: String$1.trimEnd(text).length
329
- }
330
- };
331
- });
332
- // src/request.ts
333
- const DATA_FIRST_ARITY$2 = 2;
334
- const FIRST_LINE = 1;
335
- const LOCATION_SUFFIX = "_location";
336
- const TRUNCATION_MARKER = "/* ...truncated */";
337
- const refAt = (index) => `s${String(index)}`;
338
- const locationRefOf = (ref) => `${ref}${LOCATION_SUFFIX}`;
339
- const snippetRefOf = (questionId) => Boolean.match(String$1.endsWith(LOCATION_SUFFIX)(questionId), {
340
- onTrue: () => String$1.slice(Number$1.decrement(FIRST_LINE), -9)(questionId),
341
- onFalse: () => questionId
342
- });
343
- const truncateSnippet = Function.dual(DATA_FIRST_ARITY$2, (text, maxChars) => Boolean.match(text.length <= maxChars, {
344
- onTrue: () => text,
345
- onFalse: () => `${String$1.slice(Number$1.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`
346
- }));
347
- const numbered = (snippet) => pipe(numberedLines(snippet), Array.map(({ text, line }) => `L${String(line)}| ${text}`), Array.join("\n"));
348
- const contextNote = (match, ref) => {
349
- if (Predicate.isUndefined(match.context)) return "";
350
- return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;
351
- };
352
- const mainQuestionFor = (match, ref) => [ref, questionFor(match.rule.answer, `Consider only snippet "${ref}" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`)];
353
- const questionsFor = (match, ref) => {
354
- if (!locates(match)) return [mainQuestionFor(match, ref)];
355
- return [mainQuestionFor(match, ref), [locationRefOf(ref), locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE))]];
356
- };
357
- const snippetFor = (match) => {
358
- if (locates(match)) return numbered(match.snippet);
359
- return match.snippet;
360
- };
361
- const contextsOf = (matches) => {
362
- const contexts = pipe(matches, Array.flatMap((match, index) => Option.toArray(Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text]))));
363
- if (Array.isReadonlyArrayEmpty(contexts)) return {};
364
- return { contexts: Record.fromEntries(contexts) };
365
- };
366
- const buildRequest = Function.dual(DATA_FIRST_ARITY$2, (model, matches) => ({
367
- model,
368
- state: {
369
- snippets: Record.fromEntries(pipe(matches, Array.map((match, index) => [refAt(index), snippetFor(match)]))),
370
- ...contextsOf(matches)
371
- },
372
- questions: Record.fromEntries(pipe(matches, Array.flatMap((match, index) => questionsFor(match, refAt(index)))))
373
- }));
374
- const choiceQuestionsOf$1 = (request) => pipe(Record.toEntries(request.questions), Array.flatMap(([id, question]) => {
375
- if (question.type === "choice") return [[id, question.criteria]];
376
- return [];
377
- }));
378
- const mainQuestionsOf = (request) => pipe(Record.toEntries(request.questions), Array.filter(([id]) => !String$1.endsWith(LOCATION_SUFFIX)(id)));
379
- const resultOf = (answers, [ref, question]) => [ref, Option.getOrThrowWith(verdictOf(question, answers[ref]), () => /* @__PURE__ */ new Error(`response has no valid answer for "${ref}"`))];
380
- const parseVerdicts = Function.dual(DATA_FIRST_ARITY$2, (response, request) => {
381
- const { model, answers } = Option.getOrThrowWith(Option.liftPredicate(response, ({ model: served }) => String$1.isNonEmpty(served)), () => /* @__PURE__ */ new Error("response has no model id"));
382
- return {
383
- model,
384
- results: Record.fromEntries(pipe(mainQuestionsOf(request), Array.map((entry) => resultOf(answers, entry)))),
385
- answers,
386
- complete: pipe(choiceQuestionsOf$1(request), Array.every(([id, criteria]) => validChoice(answers[id], criteria)))
387
- };
388
- });
389
- // src/wire-choice.ts
390
- const DATA_FIRST_ARITY$1 = 2;
391
- const RESPAN_MODELS = ["respan/"];
392
- const OPTION_SEPARATOR = "__";
393
- const CERTAIN = 1;
394
- const NO_SEVERITY = "none";
395
- const isRespan = (model) => pipe(RESPAN_MODELS, Array.some((prefix) => String$1.startsWith(prefix)(model)));
396
- const optionIdOf = Function.dual(DATA_FIRST_ARITY$1, (id, label) => `${id}${OPTION_SEPARATOR}${label}`);
397
- const isSeverityScale = (criteria) => pipe(Record.keys(criteria), Array.join(",")) === pipe(SEVERITY_ORDER, Array.join(","));
398
- const levelsAboveNone = (criteria) => pipe(Record.toEntries(criteria), Array.filter(([label]) => label !== NO_SEVERITY));
399
- const byYes = Order.mapInput(Order.Number, ({ yes }) => yes);
400
- const scoreOf = (answers, id, label) => Option.map(noulOf(answers[optionIdOf(id, label)]), ({ noul }) => ({
401
- label,
402
- yes: noul
403
- }));
404
- const scoresOf = (answers, id, labels) => pipe(labels, Array.map((label) => scoreOf(answers, id, label)), Option.all, Option.flatMap((scores) => Option.liftPredicate(scores, Array.isArrayNonEmpty)));
405
- const probabilitiesOf = (scores) => Record.fromEntries(pipe(scores, Array.map(({ label, yes }) => [label, yes])));
406
- const choiceAnswer = (choice, probabilities) => ({
407
- type: "choice",
408
- choice,
409
- probabilities
410
- });
411
- const bestLabel = (scores) => choiceAnswer(Array.max(scores, byYes).label, probabilitiesOf(scores));
412
- const atLeast = (scores) => pipe(scores, Array.map(({ label }, index) => ({
413
- label,
414
- yes: Math.max(...pipe(scores.slice(index), Array.map(({ yes }) => yes)))
415
- })));
416
- const severityLevel = (scores) => {
417
- const cumulative = atLeast(scores);
418
- const probabilities = {
419
- [NO_SEVERITY]: Number$1.subtract(CERTAIN, Array.headNonEmpty(cumulative).yes),
420
- ...probabilitiesOf(cumulative)
421
- };
422
- const reached = pipe(cumulative, Array.findLast(({ yes }) => yes >= CONFIDENT));
423
- return choiceAnswer(Option.match(reached, {
424
- onNone: () => NO_SEVERITY,
425
- onSome: ({ label }) => label
426
- }), probabilities);
427
- };
428
- const labelsAsked = (criteria) => {
429
- if (isSeverityScale(criteria)) return pipe(levelsAboveNone(criteria), Array.map(([label]) => label));
430
- return Record.keys(criteria);
431
- };
432
- const choiceFromYesNo = (answers, [id, { criteria }]) => {
433
- const collapse = Boolean.match(isSeverityScale(criteria), {
434
- onTrue: () => severityLevel,
435
- onFalse: () => bestLabel
436
- });
437
- return scoresOf(answers, id, labelsAsked(criteria)).pipe(Option.map((scores) => [id, collapse(scores)]), Option.toArray);
438
- };
439
- const choiceQuestionsOf = (request) => pipe(Record.toEntries(request.questions), Array.flatMap(([id, question]) => {
440
- if (question.type === "choice") return [[id, question]];
441
- return [];
442
- }));
443
- const withChoices = Function.dual(DATA_FIRST_ARITY$1, (request, answers) => {
444
- if (!isRespan(request.model)) return answers;
445
- return {
446
- ...answers,
447
- ...Record.fromEntries(pipe(choiceQuestionsOf(request), Array.flatMap((entry) => choiceFromYesNo(answers, entry))))
448
- };
449
- });
450
- // src/wire.ts
451
- const DATA_FIRST_ARITY = 2;
452
- const sectionsOf = (name, entries) => pipe(Record.toEntries(entries), Array.map(([ref, text]) => `state.${name}.${ref}:\n${text}`));
453
- const stateAsText = ({ snippets, contexts = {} }) => pipe([...sectionsOf("snippets", snippets), ...sectionsOf("contexts", contexts)], Array.join("\n\n"));
454
- const only = (entries, ref) => Option.match(Option.fromUndefinedOr(entries[ref]), {
455
- onNone: () => ({}),
456
- onSome: (text) => ({ [ref]: text })
457
- });
458
- const stateOf = ({ snippets, contexts }, ref) => {
459
- if (Predicate.isUndefined(contexts)) return { snippets: only(snippets, ref) };
460
- return {
461
- snippets: only(snippets, ref),
462
- contexts: only(contexts, ref)
463
- };
464
- };
465
- const optionText = (label, description) => Option.match(Option.fromNullishOr(description), {
466
- onNone: () => `"${label}"`,
467
- onSome: (text) => `"${label}" (${text})`
468
- });
469
- const labelQuestion = (instructions, label, description) => ({
470
- type: "noul",
471
- instructions: `${instructions} Does the label ${optionText(label, description)} fit?`
472
- });
473
- const levelQuestion = (instructions, label, description) => ({
474
- type: "noul",
475
- instructions: `${instructions} Is it at least as serious as ${optionText(label, description)}?`
476
- });
477
- const yesNoQuestionsOf = (id, { instructions, criteria }) => {
478
- if (isSeverityScale(criteria)) return pipe(levelsAboveNone(criteria), Array.map(([label, description]) => [optionIdOf(id, label), levelQuestion(instructions, label, description)]));
479
- return pipe(Record.toEntries(criteria), Array.map(([label, description]) => [optionIdOf(id, label), labelQuestion(instructions, label, description)]));
480
- };
481
- const asYesNo = ([id, question]) => {
482
- if (question.type === "choice") return yesNoQuestionsOf(id, question);
483
- return [[id, question]];
484
- };
485
- const perSnippet = (request) => {
486
- const bySnippet = Array.groupBy(Record.toEntries(request.questions), ([id]) => snippetRefOf(id));
487
- const wires = pipe(Record.values(bySnippet), Array.map((questions) => {
488
- const [[id]] = questions;
489
- return {
490
- model: request.model,
491
- state: stateAsText(stateOf(request.state, snippetRefOf(id))),
492
- questions: Record.fromEntries(pipe(questions, Array.flatMap((entry) => asYesNo(entry))))
493
- };
494
- }));
495
- if (Array.isReadonlyArrayNonEmpty(wires)) return wires;
496
- return [request];
497
- };
498
- const wireRequestsFor = (request) => {
499
- if (isRespan(request.model)) return perSnippet(request);
500
- return [request];
501
- };
502
- const mergeResponses = Function.dual(DATA_FIRST_ARITY, (request, responses) => ({
503
- ...Array.headNonEmpty(responses),
504
- answers: withChoices(request, pipe(responses, Array.flatMap(({ answers }) => Record.toEntries(answers)), Record.fromEntries))
505
- }));
506
- export { resolveModel as A, ModelSpecSchema as C, checked as D, checkRules as E, AnswerSchema as M, isReported as N, modelIdsOf as O, warnOnce as S, STRICT as T, failsInCi as _, parseVerdicts as a, runOrElse as b, EVERY_LINE as c, locationOfLine as d, locationQuestion as f, envOf as g, envNameOf as h, locationRefOf as i, resolveOptions as j, optionsError as k, locates as l, sourceLines as m, wireRequestsFor as n, refAt as o, selectedLocation as p, buildRequest as r, truncateSnippet as s, mergeResponses as t, locationCandidates as u, messageOf as v, PREFIX as w, toJson as x, nowMs as y };
507
-
508
- //# sourceMappingURL=wire-XbLEwd0i.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wire-XbLEwd0i.mjs","names":["Arr","Rec","DATA_FIRST_ARITY","Rec","Fn","DATA_FIRST_ARITY_3","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","DATA_FIRST_ARITY","Fn","Str","DATA_FIRST_ARITY","FIRST_LINE","Str","Num","Bool","Arr","Fn","Rec","DATA_FIRST_ARITY","Bool","Str","Num","Fn","Arr","Rec","choiceQuestionsOf","DATA_FIRST_ARITY","Arr","Str","Fn","Rec","Num","Bool","Rec","Arr","Fn"],"sources":["../src/schema.ts","../src/answer.ts","../src/options.ts","../src/runtime.ts","../src/location.ts","../src/request.ts","../src/wire-choice.ts","../src/wire.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: \"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\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\nexport { envNameOf, envOf, failsInCi, messageOf, nowMs, runOrElse, toJson, 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 Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { choiceOf, probabilityOfChoice } from \"./answer.ts\";\nimport type { Answer, ChoiceQuestion, LineRange, RequestMatch, RuleLocation } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\nconst DATA_FIRST_ARITY_3 = 3;\nconst CHOICE_OPTION_LIMIT = 254;\nconst FIRST_LINE = 1;\nconst MINIMUM_WIDTH = 1;\nconst UNKNOWN_CHOICE = \"unknown\";\n\nconst sourceLines = (text: string): readonly string[] =>\n Str.split(text, /\\r\\n|[\\n\\r\\u2028\\u2029]/u);\n\ntype LocatedMatch = RequestMatch & {\n readonly rule: { readonly question: string; readonly location: RuleLocation };\n};\n\nconst locates = (match: RequestMatch): match is LocatedMatch =>\n Predicate.isNotUndefined(match.rule.location) && !match.truncated;\n\ninterface NumberedLine {\n readonly text: string;\n readonly line: number;\n}\n\nconst EVERY_LINE: LineRange = { start: FIRST_LINE, end: Number.POSITIVE_INFINITY };\n\nconst isWithin = (line: number, within: LineRange): boolean =>\n Num.between(line, { minimum: within.start, maximum: within.end });\n\nconst rangeKey = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `L${String(start)}`,\n onFalse: () => `L${String(start)}-L${String(end)}`,\n });\n\nconst rangeLabel = ({ start, end }: LineRange): string =>\n Bool.match(start === end, {\n onTrue: () => `Line ${String(start)}`,\n onFalse: () => `Lines ${String(start)} to ${String(end)}`,\n });\n\nconst rangeOf = (group: Arr.NonEmptyReadonlyArray<NumberedLine>): LineRange => ({\n start: Arr.headNonEmpty(group).line,\n end: Arr.lastNonEmpty(group).line,\n});\n\nconst numberedLines = (snippet: string): readonly NumberedLine[] =>\n pipe(\n sourceLines(snippet),\n Arr.map((text, index) => ({ text, line: Num.sum(index, FIRST_LINE) })),\n );\n\nconst locationCandidates: {\n (within: LineRange): (snippet: string) => Readonly<Record<string, LineRange>>;\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>>;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (snippet: string, within: LineRange): Readonly<Record<string, LineRange>> => {\n const lines = pipe(\n numberedLines(snippet),\n Arr.filter(({ text, line }) => Str.trim(text).length >= FIRST_LINE && isWithin(line, within)),\n );\n const width = Math.max(MINIMUM_WIDTH, Math.ceil(lines.length / CHOICE_OPTION_LIMIT));\n return Rec.fromEntries(\n pipe(\n Arr.chunksOf(lines, width),\n Arr.map((group) => {\n const range = rangeOf(group);\n return [rangeKey(range), range];\n }),\n ),\n );\n },\n);\n\nconst locationQuestion: {\n (\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): (match: LocatedMatch) => ChoiceQuestion;\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n match: LocatedMatch,\n ref: string,\n candidates: Readonly<Record<string, LineRange>>,\n ): ChoiceQuestion => ({\n type: \"choice\",\n instructions: `Consider only the numbered source in state.snippets.${ref}. If it violates this rule, select the line (or range containing that line) to annotate. Rule: ${match.rule.question} Location: ${match.rule.location.question} If multiple violations exist, select the earliest one. Select ${UNKNOWN_CHOICE} if no violation exists or its location is unclear.`,\n criteria: {\n ...Rec.fromEntries(\n pipe(\n Rec.toEntries(candidates),\n Arr.map(([key, range]) => [key, rangeLabel(range)]),\n ),\n ),\n [UNKNOWN_CHOICE]: \"No clear source location for this violation\",\n },\n }),\n);\n\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst validChoice: {\n (criteria: ChoiceCriteria): (answer: Answer | undefined) => boolean;\n (answer: Answer | undefined, criteria: ChoiceCriteria): boolean;\n} = Fn.dual(DATA_FIRST_ARITY, (answer: Answer | undefined, criteria: ChoiceCriteria): boolean =>\n Option.exists(\n choiceOf(answer),\n (chosen) => Rec.has(criteria, chosen.choice) && Option.isSome(probabilityOfChoice(chosen)),\n ),\n);\n\nconst selectedLocation: {\n (\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): (answer: Answer | undefined) => Option.Option<LineRange>;\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange>;\n} = Fn.dual(\n DATA_FIRST_ARITY_3,\n (\n answer: Answer | undefined,\n candidates: Readonly<Record<string, LineRange>>,\n cutoff: number,\n ): Option.Option<LineRange> =>\n choiceOf(answer).pipe(\n Option.filter((chosen) =>\n Option.exists(probabilityOfChoice(chosen), (probability) =>\n Num.isGreaterThanOrEqualTo(probability, cutoff),\n ),\n ),\n Option.flatMap(({ choice }) => Option.fromUndefinedOr(candidates[choice])),\n ),\n);\n\nconst locationOfLine: {\n (line: number): (snippet: string) => Location;\n (snippet: string, line: number): Location;\n} = Fn.dual(DATA_FIRST_ARITY, (snippet: string, line: number): Location => {\n const text = Option.getOrElse(Arr.get(sourceLines(snippet), Num.decrement(line)), () => \"\");\n return {\n start: {\n line,\n column: Option.getOrElse(Str.search(/\\S/u)(text), () => Num.decrement(FIRST_LINE)),\n },\n end: { line, column: Str.trimEnd(text).length },\n };\n});\n\nexport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationOfLine,\n locationQuestion,\n numberedLines,\n selectedLocation,\n sourceLines,\n validChoice,\n};\nexport type { ChoiceCriteria, LocatedMatch, NumberedLine };\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Predicate,\n String as Str,\n Record as Rec,\n pipe,\n Function as Fn,\n} from \"effect\";\n\nimport { questionFor, verdictOf } from \"./answer.ts\";\nimport {\n EVERY_LINE,\n locates,\n locationCandidates,\n locationQuestion,\n numberedLines,\n validChoice,\n} from \"./location.ts\";\nimport type { ChoiceCriteria } from \"./location.ts\";\nimport type {\n Answers,\n DecisionRequest,\n DecisionResponse,\n Question,\n RequestMatch,\n Verdict,\n Verdicts,\n} from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\nconst FIRST_LINE = 1;\nconst LOCATION_SUFFIX = \"_location\";\nconst TRUNCATION_MARKER = \"/* ...truncated */\";\n\nconst refAt = (index: number): string => `s${String(index)}`;\n\nconst locationRefOf = (ref: string): string => `${ref}${LOCATION_SUFFIX}`;\n\nconst snippetRefOf = (questionId: string): string =>\n Bool.match(Str.endsWith(LOCATION_SUFFIX)(questionId), {\n onTrue: () => Str.slice(Num.decrement(FIRST_LINE), -LOCATION_SUFFIX.length)(questionId),\n onFalse: () => questionId,\n });\n\nconst truncateSnippet: {\n (maxChars: number): (text: string) => string;\n (text: string, maxChars: number): string;\n} = Fn.dual(DATA_FIRST_ARITY, (text: string, maxChars: number): string =>\n Bool.match(text.length <= maxChars, {\n onTrue: () => text,\n onFalse: () => `${Str.slice(Num.decrement(FIRST_LINE), maxChars)(text)}${TRUNCATION_MARKER}`,\n }),\n);\n\nconst numbered = (snippet: string): string =>\n pipe(\n numberedLines(snippet),\n Arr.map(({ text, line }) => `L${String(line)}| ${text}`),\n Arr.join(\"\\n\"),\n );\n\nconst contextNote = (match: RequestMatch, ref: string): string => {\n if (Predicate.isUndefined(match.context)) {\n return \"\";\n }\n return ` state.contexts.${ref} shows the source around it; use it only to understand the snippet.`;\n};\n\nconst mainQuestionFor = (match: RequestMatch, ref: string): readonly [string, Question] => [\n ref,\n questionFor(\n match.rule.answer,\n `Consider only snippet \"${ref}\" in state.snippets.${contextNote(match, ref)} ${match.rule.question}`,\n ),\n];\n\nconst questionsFor = (\n match: RequestMatch,\n ref: string,\n): readonly (readonly [string, Question])[] => {\n if (!locates(match)) {\n return [mainQuestionFor(match, ref)];\n }\n return [\n mainQuestionFor(match, ref),\n [\n locationRefOf(ref),\n locationQuestion(match, ref, locationCandidates(match.snippet, EVERY_LINE)),\n ],\n ];\n};\n\nconst snippetFor = (match: RequestMatch): string => {\n if (locates(match)) {\n return numbered(match.snippet);\n }\n return match.snippet;\n};\n\nconst contextsOf = (\n matches: readonly RequestMatch[],\n): Readonly<{ contexts?: Readonly<Record<string, string>> }> => {\n const contexts = pipe(\n matches,\n Arr.flatMap((match, index) =>\n Option.toArray(\n Option.map(Option.fromUndefinedOr(match.context), (text) => [refAt(index), text] as const),\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(contexts)) {\n return {};\n }\n return { contexts: Rec.fromEntries(contexts) };\n};\n\nconst buildRequest: {\n (matches: readonly RequestMatch[]): (model: string) => DecisionRequest;\n (model: string, matches: readonly RequestMatch[]): DecisionRequest;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (model: string, matches: readonly RequestMatch[]): DecisionRequest => ({\n model,\n state: {\n snippets: Rec.fromEntries(\n pipe(\n matches,\n Arr.map((match, index) => [refAt(index), snippetFor(match)]),\n ),\n ),\n ...contextsOf(matches),\n },\n questions: Rec.fromEntries(\n pipe(\n matches,\n Arr.flatMap((match, index) => questionsFor(match, refAt(index))),\n ),\n ),\n }),\n);\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceCriteria])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question.criteria] as const];\n }\n return [];\n }),\n );\n\nconst mainQuestionsOf = (request: DecisionRequest): readonly (readonly [string, Question])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.filter(([id]) => !Str.endsWith(LOCATION_SUFFIX)(id)),\n );\n\nconst resultOf = (\n answers: Answers,\n [ref, question]: readonly [string, Question],\n): readonly [string, Verdict] => [\n ref,\n Option.getOrThrowWith(\n verdictOf(question, answers[ref]),\n () => new Error(`response has no valid answer for \"${ref}\"`),\n ),\n];\n\nconst parseVerdicts: {\n (request: DecisionRequest): (response: DecisionResponse) => Verdicts;\n (response: DecisionResponse, request: DecisionRequest): Verdicts;\n} = Fn.dual(DATA_FIRST_ARITY, (response: DecisionResponse, request: DecisionRequest): Verdicts => {\n const { model, answers } = Option.getOrThrowWith(\n Option.liftPredicate(response, ({ model: served }) => Str.isNonEmpty(served)),\n () => new Error(\"response has no model id\"),\n );\n const results = Rec.fromEntries(\n pipe(\n mainQuestionsOf(request),\n Arr.map((entry) => resultOf(answers, entry)),\n ),\n );\n const complete = pipe(\n choiceQuestionsOf(request),\n Arr.every(([id, criteria]) => validChoice(answers[id], criteria)),\n );\n return { model, results, answers, complete };\n});\n\nexport { buildRequest, locationRefOf, parseVerdicts, refAt, snippetRefOf, truncateSnippet };\n","import {\n Array as Arr,\n Boolean as Bool,\n Number as Num,\n Option,\n Order,\n pipe,\n Record as Rec,\n String as Str,\n Function as Fn,\n} from \"effect\";\n\nimport { SEVERITY_ORDER, noulOf } from \"./answer.ts\";\nimport { CONFIDENT } from \"./schema.ts\";\nimport type { Answers, ChoiceAnswer, ChoiceQuestion, DecisionRequest } from \"./types.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\ntype ChoiceCriteria = ChoiceQuestion[\"criteria\"];\n\nconst RESPAN_MODELS = [\"respan/\"] as const;\nconst OPTION_SEPARATOR = \"__\";\nconst CERTAIN = 1;\nconst NO_SEVERITY = \"none\";\n\nconst isRespan = (model: string): boolean =>\n pipe(\n RESPAN_MODELS,\n Arr.some((prefix) => Str.startsWith(prefix)(model)),\n );\n\nconst optionIdOf: {\n (label: string): (id: string) => string;\n (id: string, label: string): string;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (id: string, label: string): string => `${id}${OPTION_SEPARATOR}${label}`,\n);\n\nconst isSeverityScale = (criteria: ChoiceCriteria): boolean =>\n pipe(Rec.keys(criteria), Arr.join(\",\")) === pipe(SEVERITY_ORDER, Arr.join(\",\"));\n\nconst levelsAboveNone = (criteria: ChoiceCriteria): readonly (readonly [string, string | null])[] =>\n pipe(\n Rec.toEntries(criteria),\n Arr.filter(([label]) => label !== NO_SEVERITY),\n );\n\ninterface Score {\n readonly label: string;\n readonly yes: number;\n}\n\nconst byYes = Order.mapInput(Order.Number, ({ yes }: Score) => yes);\n\nconst scoreOf = (answers: Answers, id: string, label: string): Option.Option<Score> =>\n Option.map(noulOf(answers[optionIdOf(id, label)]), ({ noul }) => ({ label, yes: noul }));\n\nconst scoresOf = (\n answers: Answers,\n id: string,\n labels: readonly string[],\n): Option.Option<Arr.NonEmptyReadonlyArray<Score>> =>\n pipe(\n labels,\n Arr.map((label) => scoreOf(answers, id, label)),\n Option.all,\n Option.flatMap((scores) => Option.liftPredicate(scores, Arr.isArrayNonEmpty)),\n );\n\nconst probabilitiesOf = (scores: readonly Score[]): Readonly<Record<string, number>> =>\n Rec.fromEntries(\n pipe(\n scores,\n Arr.map(({ label, yes }) => [label, yes]),\n ),\n );\n\nconst choiceAnswer = (\n choice: string,\n probabilities: Readonly<Record<string, number>>,\n): ChoiceAnswer => ({\n type: \"choice\",\n choice,\n probabilities,\n});\n\nconst bestLabel = (scores: Arr.NonEmptyReadonlyArray<Score>): ChoiceAnswer =>\n choiceAnswer(Arr.max(scores, byYes).label, probabilitiesOf(scores));\n\nconst atLeast = (scores: Arr.NonEmptyReadonlyArray<Score>): Arr.NonEmptyReadonlyArray<Score> =>\n pipe(\n scores,\n Arr.map(({ label }, index) => ({\n label,\n yes: Math.max(\n ...pipe(\n scores.slice(index),\n Arr.map(({ yes }) => yes),\n ),\n ),\n })),\n );\n\nconst severityLevel = (scores: Arr.NonEmptyReadonlyArray<Score>): ChoiceAnswer => {\n const cumulative = atLeast(scores);\n const probabilities = {\n [NO_SEVERITY]: Num.subtract(CERTAIN, Arr.headNonEmpty(cumulative).yes),\n ...probabilitiesOf(cumulative),\n };\n const reached = pipe(\n cumulative,\n Arr.findLast(({ yes }) => yes >= CONFIDENT),\n );\n return choiceAnswer(\n Option.match(reached, { onNone: () => NO_SEVERITY, onSome: ({ label }) => label }),\n probabilities,\n );\n};\n\nconst labelsAsked = (criteria: ChoiceCriteria): readonly string[] => {\n if (isSeverityScale(criteria)) {\n return pipe(\n levelsAboveNone(criteria),\n Arr.map(([label]) => label),\n );\n }\n return Rec.keys(criteria);\n};\n\nconst choiceFromYesNo = (\n answers: Answers,\n [id, { criteria }]: readonly [string, ChoiceQuestion],\n): readonly (readonly [string, ChoiceAnswer])[] => {\n const collapse = Bool.match(isSeverityScale(criteria), {\n onTrue: () => severityLevel,\n onFalse: () => bestLabel,\n });\n return scoresOf(answers, id, labelsAsked(criteria)).pipe(\n Option.map((scores) => [id, collapse(scores)] as const),\n Option.toArray,\n );\n};\n\nconst choiceQuestionsOf = (\n request: DecisionRequest,\n): readonly (readonly [string, ChoiceQuestion])[] =>\n pipe(\n Rec.toEntries(request.questions),\n Arr.flatMap(([id, question]) => {\n if (question.type === \"choice\") {\n return [[id, question] as const];\n }\n return [];\n }),\n );\n\nconst withChoices: {\n (answers: Answers): (request: DecisionRequest) => Answers;\n (request: DecisionRequest, answers: Answers): Answers;\n} = Fn.dual(DATA_FIRST_ARITY, (request: DecisionRequest, answers: Answers): Answers => {\n if (!isRespan(request.model)) {\n return answers;\n }\n return {\n ...answers,\n ...Rec.fromEntries(\n pipe(\n choiceQuestionsOf(request),\n Arr.flatMap((entry) => choiceFromYesNo(answers, entry)),\n ),\n ),\n };\n});\n\nexport { isRespan, isSeverityScale, levelsAboveNone, optionIdOf, withChoices };\nexport type { ChoiceCriteria };\n","import { Array as Arr, Option, Predicate, pipe, Record as Rec, Function as Fn } from \"effect\";\n\nimport { snippetRefOf } from \"./request.ts\";\nimport type {\n ChoiceQuestion,\n DecisionRequest,\n DecisionResponse,\n NoulQuestion,\n Question,\n} from \"./types.ts\";\nimport {\n isRespan,\n isSeverityScale,\n levelsAboveNone,\n optionIdOf,\n withChoices,\n} from \"./wire-choice.ts\";\n\nconst DATA_FIRST_ARITY = 2;\n\ntype State = DecisionRequest[\"state\"];\n\ninterface WireRequest extends Readonly<Pick<DecisionRequest, \"model\">> {\n readonly state: DecisionRequest[\"state\"] | string;\n readonly questions: Readonly<Record<string, Question>>;\n}\n\nconst sectionsOf = (name: string, entries: Readonly<Record<string, string>>): readonly string[] =>\n pipe(\n Rec.toEntries(entries),\n Arr.map(([ref, text]) => `state.${name}.${ref}:\\n${text}`),\n );\n\nconst stateAsText = ({ snippets, contexts = {} }: State): string =>\n pipe(\n [...sectionsOf(\"snippets\", snippets), ...sectionsOf(\"contexts\", contexts)],\n Arr.join(\"\\n\\n\"),\n );\n\nconst only = (\n entries: Readonly<Record<string, string>>,\n ref: string,\n): Readonly<Record<string, string>> =>\n Option.match(Option.fromUndefinedOr(entries[ref]), {\n onNone: () => ({}),\n onSome: (text) => ({ [ref]: text }),\n });\n\nconst stateOf = ({ snippets, contexts }: State, ref: string): State => {\n if (Predicate.isUndefined(contexts)) {\n return { snippets: only(snippets, ref) };\n }\n return { snippets: only(snippets, ref), contexts: only(contexts, ref) };\n};\n\nconst optionText = (label: string, description: string | null): string =>\n Option.match(Option.fromNullishOr(description), {\n onNone: () => `\"${label}\"`,\n onSome: (text) => `\"${label}\" (${text})`,\n });\n\nconst labelQuestion = (\n instructions: string,\n label: string,\n description: string | null,\n): NoulQuestion => ({\n type: \"noul\",\n instructions: `${instructions} Does the label ${optionText(label, description)} fit?`,\n});\n\nconst levelQuestion = (\n instructions: string,\n label: string,\n description: string | null,\n): NoulQuestion => ({\n type: \"noul\",\n instructions: `${instructions} Is it at least as serious as ${optionText(label, description)}?`,\n});\n\nconst yesNoQuestionsOf = (\n id: string,\n { instructions, criteria }: ChoiceQuestion,\n): readonly (readonly [string, NoulQuestion])[] => {\n if (isSeverityScale(criteria)) {\n return pipe(\n levelsAboveNone(criteria),\n Arr.map(([label, description]) => [\n optionIdOf(id, label),\n levelQuestion(instructions, label, description),\n ]),\n );\n }\n return pipe(\n Rec.toEntries(criteria),\n Arr.map(([label, description]) => [\n optionIdOf(id, label),\n labelQuestion(instructions, label, description),\n ]),\n );\n};\n\nconst asYesNo = ([id, question]: readonly [string, Question]): readonly (readonly [\n string,\n Question,\n])[] => {\n if (question.type === \"choice\") {\n return yesNoQuestionsOf(id, question);\n }\n return [[id, question]];\n};\n\nconst perSnippet = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n const bySnippet = Arr.groupBy(Rec.toEntries(request.questions), ([id]) => snippetRefOf(id));\n const wires = pipe(\n Rec.values(bySnippet),\n Arr.map((questions): WireRequest => {\n const [[id]] = questions;\n return {\n model: request.model,\n state: stateAsText(stateOf(request.state, snippetRefOf(id))),\n questions: Rec.fromEntries(\n pipe(\n questions,\n Arr.flatMap((entry) => asYesNo(entry)),\n ),\n ),\n };\n }),\n );\n if (Arr.isReadonlyArrayNonEmpty(wires)) {\n return wires;\n }\n return [request];\n};\n\nconst wireRequestsFor = (request: DecisionRequest): Arr.NonEmptyReadonlyArray<WireRequest> => {\n if (isRespan(request.model)) {\n return perSnippet(request);\n }\n return [request];\n};\n\nconst mergeResponses: {\n (\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): (request: DecisionRequest) => DecisionResponse;\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse;\n} = Fn.dual(\n DATA_FIRST_ARITY,\n (\n request: DecisionRequest,\n responses: Arr.NonEmptyReadonlyArray<DecisionResponse>,\n ): DecisionResponse => ({\n ...Arr.headNonEmpty(responses),\n answers: withChoices(\n request,\n pipe(\n responses,\n Arr.flatMap(({ answers }) => Rec.toEntries(answers)),\n Rec.fromEntries,\n ),\n ),\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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