@kamilio/wire 0.1.30 → 0.1.31
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/adapters/root.d.ts +4 -0
- package/dist/adapters/root.d.ts.map +1 -1
- package/dist/adapters/root.js +12 -1
- package/dist/adapters/root.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +3 -1
- package/dist/cli.js.map +1 -1
- package/dist/executable.d.ts.map +1 -1
- package/dist/executable.js +2 -1
- package/dist/executable.js.map +1 -1
- package/node_modules/provider-lattice/dist/browser.d.ts +4 -0
- package/node_modules/provider-lattice/dist/browser.d.ts.map +1 -0
- package/node_modules/provider-lattice/dist/browser.js +31 -0
- package/node_modules/provider-lattice/dist/browser.js.map +1 -0
- package/node_modules/provider-lattice/dist/draft.d.ts +5 -0
- package/node_modules/provider-lattice/dist/draft.d.ts.map +1 -0
- package/node_modules/provider-lattice/dist/draft.js +439 -0
- package/node_modules/provider-lattice/dist/draft.js.map +1 -0
- package/node_modules/provider-lattice/dist/index.d.ts +1 -0
- package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
- package/node_modules/provider-lattice/dist/index.js +4 -23
- package/node_modules/provider-lattice/dist/index.js.map +1 -1
- package/node_modules/provider-lattice/src/browser.ts +41 -0
- package/node_modules/provider-lattice/src/draft.ts +548 -0
- package/node_modules/provider-lattice/src/index.ts +4 -26
- package/package.json +1 -1
- package/src/adapters/root.ts +13 -2
- package/src/cli.ts +3 -1
- package/src/executable.ts +2 -1
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { RuntimeCapabilities } from "wire-core";
|
|
2
|
+
|
|
3
|
+
export type Query = <R>(fields: string, vars?: Record<string, string | null>) => Promise<R>;
|
|
4
|
+
|
|
5
|
+
export async function browser<T>(
|
|
6
|
+
runtime: RuntimeCapabilities,
|
|
7
|
+
url: URL,
|
|
8
|
+
work: (query: Query, args: string[]) => Promise<T>,
|
|
9
|
+
): Promise<T> {
|
|
10
|
+
const session = "-s=lattice-" + crypto.randomUUID();
|
|
11
|
+
const args = [session, "--raw"];
|
|
12
|
+
await runtime.process.execute("hey-browser", [
|
|
13
|
+
"run",
|
|
14
|
+
"--",
|
|
15
|
+
"playwright-cli",
|
|
16
|
+
...args,
|
|
17
|
+
"attach",
|
|
18
|
+
"--extension=chrome",
|
|
19
|
+
]);
|
|
20
|
+
const query = async <T>(fields: string, vars: Record<string, string | null> = {}): Promise<T> => {
|
|
21
|
+
const data = {
|
|
22
|
+
id: "WireLatticeRead",
|
|
23
|
+
query: "query WireLatticeRead " + fields,
|
|
24
|
+
variables: vars,
|
|
25
|
+
};
|
|
26
|
+
const code = `async page=>{const r=await page.request.post(${JSON.stringify(url.origin + "/graphql")},{maxRedirects:0,data:${JSON.stringify(data)}});return r.headers()["content-type"]?.includes("json") ? await r.json() : {errors:[{message:"Lattice HTTP "+r.status()+": sign in to this workspace in Chrome."}]}}`;
|
|
27
|
+
const result = JSON.parse(
|
|
28
|
+
(await runtime.process.execute("playwright-cli", [...args, "run-code", code])).stdout,
|
|
29
|
+
(key, value) =>
|
|
30
|
+
key === "name" && typeof value === "string" ? value.replace(/\s*\(deactivated\)\s*$/i, "") : value,
|
|
31
|
+
);
|
|
32
|
+
if (result.errors?.length)
|
|
33
|
+
throw new Error(result.errors.map((e: { message: string }) => e.message).join("; "));
|
|
34
|
+
return result.data as T;
|
|
35
|
+
};
|
|
36
|
+
try {
|
|
37
|
+
return await work(query, args);
|
|
38
|
+
} finally {
|
|
39
|
+
await runtime.process.execute("playwright-cli", [...args, "detach"]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,548 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import type { RuntimeCapabilities } from "wire-core";
|
|
5
|
+
import { browser, type Query } from "./browser.js";
|
|
6
|
+
import { richText } from "./markdown.js";
|
|
7
|
+
|
|
8
|
+
const uuid = "[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}";
|
|
9
|
+
function target(input: string, individual: boolean) {
|
|
10
|
+
const url = new URL(input);
|
|
11
|
+
const route = individual ? "response/(" + uuid + ")" : "requests";
|
|
12
|
+
const m = new RegExp("^/reviews/(" + uuid + ")/participant/" + route + "/?$", "i").exec(url.pathname);
|
|
13
|
+
if (
|
|
14
|
+
url.protocol !== "https:" ||
|
|
15
|
+
url.username ||
|
|
16
|
+
url.password ||
|
|
17
|
+
url.port ||
|
|
18
|
+
!/^[a-z0-9-]+\.latticehq\.com$/.test(url.hostname) ||
|
|
19
|
+
!m
|
|
20
|
+
)
|
|
21
|
+
throw Error("Expected a Lattice participant " + (individual ? "response" : "requests") + " URL.");
|
|
22
|
+
url.search = "";
|
|
23
|
+
url.hash = "";
|
|
24
|
+
url.pathname = url.pathname.replace(/\/$/, "");
|
|
25
|
+
return { url, cycle: m[1]!, request: m[2]! };
|
|
26
|
+
}
|
|
27
|
+
type Content = { body?: string; rating?: string; multipleSelect?: string[] };
|
|
28
|
+
type Q = {
|
|
29
|
+
id: string;
|
|
30
|
+
description: string | null;
|
|
31
|
+
isPrivate: boolean;
|
|
32
|
+
revision: {
|
|
33
|
+
__typename: string;
|
|
34
|
+
body: string;
|
|
35
|
+
choices?: string[];
|
|
36
|
+
scale?: string[];
|
|
37
|
+
question: {
|
|
38
|
+
isOptional: boolean;
|
|
39
|
+
maximumSelection?: number;
|
|
40
|
+
isBodyOptional?: boolean;
|
|
41
|
+
isMultipleChoiceOptional?: boolean;
|
|
42
|
+
isMultipleSelectOptional?: boolean;
|
|
43
|
+
isRatingOptional?: boolean;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
reviewResponse: { content: Content } | null;
|
|
47
|
+
};
|
|
48
|
+
type Review = {
|
|
49
|
+
entityId: string;
|
|
50
|
+
viewerIsResponder: boolean;
|
|
51
|
+
status: string;
|
|
52
|
+
submittedAt: string | null;
|
|
53
|
+
lockedAt: string | null;
|
|
54
|
+
closedAt: string | null;
|
|
55
|
+
isRejected: boolean;
|
|
56
|
+
reviewee: {
|
|
57
|
+
user: { name: string };
|
|
58
|
+
reviewCycle: {
|
|
59
|
+
entityId: string;
|
|
60
|
+
name: string;
|
|
61
|
+
canReviewsBeWritten: boolean;
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
reviewGroup: {
|
|
65
|
+
type: string;
|
|
66
|
+
reviewTemplate: {
|
|
67
|
+
name: string;
|
|
68
|
+
instructions: string | null;
|
|
69
|
+
wordCountLimit: number | null;
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
questions: Q[];
|
|
73
|
+
};
|
|
74
|
+
const fields = `($id:String!){viewer{r:findReviewRequest(reviewRequestId:$id){entityId viewerIsResponder status submittedAt lockedAt closedAt isRejected reviewee{user{name} reviewCycle{entityId name canReviewsBeWritten}} reviewGroup{type reviewTemplate{name instructions wordCountLimit}} questions:reviewRequestQuestions{id description isPrivate reviewResponse{content} revision:questionRevisionV2{__typename body ... on RatingQuestionRevisionInterface{scale} ... on MultipleChoiceQuestionRevision{choices} ... on MultipleChoiceAndBodyQuestionRevision{choices} ... on MultipleSelectQuestionRevision{choices} ... on MultipleSelectAndBodyQuestionRevision{choices} question{... on ReviewCycleQuestionInterface{isOptional} ... on MultipleSelectQuestion{maximumSelection} ... on MultipleSelectAndBodyQuestion{maximumSelection isBodyOptional isMultipleSelectOptional} ... on MultipleChoiceAndBodyQuestion{isBodyOptional isMultipleChoiceOptional} ... on RatingAndBodyQuestion{isBodyOptional isRatingOptional}}}}}}}`;
|
|
75
|
+
const norm = (s: string) => s.trim().replace(/\s+/g, " ");
|
|
76
|
+
const heading = (q: Q) => norm(richText(q.revision.body));
|
|
77
|
+
const guide = (s: string) =>
|
|
78
|
+
s
|
|
79
|
+
.split(/\r?\n/)
|
|
80
|
+
.map((l) => "> " + l)
|
|
81
|
+
.join("\n");
|
|
82
|
+
function intro(r: Review, url: URL) {
|
|
83
|
+
const t = r.reviewGroup.reviewTemplate;
|
|
84
|
+
return [
|
|
85
|
+
`# ${t.name} — ${r.reviewee.user.name}`,
|
|
86
|
+
`[Open in Lattice](${url.href})`,
|
|
87
|
+
r.reviewee.reviewCycle.name,
|
|
88
|
+
t.instructions && richText(t.instructions),
|
|
89
|
+
"Keep every question heading. Write below its instructions. Blank answers keep existing drafts. For choices, use one “Selected: label” line per choice; for a rating, use “Rating: label”.",
|
|
90
|
+
]
|
|
91
|
+
.filter(Boolean)
|
|
92
|
+
.join("\n\n");
|
|
93
|
+
}
|
|
94
|
+
function help(q: Q, limit: number | null) {
|
|
95
|
+
const { question, choices, scale } = q.revision;
|
|
96
|
+
return guide(
|
|
97
|
+
[
|
|
98
|
+
question.isOptional ? "Optional." : "Required for submission.",
|
|
99
|
+
q.isPrivate ? "Hidden from the reviewee." : "",
|
|
100
|
+
q.description && richText(q.description),
|
|
101
|
+
choices?.length ? "Choices: " + choices.join(" · ") : "",
|
|
102
|
+
scale?.length ? "Ratings: " + scale.join(" · ") : "",
|
|
103
|
+
question.maximumSelection ? "Maximum selections: " + question.maximumSelection + "." : "",
|
|
104
|
+
question.isBodyOptional !== undefined
|
|
105
|
+
? "Comment: " + (question.isBodyOptional ? "optional." : "required for submission.")
|
|
106
|
+
: "",
|
|
107
|
+
limit && /Body/.test(q.revision.__typename) ? "Word limit: " + limit + "." : "",
|
|
108
|
+
]
|
|
109
|
+
.filter(Boolean)
|
|
110
|
+
.join("\n"),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
function nativeBody(md: string) {
|
|
114
|
+
let fence = "";
|
|
115
|
+
return md
|
|
116
|
+
.split("\n")
|
|
117
|
+
.map((l, i, a) => {
|
|
118
|
+
const m = /^ {0,3}(`{3,}|~{3,})/.exec(l)?.[1];
|
|
119
|
+
const inside = !!fence;
|
|
120
|
+
if (m && (!fence || (m[0] === fence[0] && m.length >= fence.length))) fence = fence ? "" : m;
|
|
121
|
+
if (!l.trim() && !inside && i > 0 && a[i - 1]!.trim()) return "\n<br>\n";
|
|
122
|
+
let text = l
|
|
123
|
+
.replace(/&/g, "&")
|
|
124
|
+
.replace(/</g, "<")
|
|
125
|
+
.replace(/>/g, ">")
|
|
126
|
+
.replace(/"/g, """)
|
|
127
|
+
.replace(/'/g, "'");
|
|
128
|
+
if (!inside) text = text.replace(/^(\s*)>(?=\s)/, "$1>");
|
|
129
|
+
return text;
|
|
130
|
+
})
|
|
131
|
+
.join("\n");
|
|
132
|
+
}
|
|
133
|
+
function draftDocument(r: Review, url: URL, markdown?: string) {
|
|
134
|
+
const titles = r.questions.map(heading);
|
|
135
|
+
if (new Set(titles).size !== titles.length)
|
|
136
|
+
throw Error("Duplicate question names in this form; cannot match sections safely.");
|
|
137
|
+
const preamble = intro(r, url),
|
|
138
|
+
limit = r.reviewGroup.reviewTemplate.wordCountLimit;
|
|
139
|
+
const guides = r.questions.map((q) => help(q, limit));
|
|
140
|
+
const currentAnswers = titles.map((_, i) => {
|
|
141
|
+
const q = r.questions[i]!,
|
|
142
|
+
c = q.reviewResponse?.content;
|
|
143
|
+
const selected = (c?.multipleSelect ?? [])
|
|
144
|
+
.map((n) => "Selected: " + choice(q.revision.choices, Number(n)))
|
|
145
|
+
.join("\n");
|
|
146
|
+
const rating =
|
|
147
|
+
c?.rating != null && String(c.rating) !== ""
|
|
148
|
+
? "Rating: " + choice(q.revision.scale, Number(c.rating) - 1)
|
|
149
|
+
: "";
|
|
150
|
+
const body = c?.body && richText(c.body);
|
|
151
|
+
return [selected || rating, body && !selected && !rating && (q.revision.choices || q.revision.scale) ? "Comment: " + body : body].filter(Boolean).join("\n\n");
|
|
152
|
+
});
|
|
153
|
+
const template =
|
|
154
|
+
[
|
|
155
|
+
preamble,
|
|
156
|
+
...titles.map((h, i) => ["## " + h, guides[i], currentAnswers[i]].filter(Boolean).join("\n\n")),
|
|
157
|
+
].join("\n\n") + "\n";
|
|
158
|
+
const local: Record<string, string> = {};
|
|
159
|
+
const updates: { reviewRequestQuestionId: string; content: Content }[] = [];
|
|
160
|
+
if (markdown === undefined) return { template, updates, local };
|
|
161
|
+
let src = markdown
|
|
162
|
+
.replace(/^\uFEFF/, "")
|
|
163
|
+
.replace(/\r\n?/g, "\n")
|
|
164
|
+
.trim();
|
|
165
|
+
if (src.startsWith("# ")) {
|
|
166
|
+
if (!src.startsWith(preamble + "\n"))
|
|
167
|
+
throw Error("Template header does not match this review. Get a fresh template.");
|
|
168
|
+
src = src.slice(preamble.length).trim();
|
|
169
|
+
}
|
|
170
|
+
const sections = new Map<string, string[]>();
|
|
171
|
+
let current: string[] | undefined;
|
|
172
|
+
let fence = "";
|
|
173
|
+
for (const line of src.split("\n")) {
|
|
174
|
+
const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
|
|
175
|
+
if (!fence && /^##(?:\s|$)/.test(line)) {
|
|
176
|
+
const h = norm(line.slice(2));
|
|
177
|
+
if (!titles.includes(h)) throw Error("Unknown question: " + h);
|
|
178
|
+
if (sections.has(h)) throw Error("Repeated question: " + h);
|
|
179
|
+
current = [];
|
|
180
|
+
sections.set(h, current);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (!current) throw Error("Expected a ## question heading.");
|
|
184
|
+
current.push(line);
|
|
185
|
+
if (marker && (!fence || (marker[0] === fence[0] && marker.length >= fence.length)))
|
|
186
|
+
fence = fence ? "" : marker;
|
|
187
|
+
}
|
|
188
|
+
if (fence) throw Error("Unclosed code fence.");
|
|
189
|
+
for (const [i, q] of r.questions.entries()) {
|
|
190
|
+
const h = titles[i]!,
|
|
191
|
+
lines = sections.get(h);
|
|
192
|
+
if (!lines) throw Error("Missing question: " + h);
|
|
193
|
+
let answer = lines.join("\n").trim();
|
|
194
|
+
if (answer === guides[i] || answer.startsWith(guides[i] + "\n"))
|
|
195
|
+
answer = answer.slice(guides[i]!.length).trim();
|
|
196
|
+
else if (answer.startsWith("> Required for submission.") || answer.startsWith("> Optional."))
|
|
197
|
+
throw Error("Template guidance changed for: " + h);
|
|
198
|
+
local[q.id] = hash(answer);
|
|
199
|
+
if (!answer || answer === currentAnswers[i]) continue;
|
|
200
|
+
const t = q.revision.__typename,
|
|
201
|
+
hasBody = /^(?:Body|(?:Rating|MultipleChoice|MultipleSelect)AndBody)QuestionRevision$/.test(t);
|
|
202
|
+
const old = q.reviewResponse?.content;
|
|
203
|
+
const content: Content = {};
|
|
204
|
+
if (old?.body) content.body = old.body;
|
|
205
|
+
if (old?.rating) content.rating = String(old.rating);
|
|
206
|
+
if (old?.multipleSelect?.length) content.multipleSelect = old.multipleSelect.map(String);
|
|
207
|
+
const { choices, scale, question } = q.revision;
|
|
208
|
+
if (choices || scale) {
|
|
209
|
+
const labels = choices ?? scale!,
|
|
210
|
+
prefix = choices ? "Selected: " : "Rating: ";
|
|
211
|
+
const rows = answer.split("\n");
|
|
212
|
+
const canon = (v: string) => norm(v).normalize("NFC").toLowerCase();
|
|
213
|
+
const normalized = labels.map(canon);
|
|
214
|
+
const binary =
|
|
215
|
+
t.startsWith("MultipleChoice") &&
|
|
216
|
+
labels.length === 2 &&
|
|
217
|
+
(["yes", "no"].every((x) => normalized.includes(x)) ||
|
|
218
|
+
["true", "false"].every((x) => normalized.includes(x)));
|
|
219
|
+
const indexOf = (v: string) => {
|
|
220
|
+
let key = canon(v);
|
|
221
|
+
if (binary && ["yes", "true", "no", "false"].includes(key))
|
|
222
|
+
key =
|
|
223
|
+
key === "yes" || key === "true"
|
|
224
|
+
? normalized.includes("yes")
|
|
225
|
+
? "yes"
|
|
226
|
+
: "true"
|
|
227
|
+
: normalized.includes("no")
|
|
228
|
+
? "no"
|
|
229
|
+
: "false";
|
|
230
|
+
const n = normalized.indexOf(key);
|
|
231
|
+
return n >= 0 && normalized.lastIndexOf(key) === n ? n : -1;
|
|
232
|
+
};
|
|
233
|
+
const picked: number[] = [],
|
|
234
|
+
seen = new Set<number>();
|
|
235
|
+
while (rows.length) {
|
|
236
|
+
const line = rows[0]!.trim();
|
|
237
|
+
if (!line) break;
|
|
238
|
+
const explicit = line.match(/^(Selected|Rating):\s*(.*)$/i);
|
|
239
|
+
const check = line.match(/^[-*] \[([ xX])\]\s+(.+)$/);
|
|
240
|
+
const bullet = t.startsWith("MultipleSelect") && line.match(/^[-*]\s+(.+)$/);
|
|
241
|
+
if (explicit && explicit[1]!.toLowerCase() + ": " !== prefix.toLowerCase())
|
|
242
|
+
throw Error("Invalid choice field for: " + h);
|
|
243
|
+
const label = explicit?.[2] ?? check?.[2] ?? (bullet ? bullet[1]! : line);
|
|
244
|
+
const n = indexOf(label);
|
|
245
|
+
if (n < 0 && !explicit && !check && !bullet) break;
|
|
246
|
+
if (n < 0) throw Error("Invalid choice for " + h + ": " + label + ". Options: " + labels.join(" · "));
|
|
247
|
+
if (seen.has(n)) throw Error("Repeated choice for: " + h);
|
|
248
|
+
seen.add(n);
|
|
249
|
+
if (!check || check[1] !== " ") picked.push(n);
|
|
250
|
+
rows.shift();
|
|
251
|
+
}
|
|
252
|
+
if (
|
|
253
|
+
(!t.startsWith("MultipleSelect") && picked.length > 1) ||
|
|
254
|
+
(question.maximumSelection && picked.length > question.maximumSelection)
|
|
255
|
+
)
|
|
256
|
+
throw Error("Invalid number of choices for: " + h);
|
|
257
|
+
if (picked.length) {
|
|
258
|
+
if (choices) content.multipleSelect = picked.map(String);
|
|
259
|
+
else content.rating = String(picked[0]! + 1);
|
|
260
|
+
}
|
|
261
|
+
answer = rows.join("\n").trim();
|
|
262
|
+
if (answer) {
|
|
263
|
+
if (
|
|
264
|
+
!hasBody ||
|
|
265
|
+
/^(?:Selected|Rating):/im.test(answer) ||
|
|
266
|
+
(!picked.length && !/^Comment:\s*/i.test(answer))
|
|
267
|
+
)
|
|
268
|
+
throw Error("Invalid choice for " + h + ". Options: " + labels.join(" · "));
|
|
269
|
+
answer = answer.replace(/^Comment:\s*/i, "");
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (answer) {
|
|
273
|
+
if (!hasBody) throw Error("Unsupported question type: " + t);
|
|
274
|
+
if (limit && answer.split(/\s+/).length > limit) throw Error("Word limit exceeded for: " + h);
|
|
275
|
+
content.body = nativeBody(answer);
|
|
276
|
+
}
|
|
277
|
+
if (
|
|
278
|
+
content.body !== old?.body ||
|
|
279
|
+
content.rating !== (old?.rating == null ? undefined : String(old.rating)) ||
|
|
280
|
+
JSON.stringify(content.multipleSelect ?? []) !== JSON.stringify((old?.multipleSelect ?? []).map(String))
|
|
281
|
+
)
|
|
282
|
+
updates.push({ reviewRequestQuestionId: q.id, content });
|
|
283
|
+
}
|
|
284
|
+
return { template, updates, local };
|
|
285
|
+
}
|
|
286
|
+
function hash(text: string) {
|
|
287
|
+
return createHash("sha256").update(text).digest("hex");
|
|
288
|
+
}
|
|
289
|
+
function choice(labels: string[] | undefined, n: number) {
|
|
290
|
+
if (labels?.[n] === undefined) throw Error("Unknown Lattice choice index.");
|
|
291
|
+
return labels[n];
|
|
292
|
+
}
|
|
293
|
+
async function loadReview(query: Query, cycle: string, request: string) {
|
|
294
|
+
const {
|
|
295
|
+
viewer: { r },
|
|
296
|
+
} = await query<{ viewer: { r: Review | null } }>(fields, { id: request });
|
|
297
|
+
if (!r || r.entityId !== request || !r.viewerIsResponder || r.reviewee.reviewCycle.entityId !== cycle)
|
|
298
|
+
throw Error("This is not your review assignment for that cycle.");
|
|
299
|
+
if (r.submittedAt || r.lockedAt || r.closedAt || r.isRejected || !r.reviewee.reviewCycle.canReviewsBeWritten)
|
|
300
|
+
throw Error("This review is not open for draft writing.");
|
|
301
|
+
return r;
|
|
302
|
+
}
|
|
303
|
+
export async function latticeReviewDraft(runtime: RuntimeCapabilities, input: string, markdown?: string) {
|
|
304
|
+
const { url, cycle, request } = target(input, true);
|
|
305
|
+
return browser(runtime, url, async (query, args) => {
|
|
306
|
+
const r = await loadReview(query, cycle, request);
|
|
307
|
+
const { template, updates } = draftDocument(r, url, markdown);
|
|
308
|
+
if (markdown === undefined) return template;
|
|
309
|
+
if (!updates.length) return "No draft changes.";
|
|
310
|
+
await save(runtime, url, args, request, updates);
|
|
311
|
+
return `Saved ${updates.length} draft answer(s). Nothing was submitted.`;
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
async function save(
|
|
315
|
+
runtime: RuntimeCapabilities,
|
|
316
|
+
url: URL,
|
|
317
|
+
args: string[],
|
|
318
|
+
request: string,
|
|
319
|
+
updates: ReturnType<typeof draftDocument>["updates"],
|
|
320
|
+
) {
|
|
321
|
+
const mutation =
|
|
322
|
+
"mutation SaveDraftReviewResponsesMutation($input:SaveDraftReviewResponsesInput!){saveDraftReviewResponses(input:$input){errors results{reviewRequestQuestion{id reviewResponse{content}} reviewRequest{entityId submittedAt}}}}";
|
|
323
|
+
const data = {
|
|
324
|
+
id: "SaveDraftReviewResponsesMutation",
|
|
325
|
+
query: mutation,
|
|
326
|
+
variables: { input: { reviewRequestQuestions: updates } },
|
|
327
|
+
};
|
|
328
|
+
const dir = await mkdtemp(resolve(".wire-lattice-"));
|
|
329
|
+
try {
|
|
330
|
+
const file = join(dir, "draft.js");
|
|
331
|
+
await writeFile(
|
|
332
|
+
file,
|
|
333
|
+
`async page=>{const r=await page.request.post(${JSON.stringify(url.origin + "/graphql")},{maxRedirects:0,data:${JSON.stringify(data)}});return await r.json()}`,
|
|
334
|
+
{ mode: 0o600 },
|
|
335
|
+
);
|
|
336
|
+
const result = JSON.parse(
|
|
337
|
+
(await runtime.process.execute("playwright-cli", [...args, "run-code", "--filename=" + file])).stdout,
|
|
338
|
+
);
|
|
339
|
+
const saved = result.data?.saveDraftReviewResponses;
|
|
340
|
+
if (
|
|
341
|
+
result.errors?.length ||
|
|
342
|
+
!saved ||
|
|
343
|
+
saved.errors?.length ||
|
|
344
|
+
saved.results?.length !== updates.length ||
|
|
345
|
+
!updates.every((u) =>
|
|
346
|
+
saved.results.some(
|
|
347
|
+
(v: {
|
|
348
|
+
reviewRequest: { entityId: string; submittedAt: string | null };
|
|
349
|
+
reviewRequestQuestion: {
|
|
350
|
+
id: string;
|
|
351
|
+
reviewResponse: { content: Content };
|
|
352
|
+
};
|
|
353
|
+
}) => {
|
|
354
|
+
const c = v.reviewRequestQuestion.reviewResponse?.content;
|
|
355
|
+
return (
|
|
356
|
+
v.reviewRequest.entityId === request &&
|
|
357
|
+
v.reviewRequest.submittedAt === null &&
|
|
358
|
+
v.reviewRequestQuestion.id === u.reviewRequestQuestionId &&
|
|
359
|
+
!!c &&
|
|
360
|
+
(!u.content.body || c.body === u.content.body) &&
|
|
361
|
+
(!u.content.rating || String(c.rating) === u.content.rating) &&
|
|
362
|
+
(!u.content.multipleSelect ||
|
|
363
|
+
JSON.stringify(c.multipleSelect?.map(String)) === JSON.stringify(u.content.multipleSelect))
|
|
364
|
+
);
|
|
365
|
+
},
|
|
366
|
+
),
|
|
367
|
+
)
|
|
368
|
+
)
|
|
369
|
+
throw Error("Lattice did not confirm every draft answer. Check the review before retrying.");
|
|
370
|
+
} finally {
|
|
371
|
+
await rm(dir, { recursive: true });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function openRequests(query: Query, cycle: string) {
|
|
376
|
+
type Row = {
|
|
377
|
+
entityId: string;
|
|
378
|
+
status: string;
|
|
379
|
+
viewerIsResponder: boolean;
|
|
380
|
+
submittedAt: string | null;
|
|
381
|
+
closedAt: string | null;
|
|
382
|
+
lockedAt: string | null;
|
|
383
|
+
isRejected: boolean;
|
|
384
|
+
reviewee: { user: { name: string } };
|
|
385
|
+
reviewGroup: { type: string };
|
|
386
|
+
};
|
|
387
|
+
const rows = new Map<string, Row>();
|
|
388
|
+
const load = (cursor: string | null) =>
|
|
389
|
+
query<{
|
|
390
|
+
viewer: {
|
|
391
|
+
cycle: {
|
|
392
|
+
canReviewsBeWritten: boolean;
|
|
393
|
+
groups: {
|
|
394
|
+
id: string;
|
|
395
|
+
requests: {
|
|
396
|
+
edges: { node: Row }[];
|
|
397
|
+
pageInfo: { hasNextPage: boolean; endCursor: string | null };
|
|
398
|
+
};
|
|
399
|
+
}[];
|
|
400
|
+
};
|
|
401
|
+
};
|
|
402
|
+
}>(
|
|
403
|
+
`($cycle:String!,$after:String){viewer{cycle:findReviewCycle(reviewCycleId:$cycle){canReviewsBeWritten groups:viewerReviewGroupsToRespond{id requests:viewerReviewRequests(first:50,after:$after){pageInfo{hasNextPage endCursor} edges{node{entityId status viewerIsResponder submittedAt closedAt lockedAt isRejected reviewee{user{name}} reviewGroup{type}}}}}}}}`,
|
|
404
|
+
{ cycle, after: cursor },
|
|
405
|
+
);
|
|
406
|
+
const first = (await load(null)).viewer.cycle;
|
|
407
|
+
if (!first.canReviewsBeWritten) return [];
|
|
408
|
+
for (const g of first.groups) {
|
|
409
|
+
let page = g.requests;
|
|
410
|
+
const cursors = new Set<string>();
|
|
411
|
+
for (;;) {
|
|
412
|
+
for (const { node: r } of page.edges)
|
|
413
|
+
if (r.viewerIsResponder && !r.submittedAt && !r.closedAt && !r.lockedAt && !r.isRejected)
|
|
414
|
+
rows.set(r.entityId, r);
|
|
415
|
+
if (!page.pageInfo.hasNextPage) break;
|
|
416
|
+
const after = page.pageInfo.endCursor;
|
|
417
|
+
if (!after || cursors.has(after)) throw Error("Lattice pagination did not advance.");
|
|
418
|
+
cursors.add(after);
|
|
419
|
+
page = (await load(after)).viewer.cycle.groups.find((x) => x.id === g.id)!.requests;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return [...rows.values()];
|
|
423
|
+
}
|
|
424
|
+
export async function listLatticeReviewRequests(runtime: RuntimeCapabilities, input: string) {
|
|
425
|
+
const { url, cycle } = target(input, false);
|
|
426
|
+
return browser(runtime, url, async (query) => {
|
|
427
|
+
return (
|
|
428
|
+
(await openRequests(query, cycle))
|
|
429
|
+
.map(
|
|
430
|
+
(r) =>
|
|
431
|
+
`- [${r.reviewee.user.name.replace(/[\\[\]]/g, "\\$&")}](${url.origin}/reviews/${cycle}/participant/response/${r.entityId}) · ${r.reviewGroup.type} · ${r.status}`,
|
|
432
|
+
)
|
|
433
|
+
.join("\n") || "No open review requests."
|
|
434
|
+
);
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
type Baseline = Record<string, { file: string; questions: Record<string, { local: string; remote: string }> }>;
|
|
439
|
+
function remoteHash(c: Content | undefined) {
|
|
440
|
+
return hash(JSON.stringify([c?.body ?? "", String(c?.rating ?? ""), (c?.multipleSelect ?? []).map(String)]));
|
|
441
|
+
}
|
|
442
|
+
export async function syncLatticeDrafts(
|
|
443
|
+
runtime: RuntimeCapabilities,
|
|
444
|
+
input: string | undefined,
|
|
445
|
+
directory: string,
|
|
446
|
+
) {
|
|
447
|
+
const stateFile = join(directory, ".wire-lattice-drafts.json");
|
|
448
|
+
const lock = join(directory, ".wire-lattice-sync.lock");
|
|
449
|
+
await mkdir(lock, { mode: 0o700 });
|
|
450
|
+
try {
|
|
451
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
452
|
+
const state: Baseline = entries.some((e) => e.name === ".wire-lattice-drafts.json")
|
|
453
|
+
? JSON.parse(await readFile(stateFile, "utf8"))
|
|
454
|
+
: {};
|
|
455
|
+
const known = [...new Set(Object.keys(state).map((s) => s.replace(/\/response\/[^/]+$/, "/requests")))];
|
|
456
|
+
if (!input && known.length !== 1) throw Error("Provide the Lattice cycle requests URL.");
|
|
457
|
+
const { url, cycle } = target(input ?? known[0]!, false);
|
|
458
|
+
const docs = new Map<string, { name: string; md: string }>();
|
|
459
|
+
const names = new Set(entries.map((e) => e.name.toLowerCase()));
|
|
460
|
+
for (const e of entries) {
|
|
461
|
+
if (!e.isFile() || !e.name.endsWith(".md")) continue;
|
|
462
|
+
const md = await readFile(join(directory, e.name), "utf8");
|
|
463
|
+
const source = /^\[Open in Lattice\]\((https:\/\/[^)]+)\)$/m.exec(md)?.[1];
|
|
464
|
+
if (!source) continue;
|
|
465
|
+
if (docs.has(source)) throw Error("Multiple draft files for " + source);
|
|
466
|
+
docs.set(source, { name: e.name, md });
|
|
467
|
+
}
|
|
468
|
+
return await browser(runtime, url, async (query, args) => {
|
|
469
|
+
const jobs = [];
|
|
470
|
+
let created = 0,
|
|
471
|
+
answers = 0;
|
|
472
|
+
for (const row of await openRequests(query, cycle)) {
|
|
473
|
+
const address = new URL("response/" + row.entityId, url);
|
|
474
|
+
const key = address.href,
|
|
475
|
+
prev = state[key],
|
|
476
|
+
doc = docs.get(key);
|
|
477
|
+
if (prev && !doc) throw Error("Cannot find the draft for " + key + " (previously " + prev.file + ").");
|
|
478
|
+
const r = await loadReview(query, cycle, row.entityId);
|
|
479
|
+
const template = draftDocument(r, address).template;
|
|
480
|
+
let name = doc?.name;
|
|
481
|
+
if (!name) {
|
|
482
|
+
const stem = [r.reviewee.reviewCycle.name, r.reviewGroup.type, r.reviewee.user.name]
|
|
483
|
+
.join(" - ")
|
|
484
|
+
.normalize("NFC")
|
|
485
|
+
.replace(/[^\p{L}\p{M}\p{N}]+/gu, "-")
|
|
486
|
+
.replace(/^-|-$/g, "")
|
|
487
|
+
.slice(0, 160);
|
|
488
|
+
name = stem + ".md";
|
|
489
|
+
for (let n = 2; names.has(name.toLowerCase()); n++) name = stem + "-" + n + ".md";
|
|
490
|
+
names.add(name.toLowerCase());
|
|
491
|
+
}
|
|
492
|
+
const parsed = draftDocument(r, address, doc?.md ?? template);
|
|
493
|
+
const updates = parsed.updates.filter((u) => {
|
|
494
|
+
const old = prev?.questions[u.reviewRequestQuestionId];
|
|
495
|
+
if (!doc || old?.local === parsed.local[u.reviewRequestQuestionId]) return false;
|
|
496
|
+
const q = r.questions.find((q) => q.id === u.reviewRequestQuestionId)!;
|
|
497
|
+
const current = remoteHash(q.reviewResponse?.content);
|
|
498
|
+
if (old ? old.remote !== current : current !== remoteHash(undefined))
|
|
499
|
+
throw Error(
|
|
500
|
+
"Draft conflict: " +
|
|
501
|
+
name +
|
|
502
|
+
" / " +
|
|
503
|
+
heading(q) +
|
|
504
|
+
". Compare with Lattice before filling this review.",
|
|
505
|
+
);
|
|
506
|
+
return true;
|
|
507
|
+
});
|
|
508
|
+
const questions = Object.fromEntries(
|
|
509
|
+
r.questions.map((q) => {
|
|
510
|
+
const local = parsed.local[q.id]!,
|
|
511
|
+
old = prev?.questions[q.id],
|
|
512
|
+
saved = updates.find((u) => u.reviewRequestQuestionId === q.id);
|
|
513
|
+
return [
|
|
514
|
+
q.id,
|
|
515
|
+
{
|
|
516
|
+
local,
|
|
517
|
+
remote:
|
|
518
|
+
old && old.local === local
|
|
519
|
+
? old.remote
|
|
520
|
+
: remoteHash(saved?.content ?? q.reviewResponse?.content),
|
|
521
|
+
},
|
|
522
|
+
];
|
|
523
|
+
}),
|
|
524
|
+
);
|
|
525
|
+
jobs.push({ key, name, template, create: !doc, updates, questions, address, request: row.entityId });
|
|
526
|
+
}
|
|
527
|
+
for (const job of jobs) {
|
|
528
|
+
if (job.create) {
|
|
529
|
+
await writeFile(join(directory, job.name), job.template, { flag: "wx", mode: 0o600 });
|
|
530
|
+
created++;
|
|
531
|
+
}
|
|
532
|
+
if (job.updates.length) {
|
|
533
|
+
await save(runtime, job.address, args, job.request, job.updates);
|
|
534
|
+
answers += job.updates.length;
|
|
535
|
+
}
|
|
536
|
+
const next = { file: job.name, questions: job.questions };
|
|
537
|
+
if (JSON.stringify(state[job.key]) === JSON.stringify(next)) continue;
|
|
538
|
+
state[job.key] = next;
|
|
539
|
+
const tmp = join(lock, "state.json");
|
|
540
|
+
await writeFile(tmp, JSON.stringify(state) + "\n", { mode: 0o600 });
|
|
541
|
+
await rename(tmp, stateFile);
|
|
542
|
+
}
|
|
543
|
+
return `${jobs.length} open reviews; ${created} placeholder(s) created; ${answers} draft answer(s) saved. Nothing was submitted.`;
|
|
544
|
+
});
|
|
545
|
+
} finally {
|
|
546
|
+
await rm(lock, { recursive: true });
|
|
547
|
+
}
|
|
548
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { browser } from "./browser.js";
|
|
2
|
+
export { latticeReviewDraft, listLatticeReviewRequests, syncLatticeDrafts } from "./draft.js";
|
|
1
3
|
import { defineService, type AddMarkdown, type FetchedDocument, type RuntimeCapabilities } from "wire-core";
|
|
2
4
|
import { richText } from "./markdown.js";
|
|
3
5
|
|
|
@@ -141,29 +143,7 @@ const doc = (title: string, url: string, parts: string[]): FetchedDocument => ({
|
|
|
141
143
|
});
|
|
142
144
|
|
|
143
145
|
async function read(runtime: RuntimeCapabilities, url: URL, add?: AddMarkdown) {
|
|
144
|
-
|
|
145
|
-
const args = [session, "--raw"];
|
|
146
|
-
await runtime.process.execute("hey-browser", [
|
|
147
|
-
"run",
|
|
148
|
-
"--",
|
|
149
|
-
"playwright-cli",
|
|
150
|
-
...args,
|
|
151
|
-
"attach",
|
|
152
|
-
"--extension=chrome",
|
|
153
|
-
]);
|
|
154
|
-
const query = async <T>(fields: string, vars: Record<string, string | null> = {}): Promise<T> => {
|
|
155
|
-
const data = { id: "WireLatticeRead", query: "query WireLatticeRead " + fields, variables: vars };
|
|
156
|
-
const code = `async page=>{const r=await page.request.post(${JSON.stringify(url.origin + "/graphql")},{maxRedirects:0,data:${JSON.stringify(data)}});return r.headers()["content-type"]?.includes("json") ? await r.json() : {errors:[{message:"Lattice HTTP "+r.status()+": sign in to this workspace in Chrome."}]}}`;
|
|
157
|
-
const result = JSON.parse(
|
|
158
|
-
(await runtime.process.execute("playwright-cli", [...args, "run-code", code])).stdout,
|
|
159
|
-
(key, value) =>
|
|
160
|
-
key === "name" && typeof value === "string" ? value.replace(/\s*\(deactivated\)\s*$/i, "") : value,
|
|
161
|
-
);
|
|
162
|
-
if (result.errors?.length)
|
|
163
|
-
throw new Error(result.errors.map((e: { message: string }) => e.message).join("; "));
|
|
164
|
-
return result.data as T;
|
|
165
|
-
};
|
|
166
|
-
try {
|
|
146
|
+
return browser(runtime, url, async (query) => {
|
|
167
147
|
const viewer = (
|
|
168
148
|
await query<{ viewer: { user: Person & { entityId: string } } }>("{ viewer { user { name entityId } } }")
|
|
169
149
|
).viewer.user;
|
|
@@ -484,9 +464,7 @@ async function read(runtime: RuntimeCapabilities, url: URL, add?: AddMarkdown) {
|
|
|
484
464
|
const document = doc("Lattice — " + viewer.name, origin + path, parts);
|
|
485
465
|
const file = index + ".md";
|
|
486
466
|
return finish(file, document);
|
|
487
|
-
}
|
|
488
|
-
await runtime.process.execute("playwright-cli", [...args, "detach"]);
|
|
489
|
-
}
|
|
467
|
+
});
|
|
490
468
|
}
|
|
491
469
|
|
|
492
470
|
export const latticeService = defineService<RuntimeCapabilities>({
|
package/package.json
CHANGED
package/src/adapters/root.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { Auth, AuthResult, AuthService } from "../auth.js";
|
|
|
8
8
|
|
|
9
9
|
export type WireRoot = Group;
|
|
10
10
|
export type TextInputReader = () => Promise<string>;
|
|
11
|
-
export type WireRootOptions = Readonly<{ allowPaste: boolean; scrapeZoom?: () => ReturnType<typeof zoomProvider.scrape> }>;
|
|
11
|
+
export type WireRootOptions = Readonly<{ allowPaste: boolean; latticeSync?: (url: string | undefined) => Promise<string>; latticeRequests?: (url: string) => Promise<string>; latticeTemplate?: (url: string) => Promise<string>; latticeFill?: (url: string, file: string) => Promise<string>; scrapeZoom?: () => ReturnType<typeof zoomProvider.scrape> }>;
|
|
12
12
|
|
|
13
13
|
const authServices = ["asana", "chatgpt", "gmail", "google-docs", "notion", "slack", "zoom"] as const;
|
|
14
14
|
const removedCliCommandNames = Object.freeze({
|
|
@@ -587,7 +587,18 @@ export function createRoot(wire: Wire, currentDirectory: string, auth?: Auth, re
|
|
|
587
587
|
scope: ["cli", "mcp", "sdk"],
|
|
588
588
|
children: [
|
|
589
589
|
defaultAttach,
|
|
590
|
-
...(latticeRoot ? [defineGroup({ name: "lattice", scope: ["cli"], description: "Read
|
|
590
|
+
...(latticeRoot ? [defineGroup({ name: "lattice", scope: ["cli"], description: "Read reviews and fill your drafts.", children: [
|
|
591
|
+
...([["requests","List open assignments from a Lattice review requests URL.",options.latticeRequests],["template","Print the current review form as editable Markdown.",options.latticeTemplate]] as const).flatMap(([name,description,run]) => run ? [defineCommand({
|
|
592
|
+
name, description, scope:["cli"], positional:["url"], params:S.Object({url:S.String({description:"Lattice review URL."})}), handler:({params})=>userFacing(()=>run(params.url)), render:render<string>(v=>v),
|
|
593
|
+
})] : []),
|
|
594
|
+
...(options.latticeSync ? [defineCommand({name:"sync-drafts",description:"Create missing files here and save edited answers as drafts. Remembers the cycle.",scope:["cli"],positional:["url"],
|
|
595
|
+
params:S.Object({url:S.Optional(S.String({description:"Cycle requests URL; required on the first run."}))}),
|
|
596
|
+
handler:({params})=>userFacing(()=>options.latticeSync!(params.url)),render:render<string>(v=>v),
|
|
597
|
+
})] : []),
|
|
598
|
+
...(options.latticeFill ? [defineCommand({name:"fill",description:"Save a review draft without submitting. Use the displayed option, yes/no or true/false for binary choices, or one option per line for multiple selections.",scope:["cli"],positional:["url","file"],
|
|
599
|
+
params:S.Object({url:S.String({description:"Your Lattice review response URL."}),file:S.String({description:"Markdown file with the template’s question headings."})}),
|
|
600
|
+
handler:({params})=>userFacing(()=>options.latticeFill!(params.url,params.file)),render:render<string>(v=>v),
|
|
601
|
+
})] : []),
|
|
591
602
|
defineCommand({ name: "scrape", hidden: true, scope: ["cli"], description: "Download Lattice history.", params: S.Object({}),
|
|
592
603
|
handler: () => userFacing(async () => wire.downloadSource(await latticeRoot(), currentDirectory)), render: wirePresentation.download }),
|
|
593
604
|
] })] : []),
|