@verevoir/aigency-work 0.0.0-stage → 0.2.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.
@@ -0,0 +1,733 @@
1
+ // A `CardSource`/`CardSink` over one Notion database, talking to the REST
2
+ // API with raw `fetch` — no SDK, no new dependency. `fetch`, `sleep` and
3
+ // `getToken` are all injected (see `NotionBoardConfig`): tests supply fixed
4
+ // responses and an instant clock, and credentials are a name this board is
5
+ // handed, never an environment variable it reads for itself or a value it
6
+ // ever writes to a log.
7
+ //
8
+ // Notion has no compare-and-set primitive, and a last_edited_time check
9
+ // before a write is not atomic — it can never close the race it would
10
+ // claim to guard. So `expectedRevision` is never honoured here: any write
11
+ // that supplies one gets `unsupported`, naming it, rather than a guard
12
+ // that looks real and isn't (the same discipline `payload-board.ts`
13
+ // applies for the same reason).
14
+ /** The API version this board was built and tested against. */
15
+ export const NOTION_VERSION = '2022-06-28';
16
+ const DEFAULT_MAX_ATTEMPTS = 4;
17
+ const DEFAULT_BASE_DELAY_MS = 250;
18
+ /**
19
+ * An upper bound on any single retry delay, including one taken from a
20
+ * server-supplied `Retry-After`. Without this, Notion (or anything
21
+ * fronting it) could impose an arbitrarily long sleep that the named,
22
+ * configurable retry budget (`maxAttempts`/`baseDelayMs`) was never meant
23
+ * to cover.
24
+ */
25
+ const MAX_RETRY_DELAY_MS = 30_000;
26
+ /** The reason given for any write that supplies `expectedRevision`. */
27
+ export const EXPECTED_REVISION_UNSUPPORTED_REASON = 'expectedRevision is not supported by NotionBoard: Notion has no compare-and-set primitive, and checking last_edited_time first would not be atomic';
28
+ // `request` below reaches `fetch` through a local variable at its call
29
+ // site (`const doFetch = resolved.fetch; await doFetch(url, init)`), never
30
+ // as `resolved.fetch(url, init)` — calling the latter as a method binds
31
+ // `this` to `resolved`, and some native `fetch` implementations throw
32
+ // "Illegal invocation" unless `this` is the global object. The local
33
+ // variable avoids that for ANY caller-supplied fetch, not only this
34
+ // module's own default below, which also explicitly targets `globalThis`
35
+ // so it is safe regardless of how it is called.
36
+ const defaultFetch = (url, init) => globalThis.fetch(url, init);
37
+ const defaultSleep = (ms) => new Promise((resolve) => {
38
+ globalThis.setTimeout(resolve, ms);
39
+ });
40
+ function resolveConfig(config) {
41
+ return {
42
+ databaseId: config.databaseId,
43
+ getToken: config.getToken,
44
+ statusProperty: config.statusProperty ?? 'Status',
45
+ titleProperty: config.titleProperty ?? 'Name',
46
+ fetch: config.fetch ?? defaultFetch,
47
+ sleep: config.sleep ?? defaultSleep,
48
+ // Clamped to at least 1: a configured 0 (or negative) used to fall
49
+ // straight through the retry loop having made no call at all, and
50
+ // still report `contentionExhausted`, claiming Notion "kept
51
+ // responding" when nobody was ever asked — mislabelling a
52
+ // configuration mistake as contention.
53
+ maxAttempts: Math.max(1, config.maxAttempts ?? DEFAULT_MAX_ATTEMPTS),
54
+ baseDelayMs: config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS,
55
+ };
56
+ }
57
+ function isRecord(value) {
58
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
59
+ }
60
+ /**
61
+ * Validates that a parsed 2xx body actually looks like a Notion page,
62
+ * rather than trusting a blind cast. Without this, a parseable-but-wrong
63
+ * body (`null`, `{}`, a JSON parse failure already reduced to
64
+ * `undefined` by `request`) reached `pageToCard`/`resolveRelation` and
65
+ * threw an unrelated `TypeError` instead of reporting a named outcome.
66
+ */
67
+ function asNotionPage(body) {
68
+ if (!isRecord(body) || typeof body.id !== 'string' || typeof body.url !== 'string') {
69
+ return undefined;
70
+ }
71
+ if (!isRecord(body.properties)) {
72
+ return undefined;
73
+ }
74
+ return body;
75
+ }
76
+ function asNotionQueryResponse(body) {
77
+ if (!isRecord(body) || !Array.isArray(body.results) || typeof body.has_more !== 'boolean') {
78
+ return undefined;
79
+ }
80
+ return body;
81
+ }
82
+ function asNotionSchema(body) {
83
+ if (!isRecord(body) || !isRecord(body.properties)) {
84
+ return undefined;
85
+ }
86
+ return body;
87
+ }
88
+ /** The message used wherever a 2xx body turns out unusable for what it was read for. */
89
+ function unreadableBodyMessage(kind) {
90
+ return `Notion's response either did not parse as JSON or was not shaped like a ${kind}`;
91
+ }
92
+ async function tryParseJson(response) {
93
+ try {
94
+ return await response.json();
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ }
100
+ function messageFrom(detail, fallback) {
101
+ if (detail !== null &&
102
+ typeof detail === 'object' &&
103
+ 'message' in detail &&
104
+ typeof detail.message === 'string') {
105
+ return detail.message;
106
+ }
107
+ return fallback;
108
+ }
109
+ /**
110
+ * The single point every call to Notion passes through: auth header,
111
+ * HTTP-to-outcome mapping, and the bounded 409/429 retry with backoff,
112
+ * honouring `Retry-After` when Notion sends one (capped at
113
+ * `MAX_RETRY_DELAY_MS`, and ignored in favour of the exponential backoff
114
+ * when it is not a usable, non-negative number of seconds). The token is
115
+ * read once per call from `getToken` and placed only in the
116
+ * `Authorization` header — never returned, never included in any `reason`
117
+ * string below. A `getToken` that throws or rejects becomes `unreachable`
118
+ * naming the failure, never an unhandled rejection out of this board.
119
+ */
120
+ async function request(resolved, method, path, body) {
121
+ let token;
122
+ try {
123
+ token = await resolved.getToken();
124
+ }
125
+ catch (error) {
126
+ return {
127
+ kind: 'unreachable',
128
+ reason: `getToken failed: ${error instanceof Error ? error.message : String(error)}`,
129
+ };
130
+ }
131
+ const url = `https://api.notion.com/v1${path}`;
132
+ const headers = {
133
+ Authorization: `Bearer ${token}`,
134
+ 'Notion-Version': NOTION_VERSION,
135
+ 'Content-Type': 'application/json',
136
+ };
137
+ const doFetch = resolved.fetch;
138
+ for (let attempt = 1; attempt <= resolved.maxAttempts; attempt++) {
139
+ let response;
140
+ try {
141
+ response = await doFetch(url, {
142
+ method,
143
+ headers,
144
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
145
+ });
146
+ }
147
+ catch (error) {
148
+ return {
149
+ kind: 'unreachable',
150
+ reason: `network error reaching Notion: ${error instanceof Error ? error.message : String(error)}`,
151
+ };
152
+ }
153
+ if (response.status === 401 || response.status === 403) {
154
+ return {
155
+ kind: 'unreachable',
156
+ reason: `Notion rejected the credentials (status ${response.status})`,
157
+ };
158
+ }
159
+ if (response.status === 404) {
160
+ return { kind: 'notFound' };
161
+ }
162
+ if (response.status === 400) {
163
+ const detail = await tryParseJson(response);
164
+ return {
165
+ kind: 'badRequest',
166
+ reason: messageFrom(detail, 'Notion rejected the request (status 400)'),
167
+ };
168
+ }
169
+ if (response.status === 409 || response.status === 429) {
170
+ if (attempt >= resolved.maxAttempts) {
171
+ return {
172
+ kind: 'contentionExhausted',
173
+ reason: `Notion kept responding ${response.status} after ${attempt} attempt(s)`,
174
+ };
175
+ }
176
+ const retryAfterHeader = response.headers.get('Retry-After');
177
+ const retryAfterSeconds = retryAfterHeader !== null && retryAfterHeader !== '' ? Number(retryAfterHeader) : NaN;
178
+ const rawDelayMs = Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0
179
+ ? retryAfterSeconds * 1000
180
+ : resolved.baseDelayMs * 2 ** (attempt - 1);
181
+ await resolved.sleep(Math.min(rawDelayMs, MAX_RETRY_DELAY_MS));
182
+ continue;
183
+ }
184
+ if (!response.ok) {
185
+ return {
186
+ kind: 'unreachable',
187
+ reason: `Notion returned an unexpected status ${response.status}`,
188
+ };
189
+ }
190
+ return { kind: 'ok', body: await tryParseJson(response) };
191
+ }
192
+ return {
193
+ kind: 'contentionExhausted',
194
+ reason: 'Notion kept responding with contention after retries',
195
+ };
196
+ }
197
+ /**
198
+ * Maps a failed `request` outcome onto `GetResult`. `notFound` is
199
+ * `absent`; everything else (`badRequest`, `contentionExhausted` — 429
200
+ * rate-limiting applies to a plain GET as much as to a write, so this IS
201
+ * reachable from here — and `unreachable`) falls back to `unreachable`.
202
+ */
203
+ function toGetFailure(outcome) {
204
+ if (outcome.kind === 'notFound') {
205
+ return { outcome: 'absent' };
206
+ }
207
+ return { outcome: 'unreachable', reason: outcome.reason };
208
+ }
209
+ function toListFailure(outcome) {
210
+ if (outcome.kind === 'notFound') {
211
+ return { outcome: 'unreachable', reason: 'Notion reported no such database' };
212
+ }
213
+ return { outcome: 'unreachable', reason: outcome.reason };
214
+ }
215
+ function toWriteFailure(outcome, notFoundReason) {
216
+ switch (outcome.kind) {
217
+ case 'notFound':
218
+ return { outcome: 'refused', reason: notFoundReason };
219
+ case 'badRequest':
220
+ return { outcome: 'refused', reason: outcome.reason };
221
+ case 'contentionExhausted':
222
+ return { outcome: 'contentionExhausted', reason: outcome.reason };
223
+ case 'unreachable':
224
+ return { outcome: 'unreachable', reason: outcome.reason };
225
+ }
226
+ }
227
+ function toWriteResult(outcome, notFoundReason) {
228
+ if (outcome.kind === 'ok') {
229
+ return { outcome: 'applied' };
230
+ }
231
+ return toWriteFailure(outcome, notFoundReason);
232
+ }
233
+ function plainTextOf(fragments) {
234
+ return (fragments ?? []).map((fragment) => fragment.plain_text ?? '').join('');
235
+ }
236
+ function formatDate(date) {
237
+ if (date.end !== undefined && date.end !== null) {
238
+ return `${date.start}/${date.end}`;
239
+ }
240
+ return date.start;
241
+ }
242
+ function statusPropertyRefusalReason(statusProperty, statusDef) {
243
+ if (statusDef === undefined) {
244
+ return `property "${statusProperty}" does not exist on this database, so its state cannot be written`;
245
+ }
246
+ return `property "${statusProperty}" has type "${statusDef.type}", not select or status, so its state cannot be written`;
247
+ }
248
+ /**
249
+ * Resolves one relation property's value. "Requires" is a reference to
250
+ * other tickets: its value is the related pages' own `Ticket` property,
251
+ * never their ids — an id means nothing to a human reading the board, and
252
+ * falling back to one when the real value could not be read would make a
253
+ * deleted dependency, an outage, and a missing ticket all look like
254
+ * genuine data. Every other relation reports the related pages' ids
255
+ * directly — the only thing a generic relation can mean without knowing
256
+ * what it points at, and not a failure of anything, so no fetch is made
257
+ * for it at all. Stops at the first unresolved "Requires" target rather
258
+ * than fetching the rest, naming only that one.
259
+ */
260
+ async function resolveRelation(propertyName, refs, resolved) {
261
+ if (propertyName !== 'Requires') {
262
+ return { ok: true, value: refs.map((ref) => ref.id).join(', ') };
263
+ }
264
+ const values = [];
265
+ for (const ref of refs) {
266
+ const outcome = await request(resolved, 'GET', `/pages/${encodeURIComponent(ref.id)}`);
267
+ if (outcome.kind === 'unreachable') {
268
+ return {
269
+ ok: false,
270
+ kind: 'unreachable',
271
+ reason: `"${propertyName}" could not be resolved: related page ${ref.id} is unreachable: ${outcome.reason}`,
272
+ };
273
+ }
274
+ if (outcome.kind === 'notFound') {
275
+ return {
276
+ ok: false,
277
+ kind: 'problem',
278
+ reason: `"${propertyName}" references page ${ref.id}, which no longer exists`,
279
+ };
280
+ }
281
+ if (outcome.kind !== 'ok') {
282
+ return {
283
+ ok: false,
284
+ kind: 'problem',
285
+ reason: `"${propertyName}" references page ${ref.id}, which could not be read (${outcome.kind}): ${outcome.reason}`,
286
+ };
287
+ }
288
+ const related = asNotionPage(outcome.body);
289
+ if (related === undefined) {
290
+ return {
291
+ ok: false,
292
+ kind: 'problem',
293
+ reason: `"${propertyName}" references page ${ref.id}: ${unreadableBodyMessage('page')}`,
294
+ };
295
+ }
296
+ const ticket = related.properties.Ticket;
297
+ if (ticket === undefined) {
298
+ return {
299
+ ok: false,
300
+ kind: 'problem',
301
+ reason: `"${propertyName}" references page ${ref.id}, which has no "Ticket" property`,
302
+ };
303
+ }
304
+ if (ticket.type !== 'rich_text') {
305
+ return {
306
+ ok: false,
307
+ kind: 'problem',
308
+ reason: `"${propertyName}" references page ${ref.id}, whose "Ticket" property has type "${ticket.type}", not rich_text`,
309
+ };
310
+ }
311
+ const text = plainTextOf(ticket.rich_text);
312
+ if (text === '') {
313
+ return {
314
+ ok: false,
315
+ kind: 'problem',
316
+ reason: `"${propertyName}" references page ${ref.id}, whose "Ticket" property is empty`,
317
+ };
318
+ }
319
+ values.push(text);
320
+ }
321
+ return { ok: true, value: values.join(', ') };
322
+ }
323
+ /**
324
+ * Flattens one Notion property into `properties` (a plain string) or,
325
+ * when its type cannot reduce to a string without lying about what it
326
+ * holds, into `unknownFields` — the same discipline `payload-board.ts`
327
+ * applies to a tracker-shaped value it cannot safely treat as this
328
+ * boundary's own flat `properties` bag. A relation that cannot be
329
+ * resolved is neither: see `resolveRelation`.
330
+ */
331
+ async function flattenProperty(name, prop, resolved, properties, unknownFields) {
332
+ switch (prop.type) {
333
+ case 'title': {
334
+ const text = plainTextOf(prop.title);
335
+ if (text !== '') {
336
+ properties[name] = text;
337
+ }
338
+ return { ok: true };
339
+ }
340
+ case 'rich_text': {
341
+ const text = plainTextOf(prop.rich_text);
342
+ if (text !== '') {
343
+ properties[name] = text;
344
+ }
345
+ return { ok: true };
346
+ }
347
+ case 'select': {
348
+ if (prop.select) {
349
+ properties[name] = prop.select.name;
350
+ }
351
+ return { ok: true };
352
+ }
353
+ case 'multi_select': {
354
+ // Omit the key entirely when there is nothing selected, matching
355
+ // every other type here (an absent value is never represented as
356
+ // `''`) — a reader of `properties` should not have to know that
357
+ // multi_select is the one type where "empty" and "absent" differ.
358
+ const names = (prop.multi_select ?? []).map((option) => option.name);
359
+ if (names.length > 0) {
360
+ properties[name] = names.join(', ');
361
+ }
362
+ return { ok: true };
363
+ }
364
+ case 'number': {
365
+ if (prop.number !== null && prop.number !== undefined) {
366
+ properties[name] = String(prop.number);
367
+ }
368
+ return { ok: true };
369
+ }
370
+ case 'date': {
371
+ if (prop.date) {
372
+ properties[name] = formatDate(prop.date);
373
+ }
374
+ return { ok: true };
375
+ }
376
+ case 'url': {
377
+ if (prop.url !== null && prop.url !== undefined) {
378
+ properties[name] = prop.url;
379
+ }
380
+ return { ok: true };
381
+ }
382
+ case 'relation': {
383
+ const refs = prop.relation ?? [];
384
+ if (refs.length === 0) {
385
+ return { ok: true };
386
+ }
387
+ const outcome = await resolveRelation(name, refs, resolved);
388
+ if (!outcome.ok) {
389
+ if (outcome.kind === 'unreachable') {
390
+ return { ok: false, kind: 'unreachable', reason: outcome.reason };
391
+ }
392
+ return { ok: false, kind: 'problem', field: name, reason: outcome.reason };
393
+ }
394
+ properties[name] = outcome.value;
395
+ return { ok: true };
396
+ }
397
+ default:
398
+ unknownFields[name] = prop;
399
+ return { ok: true };
400
+ }
401
+ }
402
+ /**
403
+ * Reads the configured status property off a page. A property that is
404
+ * missing, or present with a type that is neither `select` nor `status`,
405
+ * is a MISCONFIGURATION — a different fact from a card that genuinely has
406
+ * no state set — and is reported as such (`ok: false`, naming the
407
+ * property and, when it exists, the type it actually has), never folded
408
+ * into the same `''` a card's genuinely-empty status also produces. A
409
+ * `select`/`status` property with no option chosen is a real, ordinary
410
+ * `''`.
411
+ */
412
+ function extractState(page, resolved) {
413
+ const prop = page.properties[resolved.statusProperty];
414
+ if (prop === undefined) {
415
+ return {
416
+ ok: false,
417
+ reason: `property "${resolved.statusProperty}" does not exist on this page, so its state cannot be read`,
418
+ };
419
+ }
420
+ if (prop.type === 'select') {
421
+ return { ok: true, state: prop.select?.name ?? '' };
422
+ }
423
+ if (prop.type === 'status') {
424
+ return { ok: true, state: prop.status?.name ?? '' };
425
+ }
426
+ return {
427
+ ok: false,
428
+ reason: `property "${resolved.statusProperty}" has type "${prop.type}", not select or status, so its state cannot be read`,
429
+ };
430
+ }
431
+ async function pageToCard(page, resolved) {
432
+ const problems = [];
433
+ let state = '';
434
+ const stateOutcome = extractState(page, resolved);
435
+ if (stateOutcome.ok) {
436
+ state = stateOutcome.state;
437
+ }
438
+ else {
439
+ problems.push({ field: resolved.statusProperty, message: stateOutcome.reason });
440
+ }
441
+ const properties = {};
442
+ const unknownFields = {};
443
+ for (const [name, prop] of Object.entries(page.properties)) {
444
+ if (name === resolved.statusProperty) {
445
+ continue;
446
+ }
447
+ const outcome = await flattenProperty(name, prop, resolved, properties, unknownFields);
448
+ if (!outcome.ok) {
449
+ if (outcome.kind === 'unreachable') {
450
+ // A relation target could not be reached at all — nobody knows
451
+ // what it contains, so the whole card is unreachable, never a
452
+ // partial `found` built around a gap.
453
+ return { ok: false, kind: 'unreachable', reason: outcome.reason };
454
+ }
455
+ problems.push({ field: outcome.field, message: outcome.reason });
456
+ }
457
+ }
458
+ if (problems.length > 0) {
459
+ return { ok: false, kind: 'unparseable', problems };
460
+ }
461
+ return {
462
+ ok: true,
463
+ card: {
464
+ id: page.id,
465
+ state,
466
+ reference: page.url,
467
+ source: `notion:${resolved.databaseId}`,
468
+ unknownFields,
469
+ properties,
470
+ },
471
+ };
472
+ }
473
+ async function performGet(id, resolved) {
474
+ const outcome = await request(resolved, 'GET', `/pages/${encodeURIComponent(id)}`);
475
+ if (outcome.kind !== 'ok') {
476
+ return toGetFailure(outcome);
477
+ }
478
+ const page = asNotionPage(outcome.body);
479
+ if (page === undefined) {
480
+ return {
481
+ outcome: 'unparseable',
482
+ id,
483
+ problems: [{ field: 'body', message: unreadableBodyMessage('page') }],
484
+ };
485
+ }
486
+ const mapped = await pageToCard(page, resolved);
487
+ if (!mapped.ok) {
488
+ if (mapped.kind === 'unreachable') {
489
+ return { outcome: 'unreachable', reason: mapped.reason };
490
+ }
491
+ return { outcome: 'unparseable', id, problems: mapped.problems };
492
+ }
493
+ return { outcome: 'found', card: mapped.card };
494
+ }
495
+ async function performList(filter, resolved) {
496
+ const cards = [];
497
+ const unparseable = [];
498
+ let cursor;
499
+ for (;;) {
500
+ const body = {};
501
+ if (filter !== undefined) {
502
+ body.filter = filter;
503
+ }
504
+ if (cursor !== undefined) {
505
+ body.start_cursor = cursor;
506
+ }
507
+ const outcome = await request(resolved, 'POST', `/databases/${encodeURIComponent(resolved.databaseId)}/query`, body);
508
+ if (outcome.kind !== 'ok') {
509
+ return toListFailure(outcome);
510
+ }
511
+ const queryResponse = asNotionQueryResponse(outcome.body);
512
+ if (queryResponse === undefined) {
513
+ return { outcome: 'unreachable', reason: unreadableBodyMessage('query result') };
514
+ }
515
+ for (const raw of queryResponse.results) {
516
+ const page = asNotionPage(raw);
517
+ if (page === undefined) {
518
+ const rawId = isRecord(raw) && typeof raw.id === 'string' ? raw.id : '(id unreadable)';
519
+ unparseable.push({
520
+ id: rawId,
521
+ problems: [{ field: 'body', message: unreadableBodyMessage('page') }],
522
+ });
523
+ continue;
524
+ }
525
+ const mapped = await pageToCard(page, resolved);
526
+ if (!mapped.ok) {
527
+ if (mapped.kind === 'unreachable') {
528
+ // A relation target in this page could not be reached at all —
529
+ // the same fact that makes a single `get` unreachable rather
530
+ // than found. A list cannot safely report "everything else is
531
+ // fine" around a gap it cannot characterise, so the whole
532
+ // listing reports it, never a partial `cards` result.
533
+ return { outcome: 'unreachable', reason: mapped.reason };
534
+ }
535
+ unparseable.push({ id: page.id, problems: mapped.problems });
536
+ continue;
537
+ }
538
+ cards.push(mapped.card);
539
+ }
540
+ if (queryResponse.has_more && queryResponse.next_cursor !== null) {
541
+ cursor = queryResponse.next_cursor;
542
+ }
543
+ else {
544
+ break;
545
+ }
546
+ }
547
+ if (cards.length === 0 && unparseable.length === 0) {
548
+ return { outcome: 'empty' };
549
+ }
550
+ return { outcome: 'cards', cards, unparseable, danglingIds: [] };
551
+ }
552
+ async function performWriteState(id, state, resolved, options) {
553
+ if (options?.expectedRevision !== undefined) {
554
+ return { outcome: 'unsupported', id, reason: EXPECTED_REVISION_UNSUPPORTED_REASON };
555
+ }
556
+ const schemaOutcome = await request(resolved, 'GET', `/databases/${encodeURIComponent(resolved.databaseId)}`);
557
+ if (schemaOutcome.kind !== 'ok') {
558
+ return toWriteFailure(schemaOutcome, `database ${resolved.databaseId} not found`);
559
+ }
560
+ const schema = asNotionSchema(schemaOutcome.body);
561
+ if (schema === undefined) {
562
+ return { outcome: 'unreachable', reason: unreadableBodyMessage('database schema') };
563
+ }
564
+ const statusDef = schema.properties[resolved.statusProperty];
565
+ if (statusDef === undefined || (statusDef.type !== 'select' && statusDef.type !== 'status')) {
566
+ return {
567
+ outcome: 'refused',
568
+ reason: statusPropertyRefusalReason(resolved.statusProperty, statusDef),
569
+ };
570
+ }
571
+ const patchOutcome = await request(resolved, 'PATCH', `/pages/${encodeURIComponent(id)}`, {
572
+ properties: { [resolved.statusProperty]: { [statusDef.type]: { name: state } } },
573
+ });
574
+ return toWriteResult(patchOutcome, `no card with id ${id}`);
575
+ }
576
+ /**
577
+ * The per-type write mapping `annotate` and `createCard` both apply to a
578
+ * flat string value: only `rich_text` and `url` can be written back
579
+ * safely without more information than a flat string carries (a `select`
580
+ * needs to know whether the option already exists, `multi_select` needs
581
+ * a list, `number`/`date` need a parse that can fail in ways a plain
582
+ * string write cannot surface). Anything else is `ok: false` — the caller
583
+ * decides what that means (refuse the annotate, or refuse the whole
584
+ * create) rather than this function silently doing nothing.
585
+ */
586
+ function propertyWritePayload(type, value) {
587
+ if (type === 'rich_text') {
588
+ return { ok: true, payload: { rich_text: value === '' ? [] : [{ text: { content: value } }] } };
589
+ }
590
+ if (type === 'url') {
591
+ return { ok: true, payload: { url: value === '' ? null : value } };
592
+ }
593
+ return { ok: false };
594
+ }
595
+ /**
596
+ * Creates a page in the configured database. Notion has nothing resembling
597
+ * a unique constraint on a title, so a duplicate create is never
598
+ * detectable from here — calling this twice with the same `card.id` (which
599
+ * is meaningless to Notion; it assigns its own page id) always creates two
600
+ * pages. Callers that need "create if absent" must check with `get` first
601
+ * and accept the race that implies.
602
+ *
603
+ * Every mappable property is written, using exactly the mapping
604
+ * `annotate` uses (see `propertyWritePayload`) — never only the title.
605
+ * `card.state` is always written to the configured status property, and
606
+ * `card.properties[titleProperty]` is always written to the configured
607
+ * title property — neither is read a second time out of `card.properties`
608
+ * as an ordinary mappable entry. The whole create is REFUSED, naming
609
+ * every offending field, before any page is created, when: the title
610
+ * property is missing from the schema or is not a `title`; the status
611
+ * property is missing or is not `select`/`status`; `card.properties`
612
+ * carries an entry under the status property's own name (ambiguous with
613
+ * `card.state` — set the state through `card.state`, not here); or any
614
+ * other entry has no matching schema property, or a schema type
615
+ * `propertyWritePayload` does not support. `applied` means every field
616
+ * the caller supplied actually landed — never a partial write reported as
617
+ * if it were complete.
618
+ */
619
+ async function performCreateCard(card, resolved) {
620
+ const schemaOutcome = await request(resolved, 'GET', `/databases/${encodeURIComponent(resolved.databaseId)}`);
621
+ if (schemaOutcome.kind !== 'ok') {
622
+ return toWriteFailure(schemaOutcome, `database ${resolved.databaseId} not found`);
623
+ }
624
+ const schema = asNotionSchema(schemaOutcome.body);
625
+ if (schema === undefined) {
626
+ return { outcome: 'unreachable', reason: unreadableBodyMessage('database schema') };
627
+ }
628
+ const problems = [];
629
+ const titleDef = schema.properties[resolved.titleProperty];
630
+ if (titleDef === undefined || titleDef.type !== 'title') {
631
+ problems.push(`${resolved.titleProperty} (not a title property on this database)`);
632
+ }
633
+ const statusDef = schema.properties[resolved.statusProperty];
634
+ let statusType;
635
+ if (statusDef !== undefined && (statusDef.type === 'select' || statusDef.type === 'status')) {
636
+ statusType = statusDef.type;
637
+ }
638
+ else {
639
+ problems.push(statusPropertyRefusalReason(resolved.statusProperty, statusDef));
640
+ }
641
+ const mappable = {};
642
+ for (const [name, value] of Object.entries(card.properties ?? {})) {
643
+ if (name === resolved.titleProperty) {
644
+ continue; // written once below, from the same source value.
645
+ }
646
+ if (name === resolved.statusProperty) {
647
+ problems.push(`${name} (state is set from card.state, not card.properties — remove this entry)`);
648
+ continue;
649
+ }
650
+ const def = schema.properties[name];
651
+ if (def === undefined) {
652
+ problems.push(`${name} (no such property on the database)`);
653
+ continue;
654
+ }
655
+ const written = propertyWritePayload(def.type, value);
656
+ if (!written.ok) {
657
+ problems.push(`${name} (type "${def.type}" cannot be written safely)`);
658
+ continue;
659
+ }
660
+ mappable[name] = written.payload;
661
+ }
662
+ if (problems.length > 0) {
663
+ return {
664
+ outcome: 'refused',
665
+ reason: `card cannot be created without silently dropping or misinterpreting data: ${problems.join(', ')}`,
666
+ };
667
+ }
668
+ const titleText = card.properties?.[resolved.titleProperty] ?? '';
669
+ const properties = {
670
+ ...mappable,
671
+ [resolved.titleProperty]: { title: titleText === '' ? [] : [{ text: { content: titleText } }] },
672
+ // `statusType` is guaranteed defined here: `problems` is empty, and
673
+ // the only way it stays undefined is the branch above that pushes a
674
+ // problem.
675
+ [resolved.statusProperty]: { [statusType]: { name: card.state } },
676
+ };
677
+ const createOutcome = await request(resolved, 'POST', '/pages', {
678
+ parent: { database_id: resolved.databaseId },
679
+ properties,
680
+ });
681
+ return toWriteResult(createOutcome, `card ${card.id} could not be created`);
682
+ }
683
+ async function performAnnotate(id, patch, resolved, options) {
684
+ if (options?.expectedRevision !== undefined) {
685
+ return { outcome: 'unsupported', id, reason: EXPECTED_REVISION_UNSUPPORTED_REASON };
686
+ }
687
+ const pageOutcome = await request(resolved, 'GET', `/pages/${encodeURIComponent(id)}`);
688
+ if (pageOutcome.kind !== 'ok') {
689
+ return toWriteFailure(pageOutcome, `no card with id ${id}`);
690
+ }
691
+ const page = asNotionPage(pageOutcome.body);
692
+ if (page === undefined) {
693
+ return { outcome: 'unreachable', reason: unreadableBodyMessage('page') };
694
+ }
695
+ const toWrite = {};
696
+ for (const [key, value] of Object.entries(patch.properties)) {
697
+ const existing = page.properties[key];
698
+ if (existing === undefined) {
699
+ return {
700
+ outcome: 'refused',
701
+ reason: `property "${key}" does not exist on card ${id}, so it cannot be annotated`,
702
+ };
703
+ }
704
+ const written = propertyWritePayload(existing.type, value);
705
+ if (!written.ok) {
706
+ return {
707
+ outcome: 'refused',
708
+ reason: `property "${key}" has type "${existing.type}", which annotate cannot write safely — only rich_text and url properties are supported`,
709
+ };
710
+ }
711
+ const currentValue = existing.type === 'rich_text' ? plainTextOf(existing.rich_text) : (existing.url ?? '');
712
+ if (currentValue !== value) {
713
+ toWrite[key] = written.payload;
714
+ }
715
+ }
716
+ if (Object.keys(toWrite).length === 0) {
717
+ return { outcome: 'applied' };
718
+ }
719
+ const patchOutcome = await request(resolved, 'PATCH', `/pages/${encodeURIComponent(id)}`, {
720
+ properties: toWrite,
721
+ });
722
+ return toWriteResult(patchOutcome, `no card with id ${id}`);
723
+ }
724
+ export function createNotionBoard(config) {
725
+ const resolved = resolveConfig(config);
726
+ return {
727
+ get: (id) => performGet(id, resolved),
728
+ list: (filter) => performList(filter, resolved),
729
+ writeState: (id, state, options) => performWriteState(id, state, resolved, options),
730
+ createCard: (card) => performCreateCard(card, resolved),
731
+ annotate: (id, patch, options) => performAnnotate(id, patch, resolved, options),
732
+ };
733
+ }