@dench.com/cli 2.9.1 → 2.9.2

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.
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Pure parsing for `dench meetings import` and `dench meetings transcript
3
+ * set`. No network, no Convex — everything here is unit-testable and shared
4
+ * by the CLI and (through the OpenAPI description) documented for API
5
+ * callers who parse client-side.
6
+ *
7
+ * A source row is "meeting fields plus three optional attachments". The
8
+ * attachments live in side tables on the server and travel under reserved
9
+ * keys so a CSV can carry them as ordinary columns:
10
+ *
11
+ * transcript string | string[] | segment[] → meetingTranscriptSegments
12
+ * actionItems string | string[] | item[] → meetingActionItems
13
+ * attendees string | string[] | person[] → meetingParticipants
14
+ *
15
+ * `attendees`, not `participants`: `Participants` is already the meeting's
16
+ * relation to `people` rows (entry ids), and a column of names and emails
17
+ * must not be mistaken for one.
18
+ */
19
+
20
+ export type ImportedSegment = {
21
+ seq?: number;
22
+ speakerName?: string | null;
23
+ speakerEmail?: string | null;
24
+ startMs?: number;
25
+ endMs?: number;
26
+ text: string;
27
+ };
28
+
29
+ export type ImportedActionItem = {
30
+ text: string;
31
+ ownerName?: string | null;
32
+ done?: boolean;
33
+ };
34
+
35
+ export type ImportedAttendee = {
36
+ name?: string | null;
37
+ email?: string | null;
38
+ isHost?: boolean;
39
+ };
40
+
41
+ export type MeetingImportRow = {
42
+ fields: Record<string, unknown>;
43
+ transcript: ImportedSegment[] | null;
44
+ actionItems: ImportedActionItem[] | null;
45
+ attendees: ImportedAttendee[] | null;
46
+ };
47
+
48
+ /** Reserved row keys, matched case- and separator-insensitively. */
49
+ const RESERVED = {
50
+ transcript: new Set(["transcript", "transcriptsegments", "segments"]),
51
+ actionItems: new Set(["actionitems", "actions", "todos", "tasks"]),
52
+ attendees: new Set(["attendees", "speakers", "people"]),
53
+ } as const;
54
+
55
+ function normalizeKey(key: string): string {
56
+ return key.toLowerCase().replace(/[\s_-]+/g, "");
57
+ }
58
+
59
+ function isRecord(value: unknown): value is Record<string, unknown> {
60
+ return typeof value === "object" && value !== null && !Array.isArray(value);
61
+ }
62
+
63
+ function asString(value: unknown): string | null {
64
+ if (typeof value === "string") return value.trim() || null;
65
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
66
+ return null;
67
+ }
68
+
69
+ /**
70
+ * `[01:02:03]`, `01:02:03`, `1:02`, `(12:34)`, `62.5` (seconds), `62500ms`.
71
+ * Returns milliseconds, or null when the token is not a timestamp.
72
+ */
73
+ export function parseOffsetMs(raw: unknown): number | null {
74
+ if (typeof raw === "number") {
75
+ return Number.isFinite(raw) && raw >= 0 ? Math.round(raw) : null;
76
+ }
77
+ if (typeof raw !== "string") return null;
78
+ const token = raw.trim().replace(/^[[(]|[\])]$/g, "");
79
+ if (!token) return null;
80
+ const ms = token.match(/^(\d+)\s*ms$/i);
81
+ if (ms) return Number(ms[1]);
82
+ const clock = token.match(
83
+ /^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/,
84
+ );
85
+ if (clock) {
86
+ const [, h, m, s, frac] = clock;
87
+ const millis = frac ? Number(frac.padEnd(3, "0")) : 0;
88
+ return ((Number(h ?? 0) * 60 + Number(m)) * 60 + Number(s)) * 1000 + millis;
89
+ }
90
+ const seconds = token.match(/^(\d+(?:\.\d+)?)\s*s?$/);
91
+ if (seconds) return Math.round(Number(seconds[1]) * 1000);
92
+ return null;
93
+ }
94
+
95
+ /**
96
+ * A leading timestamp in any of the usual shapes, followed by an optional
97
+ * `Speaker:` label. The label is capped at 60 characters and may not contain
98
+ * sentence punctuation, so a colon later in a sentence ("We agreed. Next
99
+ * step: ship it.") never splits a turn; only the first `Word(s):` of a line
100
+ * can be a speaker.
101
+ */
102
+ const LINE_RE =
103
+ /^\s*(?:[[(]?((?:\d{1,2}:)?\d{1,2}:\d{2}(?:[.,]\d{1,3})?)[\])]?\s*[-–—]?\s*)?(?:([^:.!?\n]{1,60}?)\s*(?:[[(]((?:\d{1,2}:)?\d{1,2}:\d{2}(?:[.,]\d{1,3})?)[\])])?\s*:\s+)?(.*)$/;
104
+
105
+ /**
106
+ * Plain-text transcript → segments. One non-empty line is one segment; a
107
+ * line without a speaker label inherits the previous speaker. Timestamps
108
+ * are honoured when present, and a segment's `endMs` is the next timed
109
+ * segment's start. When nothing in the file is timed every offset is 0 —
110
+ * the UI hides the clock rather than inventing one.
111
+ */
112
+ export function parseTranscriptText(text: string): ImportedSegment[] {
113
+ const segments: ImportedSegment[] = [];
114
+ let speaker: string | null = null;
115
+ for (const rawLine of text.split(/\r?\n/)) {
116
+ const line = rawLine.trim();
117
+ if (!line) continue;
118
+ const match = line.match(LINE_RE);
119
+ if (!match) {
120
+ segments.push({ speakerName: speaker, text: line });
121
+ continue;
122
+ }
123
+ const [, leadingTs, label, labelTs, rest] = match;
124
+ const body = (rest ?? "").trim();
125
+ if (!body && !label) continue;
126
+ if (label) speaker = label.trim();
127
+ const startMs = parseOffsetMs(leadingTs ?? labelTs ?? null);
128
+ segments.push({
129
+ speakerName: speaker,
130
+ text: body || (label ?? ""),
131
+ ...(startMs !== null ? { startMs } : {}),
132
+ });
133
+ }
134
+ return fillSegmentTiming(segments);
135
+ }
136
+
137
+ /** Assign `seq` and close each timed segment at the next timed start. */
138
+ export function fillSegmentTiming(
139
+ segments: ImportedSegment[],
140
+ ): ImportedSegment[] {
141
+ const timed = segments.some((segment) => (segment.startMs ?? 0) > 0);
142
+ let previousEnd = 0;
143
+ return segments.map((segment, index) => {
144
+ const startMs = timed
145
+ ? Math.max(segment.startMs ?? previousEnd, previousEnd)
146
+ : 0;
147
+ let endMs = segment.endMs ?? undefined;
148
+ if (endMs === undefined && timed) {
149
+ const next = segments
150
+ .slice(index + 1)
151
+ .find((candidate) => candidate.startMs !== undefined);
152
+ endMs =
153
+ next?.startMs !== undefined ? Math.max(next.startMs, startMs) : startMs;
154
+ }
155
+ previousEnd = endMs ?? startMs;
156
+ return {
157
+ seq: segment.seq ?? index,
158
+ speakerName: segment.speakerName ?? null,
159
+ speakerEmail: segment.speakerEmail ?? null,
160
+ startMs,
161
+ endMs: endMs ?? startMs,
162
+ text: segment.text,
163
+ };
164
+ });
165
+ }
166
+
167
+ /** Structured segment objects (JSON/JSONL) in any of the common key spellings. */
168
+ export function normalizeSegment(value: unknown): ImportedSegment | null {
169
+ if (typeof value === "string") {
170
+ const [segment] = parseTranscriptText(value);
171
+ return segment ?? null;
172
+ }
173
+ if (!isRecord(value)) return null;
174
+ const text =
175
+ asString(value.text) ?? asString(value.content) ?? asString(value.line);
176
+ if (!text) return null;
177
+ const speakerName =
178
+ asString(value.speakerName) ??
179
+ asString(value.speaker) ??
180
+ asString(value.name);
181
+ const speakerEmail =
182
+ asString(value.speakerEmail) ?? asString(value.email) ?? null;
183
+ // `startMs`/`endMs` are milliseconds. The un-suffixed keys most exports
184
+ // use (`start`, `end`, `timestamp`, `offset`) are SECONDS when numeric —
185
+ // Fireflies, Otter and Granola all count seconds — and clock strings
186
+ // otherwise.
187
+ const secondsOrClock = (raw: unknown): number | null =>
188
+ typeof raw === "number"
189
+ ? Number.isFinite(raw) && raw >= 0
190
+ ? Math.round(raw * 1000)
191
+ : null
192
+ : parseOffsetMs(raw);
193
+ const startMs =
194
+ parseOffsetMs(value.startMs) ??
195
+ secondsOrClock(value.start) ??
196
+ secondsOrClock(value.timestamp) ??
197
+ secondsOrClock(value.offset);
198
+ const endMs = parseOffsetMs(value.endMs) ?? secondsOrClock(value.end);
199
+ const seq = typeof value.seq === "number" ? value.seq : undefined;
200
+ return {
201
+ ...(seq !== undefined ? { seq } : {}),
202
+ speakerName,
203
+ speakerEmail,
204
+ ...(startMs !== null ? { startMs } : {}),
205
+ ...(endMs !== null ? { endMs } : {}),
206
+ text,
207
+ };
208
+ }
209
+
210
+ export function normalizeTranscript(value: unknown): ImportedSegment[] | null {
211
+ if (value === null || value === undefined || value === "") return null;
212
+ if (typeof value === "string") {
213
+ const trimmed = value.trim();
214
+ if (trimmed.startsWith("[")) {
215
+ try {
216
+ return normalizeTranscript(JSON.parse(trimmed));
217
+ } catch {
218
+ // Not JSON after all — treat as text.
219
+ }
220
+ }
221
+ return parseTranscriptText(value);
222
+ }
223
+ if (Array.isArray(value)) {
224
+ const segments = value
225
+ .map(normalizeSegment)
226
+ .filter((segment): segment is ImportedSegment => segment !== null);
227
+ return fillSegmentTiming(segments);
228
+ }
229
+ return null;
230
+ }
231
+
232
+ /**
233
+ * `- [x] Send the deck (Hank)` / `Send the deck — Hank` / `{text, owner,
234
+ * done}`. Markdown checkboxes carry completion; a trailing parenthesised
235
+ * or dashed name is the owner.
236
+ */
237
+ export function normalizeActionItem(value: unknown): ImportedActionItem | null {
238
+ if (typeof value === "string") {
239
+ let text = value.trim().replace(/^[-*•]\s+/, "");
240
+ if (!text) return null;
241
+ let done: boolean | undefined;
242
+ const box = text.match(/^\[([ xX])\]\s*(.*)$/);
243
+ if (box) {
244
+ done = box[1] !== " ";
245
+ text = box[2].trim();
246
+ }
247
+ let ownerName: string | null = null;
248
+ const paren = text.match(/^(.*?)\s*\(([^()]{1,60})\)\s*$/);
249
+ const dash = text.match(/^(.*?)\s+[-–—]\s+([^-–—]{1,60})$/);
250
+ if (paren) {
251
+ text = paren[1].trim();
252
+ ownerName = paren[2].trim();
253
+ } else if (dash) {
254
+ text = dash[1].trim();
255
+ ownerName = dash[2].trim();
256
+ }
257
+ if (!text) return null;
258
+ return { text, ownerName, ...(done !== undefined ? { done } : {}) };
259
+ }
260
+ if (!isRecord(value)) return null;
261
+ const text =
262
+ asString(value.text) ?? asString(value.title) ?? asString(value.name);
263
+ if (!text) return null;
264
+ const ownerName =
265
+ asString(value.ownerName) ??
266
+ asString(value.owner) ??
267
+ asString(value.assignee) ??
268
+ null;
269
+ const done =
270
+ typeof value.done === "boolean"
271
+ ? value.done
272
+ : typeof value.completed === "boolean"
273
+ ? value.completed
274
+ : undefined;
275
+ return { text, ownerName, ...(done !== undefined ? { done } : {}) };
276
+ }
277
+
278
+ export function normalizeActionItems(
279
+ value: unknown,
280
+ ): ImportedActionItem[] | null {
281
+ if (value === null || value === undefined || value === "") return null;
282
+ if (typeof value === "string") {
283
+ const trimmed = value.trim();
284
+ if (trimmed.startsWith("[")) {
285
+ try {
286
+ return normalizeActionItems(JSON.parse(trimmed));
287
+ } catch {
288
+ // fall through to line splitting
289
+ }
290
+ }
291
+ return normalizeActionItems(trimmed.split(/\r?\n/));
292
+ }
293
+ if (Array.isArray(value)) {
294
+ return value
295
+ .map(normalizeActionItem)
296
+ .filter((item): item is ImportedActionItem => item !== null);
297
+ }
298
+ return null;
299
+ }
300
+
301
+ /** `Hank Scorpio <hank@globex.test>` / `hank@globex.test` / `Hank Scorpio`. */
302
+ export function normalizeAttendee(value: unknown): ImportedAttendee | null {
303
+ if (typeof value === "string") {
304
+ const raw = value.trim();
305
+ if (!raw) return null;
306
+ const isHost = /\((?:host|organi[sz]er)\)\s*$/i.test(raw);
307
+ const cleaned = raw.replace(/\s*\((?:host|organi[sz]er)\)\s*$/i, "");
308
+ const angle = cleaned.match(/^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/);
309
+ if (angle) {
310
+ return {
311
+ name: angle[1].trim() || null,
312
+ email: angle[2].trim(),
313
+ ...(isHost ? { isHost } : {}),
314
+ };
315
+ }
316
+ if (/^[^\s@]+@[^\s@]+$/.test(cleaned)) {
317
+ return { name: null, email: cleaned, ...(isHost ? { isHost } : {}) };
318
+ }
319
+ return { name: cleaned, email: null, ...(isHost ? { isHost } : {}) };
320
+ }
321
+ if (!isRecord(value)) return null;
322
+ const name = asString(value.name) ?? asString(value.displayName) ?? null;
323
+ const email = asString(value.email) ?? null;
324
+ if (!name && !email) return null;
325
+ const isHost =
326
+ typeof value.isHost === "boolean"
327
+ ? value.isHost
328
+ : typeof value.host === "boolean"
329
+ ? value.host
330
+ : undefined;
331
+ return { name, email, ...(isHost !== undefined ? { isHost } : {}) };
332
+ }
333
+
334
+ export function normalizeAttendees(value: unknown): ImportedAttendee[] | null {
335
+ if (value === null || value === undefined || value === "") return null;
336
+ if (typeof value === "string") {
337
+ const trimmed = value.trim();
338
+ if (trimmed.startsWith("[")) {
339
+ try {
340
+ return normalizeAttendees(JSON.parse(trimmed));
341
+ } catch {
342
+ // fall through
343
+ }
344
+ }
345
+ // Commas inside `Name <email>` are unusual; semicolons and newlines
346
+ // are the safer separators, but all three are accepted.
347
+ return normalizeAttendees(trimmed.split(/\s*[;\n]\s*|,\s*(?![^<]*>)/));
348
+ }
349
+ if (Array.isArray(value)) {
350
+ return value
351
+ .map(normalizeAttendee)
352
+ .filter((row): row is ImportedAttendee => row !== null);
353
+ }
354
+ return null;
355
+ }
356
+
357
+ /**
358
+ * Split one source row into meeting fields and its attachments. Reserved
359
+ * keys are removed from `fields` so the CRM write never sees them; an empty
360
+ * reserved cell (blank CSV column) yields `null`, meaning "nothing to do".
361
+ */
362
+ export function splitMeetingImportRow(
363
+ row: Record<string, unknown>,
364
+ ): MeetingImportRow {
365
+ const fields: Record<string, unknown> = {};
366
+ let transcript: unknown;
367
+ let actionItems: unknown;
368
+ let attendees: unknown;
369
+ for (const [key, value] of Object.entries(row)) {
370
+ const normalized = normalizeKey(key);
371
+ if (RESERVED.transcript.has(normalized)) transcript = value;
372
+ else if (RESERVED.actionItems.has(normalized)) actionItems = value;
373
+ else if (RESERVED.attendees.has(normalized)) attendees = value;
374
+ else fields[key] = value;
375
+ }
376
+ return {
377
+ fields,
378
+ transcript: normalizeTranscript(transcript),
379
+ actionItems: normalizeActionItems(actionItems),
380
+ attendees: normalizeAttendees(attendees),
381
+ };
382
+ }
383
+
384
+ /**
385
+ * Fill in what the Meetings UI needs and the source usually omits.
386
+ *
387
+ * `Status` defaults to `Completed`: an imported call already happened. An
388
+ * `Ended At` is derived from `Started At` + `Recording Duration` when the
389
+ * source gave a length but no end. Nothing else is invented — a missing
390
+ * `Started At` is reported by the caller, not guessed.
391
+ */
392
+ export function applyMeetingFieldDefaults(
393
+ fields: Record<string, unknown>,
394
+ ): Record<string, unknown> {
395
+ const out = { ...fields };
396
+ if (asString(out.Status) === null) out.Status = "Completed";
397
+ const startedAt = parseDateMs(out["Started At"]);
398
+ const endedAt = parseDateMs(out["Ended At"]);
399
+ const duration = parseSeconds(out["Recording Duration"]);
400
+ if (startedAt !== null && endedAt === null && duration !== null) {
401
+ out["Ended At"] = startedAt + duration * 1000;
402
+ }
403
+ if (
404
+ startedAt !== null &&
405
+ endedAt !== null &&
406
+ duration === null &&
407
+ endedAt > startedAt
408
+ ) {
409
+ out["Recording Duration"] = Math.round((endedAt - startedAt) / 1000);
410
+ }
411
+ return out;
412
+ }
413
+
414
+ export function parseDateMs(value: unknown): number | null {
415
+ if (typeof value === "number" && Number.isFinite(value)) return value;
416
+ if (typeof value !== "string" || !value.trim()) return null;
417
+ const ts = Date.parse(value);
418
+ return Number.isFinite(ts) ? ts : null;
419
+ }
420
+
421
+ function parseSeconds(value: unknown): number | null {
422
+ if (typeof value === "number" && Number.isFinite(value)) return value;
423
+ if (typeof value !== "string" || !value.trim()) return null;
424
+ const n = Number(value);
425
+ return Number.isFinite(n) ? n : null;
426
+ }