@hogsend/engine 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.52.0",
3
+ "version": "0.53.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -53,17 +53,17 @@
53
53
  "svix": "^1.95.1",
54
54
  "winston": "^3.19.0",
55
55
  "zod": "^4.4.3",
56
- "@hogsend/attribution": "^0.52.0",
57
- "@hogsend/core": "^0.52.0",
58
- "@hogsend/db": "^0.52.0",
59
- "@hogsend/email": "^0.52.0",
60
- "@hogsend/plugin-posthog": "^0.52.0",
61
- "@hogsend/plugin-resend": "^0.52.0",
62
- "@hogsend/sms": "^0.52.0"
56
+ "@hogsend/core": "^0.53.0",
57
+ "@hogsend/attribution": "^0.53.0",
58
+ "@hogsend/db": "^0.53.0",
59
+ "@hogsend/email": "^0.53.0",
60
+ "@hogsend/plugin-posthog": "^0.53.0",
61
+ "@hogsend/plugin-resend": "^0.53.0",
62
+ "@hogsend/sms": "^0.53.0"
63
63
  },
64
64
  "optionalDependencies": {
65
- "@hogsend/plugin-postmark": "^0.52.0",
66
- "@hogsend/plugin-twilio": "^0.52.0"
65
+ "@hogsend/plugin-postmark": "^0.53.0",
66
+ "@hogsend/plugin-twilio": "^0.53.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/node": "^22.15.3",
package/src/index.ts CHANGED
@@ -583,6 +583,7 @@ export {
583
583
  // filter, the 'qr' source marker) is deliberately NOT exported — it is
584
584
  // internal mechanics behind the /qr endpoint, not semver surface.
585
585
  export {
586
+ IdempotencyConflictError,
586
587
  type LinkType,
587
588
  type MintedLink,
588
589
  type MintLinkOptions,
@@ -70,7 +70,7 @@ import {
70
70
  registerRecordLabel,
71
71
  } from "./journey-boundary.js";
72
72
  import { logTransition } from "./journey-log.js";
73
- import { readRecordedValue, recordOnce } from "./record-once.js";
73
+ import { recordOnce } from "./record-once.js";
74
74
 
75
75
  /** Journey statuses that are terminal — a journey in any of these must never be
76
76
  * resurrected back to "active" by a wait resuming. Exported so the durable task
@@ -383,28 +383,25 @@ export function createJourneyContext(
383
383
  // and the live CEL filter swap their user predicate for the group one).
384
384
  groupScope?: { type: string; key: string },
385
385
  ): Promise<WaitForEventResult> => {
386
- // Terminal mark (the digest pattern): the recorded outcome — NOT the
387
- // deadline — is what makes this wait replay-stable. `waitDeadline` is a
388
- // shared column cleared at resolution so the NEXT wait site can mint its
389
- // own, which means a replay-from-top of an ALREADY-RESOLVED wait re-derives
390
- // a shifted scan window in which the resolving row is typically invisible —
391
- // a re-armed wait could then flip to the timeout branch (duplicate-but-
392
- // different sends downstream: the exact divergence class this engine's
393
- // replay-safety design forbids). So the outcome is frozen set-once under
394
- // `__waits__` and a replay returns it verbatim before touching the
395
- // deadline. Registering the label makes an intra-run duplicate wait label
396
- // a loud authoring error instead of a silent stale-outcome replay.
386
+ // Replay stability (the digest pattern, applied to CONTROL FLOW): Hatchet's
387
+ // journal is positional AND param-checked for COMPLETED entries, so a
388
+ // replay-from-top must re-issue exactly the durable calls the original run
389
+ // made, with identical parameters — skipping the wait (an early-returned
390
+ // recorded outcome) or re-computing a sleep duration from the wall clock
391
+ // makes the next durable call land on the wrong journal slot and the whole
392
+ // run fails with a non-determinism error (#591). The rule here is therefore
393
+ // NEVER skip a durable call; instead FREEZE every non-journaled input the
394
+ // control flow branches on — each scan result (`<nodeId>:scan:<seq>`), each
395
+ // arm's remaining-ms (`<nodeId>:arm:<seq>`, which is also the sleep param),
396
+ // and the deadline itself (`<nodeId>:deadline`; the shared `waitDeadline`
397
+ // column is cleared at resolution so it can't be the replay truth) — so the
398
+ // replay walks the identical branch sequence, Hatchet answers each re-issued
399
+ // waitFor from the journal instantly, and `recordOnce` at the end returns
400
+ // the frozen outcome verbatim. Registering the label makes an intra-run
401
+ // duplicate wait label a loud authoring error instead of a silent
402
+ // stale-outcome replay.
397
403
  registerRecordLabel(getJourneyBoundary(), `wait:${nodeId}`);
398
404
  const outcomeKey = `${nodeId}:result`;
399
- const priorOutcome = await readRecordedValue({
400
- db,
401
- stateId,
402
- namespace: "__waits__",
403
- key: outcomeKey,
404
- });
405
- if (priorOutcome !== undefined) {
406
- return priorOutcome as WaitForEventResult;
407
- }
408
405
  const recordOutcome = (o: WaitForEventResult) =>
409
406
  recordOnce({
410
407
  db,
@@ -414,16 +411,28 @@ export function createJourneyContext(
414
411
  compute: () => o,
415
412
  });
416
413
 
417
- // Durable deadline: read-first / set-once.
414
+ // Durable deadline: read-first / set-once. The RECORDED copy is the replay
415
+ // truth; the `waitDeadline` column is still written for observability and
416
+ // as the pre-record source for runs armed by an engine without the record
417
+ // (mixed-version replay keeps the original deadline instead of extending).
418
418
  const stateRow = await db
419
419
  .select({ waitDeadline: journeyStates.waitDeadline })
420
420
  .from(journeyStates)
421
421
  .where(eq(journeyStates.id, stateId))
422
422
  .limit(1);
423
423
  const storedDeadline = stateRow[0]?.waitDeadline ?? null;
424
- const deadline = storedDeadline
425
- ? new Date(storedDeadline)
426
- : new Date(Date.now() + durationToMs(timeout));
424
+ const deadlineIso = await recordOnce<string>({
425
+ db,
426
+ stateId,
427
+ namespace: "__waits__",
428
+ key: `${nodeId}:deadline`,
429
+ compute: () =>
430
+ (storedDeadline
431
+ ? new Date(storedDeadline)
432
+ : new Date(Date.now() + durationToMs(timeout))
433
+ ).toISOString(),
434
+ });
435
+ const deadline = new Date(deadlineIso);
427
436
  if (!storedDeadline) {
428
437
  await db
429
438
  .update(journeyStates)
@@ -489,8 +498,23 @@ export function createJourneyContext(
489
498
  return null;
490
499
  };
491
500
 
501
+ // Every scan is frozen set-once in call order (misses included — a stored
502
+ // `null` is distinguishable from "not recorded"). On replay the scan
503
+ // sequence returns verbatim, so the loop takes the original branches even
504
+ // though the resolving row is NOW visible in the DB (or a once-visible row
505
+ // aged out of the window).
506
+ let scanSeq = 0;
507
+ const recordedScan = () =>
508
+ recordOnce<Awaited<ReturnType<typeof scanForMatch>>>({
509
+ db,
510
+ stateId,
511
+ namespace: "__waits__",
512
+ key: `${nodeId}:scan:${scanSeq++}`,
513
+ compute: scanForMatch,
514
+ });
515
+
492
516
  // Immediate hit (incl. the lookback window) — resolve without a state flip.
493
- const preHit = await scanForMatch();
517
+ const preHit = await recordedScan();
494
518
  if (preHit) {
495
519
  await clearDeadline();
496
520
  return recordOutcome({ timedOut: false, ...preHit });
@@ -499,8 +523,9 @@ export function createJourneyContext(
499
523
  await enterWait(nodeId, "wait");
500
524
 
501
525
  let outcome: WaitForEventResult;
526
+ let armSeq = 0;
502
527
  while (true) {
503
- const hit = await scanForMatch();
528
+ const hit = await recordedScan();
504
529
  if (hit) {
505
530
  outcome = { timedOut: false, ...hit };
506
531
  break;
@@ -518,7 +543,16 @@ export function createJourneyContext(
518
543
  throw new JourneyExitedError(stateId);
519
544
  }
520
545
 
521
- const remainingMs = deadline.getTime() - Date.now();
546
+ // Frozen per arm: both the conclude-without-arming decision AND the
547
+ // sleep-branch parameter must replay identically (a completed waitFor's
548
+ // journal entry is param-checked).
549
+ const remainingMs = await recordOnce<number>({
550
+ db,
551
+ stateId,
552
+ namespace: "__waits__",
553
+ key: `${nodeId}:arm:${armSeq++}`,
554
+ compute: () => deadline.getTime() - Date.now(),
555
+ });
522
556
  if (remainingMs <= 0) {
523
557
  outcome = { timedOut: true };
524
558
  break;
@@ -541,7 +575,7 @@ export function createJourneyContext(
541
575
  if (!("event" in fired)) {
542
576
  // Timeout branch — one final scan for an event landing exactly as the
543
577
  // sleep expired, then conclude.
544
- const last = await scanForMatch();
578
+ const last = await recordedScan();
545
579
  outcome = last ? { timedOut: false, ...last } : { timedOut: true };
546
580
  break;
547
581
  }
@@ -617,48 +651,65 @@ export function createJourneyContext(
617
651
  // can never re-push. A recent matching user_events row resolves the wait
618
652
  // immediately, payload included.
619
653
  if (lookback) {
620
- const since = new Date(
621
- (await refreshNow()).getTime() - durationToMs(lookback),
622
- );
623
- const recent = await db
624
- .select({
625
- properties: userEvents.properties,
626
- occurredAt: userEvents.occurredAt,
627
- })
628
- .from(userEvents)
629
- .where(
630
- and(
631
- eq(userEvents.userId, userId),
632
- eq(userEvents.event, event),
633
- gte(userEvents.occurredAt, since),
634
- ),
635
- )
636
- .orderBy(desc(userEvents.occurredAt))
637
- .limit(1);
638
- const row = recent[0];
639
- if (row) {
640
- const scalars = Object.fromEntries(
641
- Object.entries(row.properties ?? {}).filter(
642
- ([, v]) =>
643
- typeof v === "string" ||
644
- typeof v === "number" ||
645
- typeof v === "boolean" ||
646
- v === null,
647
- ),
648
- ) as NonNullable<WaitForEventResult["properties"]>;
649
- const occurredAt =
650
- row.occurredAt instanceof Date
651
- ? row.occurredAt.toISOString()
652
- : row.occurredAt
653
- ? String(row.occurredAt)
654
- : undefined;
655
- return {
656
- timedOut: false,
657
- properties: scalars,
658
- ...(occurredAt ? { occurredAt } : {}),
659
- // Lookback rows are user-scoped, so the actor IS the enrolled user.
660
- actorUserId: userId,
661
- };
654
+ // Recording under this node's key makes an intra-run duplicate wait
655
+ // label a loud error here too (same registry as the filtered leg).
656
+ registerRecordLabel(getJourneyBoundary(), `wait:${nodeId}`);
657
+ // Frozen set-once (miss included): whether the wait resolved via lookback
658
+ // is a control-flow branch in front of a durable call, so a replay must
659
+ // take the SAME side even though the window has shifted and the DB has
660
+ // moved on (the positional-journal rule — see the filtered leg above).
661
+ const lookbackHit = await recordOnce<WaitForEventResult | null>({
662
+ db,
663
+ stateId,
664
+ namespace: "__waits__",
665
+ key: `${nodeId}:lookback`,
666
+ compute: async () => {
667
+ const since = new Date(
668
+ (await refreshNow()).getTime() - durationToMs(lookback),
669
+ );
670
+ const recent = await db
671
+ .select({
672
+ properties: userEvents.properties,
673
+ occurredAt: userEvents.occurredAt,
674
+ })
675
+ .from(userEvents)
676
+ .where(
677
+ and(
678
+ eq(userEvents.userId, userId),
679
+ eq(userEvents.event, event),
680
+ gte(userEvents.occurredAt, since),
681
+ ),
682
+ )
683
+ .orderBy(desc(userEvents.occurredAt))
684
+ .limit(1);
685
+ const row = recent[0];
686
+ if (!row) return null;
687
+ const scalars = Object.fromEntries(
688
+ Object.entries(row.properties ?? {}).filter(
689
+ ([, v]) =>
690
+ typeof v === "string" ||
691
+ typeof v === "number" ||
692
+ typeof v === "boolean" ||
693
+ v === null,
694
+ ),
695
+ ) as NonNullable<WaitForEventResult["properties"]>;
696
+ const occurredAt =
697
+ row.occurredAt instanceof Date
698
+ ? row.occurredAt.toISOString()
699
+ : row.occurredAt
700
+ ? String(row.occurredAt)
701
+ : undefined;
702
+ return {
703
+ timedOut: false,
704
+ properties: scalars,
705
+ ...(occurredAt ? { occurredAt } : {}),
706
+ // Lookback rows are user-scoped, so the actor IS the enrolled user.
707
+ actorUserId: userId,
708
+ };
709
+ },
710
+ });
711
+ if (lookbackHit) {
712
+ return lookbackHit;
662
713
  }
663
714
  }
664
715
 
package/src/lib/links.ts CHANGED
@@ -59,6 +59,15 @@ export interface MintLinkOptions {
59
59
  * OAuth redirect_uri destinations.
60
60
  */
61
61
  appendRef?: boolean;
62
+ /**
63
+ * Idempotent-mint key for slugless links: re-minting with the same key +
64
+ * same destination returns the EXISTING link (`existing: true`) instead of
65
+ * a duplicate; same key + different destination is an
66
+ * IdempotencyConflictError (→ 409). Unique among LIVE links only (partial
67
+ * index) — archiving frees the key. Mutually exclusive with `slug` (a slug
68
+ * IS an idempotency key: same slug + same url + same type recovers too).
69
+ */
70
+ idempotencyKey?: string;
62
71
  }
63
72
 
64
73
  export interface MintedLink {
@@ -72,6 +81,11 @@ export interface MintedLink {
72
81
  slug: string | null;
73
82
  /** The vanity short URL (`${baseUrl}/l/:slug`), if a slug was minted. */
74
83
  vanityUrl: string | null;
84
+ /**
85
+ * True when the mint RECOVERED an existing live link (same slug or
86
+ * idempotencyKey + same destination) instead of inserting a new one.
87
+ */
88
+ existing: boolean;
75
89
  }
76
90
 
77
91
  // ---------------------------------------------------------------------------
@@ -105,11 +119,12 @@ export function normalizeSlug(raw: string): string {
105
119
  }
106
120
 
107
121
  /**
108
- * True when a DB error is the Postgres unique_violation on the slug index.
109
- * Walks the cause chain — drizzle wraps the driver's PostgresError in a
110
- * DrizzleQueryError whose `cause` carries the actual code/constraint.
122
+ * True when a DB error is the Postgres unique_violation on the named
123
+ * constraint. Walks the cause chain — drizzle wraps the driver's
124
+ * PostgresError in a DrizzleQueryError whose `cause` carries the actual
125
+ * code/constraint.
111
126
  */
112
- export function isSlugUniqueViolation(err: unknown): boolean {
127
+ function isUniqueViolationOn(err: unknown, constraint: string): boolean {
113
128
  for (let e = err, depth = 0; e && depth < 5; depth++) {
114
129
  const candidate = e as {
115
130
  code?: string;
@@ -119,8 +134,8 @@ export function isSlugUniqueViolation(err: unknown): boolean {
119
134
  };
120
135
  if (
121
136
  candidate.code === "23505" &&
122
- (candidate.constraint_name === "links_slug_unique" ||
123
- (candidate.message?.includes("links_slug_unique") ?? false))
137
+ (candidate.constraint_name === constraint ||
138
+ (candidate.message?.includes(constraint) ?? false))
124
139
  ) {
125
140
  return true;
126
141
  }
@@ -129,6 +144,31 @@ export function isSlugUniqueViolation(err: unknown): boolean {
129
144
  return false;
130
145
  }
131
146
 
147
+ /** True when a DB error is the unique_violation on the slug index. */
148
+ export function isSlugUniqueViolation(err: unknown): boolean {
149
+ return isUniqueViolationOn(err, "links_slug_unique");
150
+ }
151
+
152
+ /**
153
+ * True when a DB error is the unique_violation on the partial (live-rows-only)
154
+ * idempotency-key index.
155
+ */
156
+ export function isIdempotencyKeyViolation(err: unknown): boolean {
157
+ return isUniqueViolationOn(err, "links_idempotency_key_unique");
158
+ }
159
+
160
+ /**
161
+ * Thrown when an idempotencyKey is already held by a LIVE link with a
162
+ * DIFFERENT destination → HTTP 409. (Same destination is not a conflict — it
163
+ * recovers the existing link.)
164
+ */
165
+ export class IdempotencyConflictError extends Error {
166
+ constructor(key: string) {
167
+ super(`Idempotency key "${key}" already used for a different destination`);
168
+ this.name = "IdempotencyConflictError";
169
+ }
170
+ }
171
+
132
172
  export function vanityUrlFor(baseUrl: string, slug: string): string {
133
173
  return `${baseUrl}/l/${slug}`;
134
174
  }
@@ -240,8 +280,39 @@ export function assertHttpUrl(url: string): void {
240
280
  }
241
281
  }
242
282
 
283
+ /**
284
+ * Build the MintedLink for an already-existing LIVE links row (idempotent
285
+ * recovery): resolves its CANONICAL tracked row (the redirect row, never the
286
+ * lazily-minted QR scan row) via the shared canonical-row predicate. Returns
287
+ * null if the link somehow has no tracked row — callers fall back to their
288
+ * conflict path rather than fabricating a dead redirect URL.
289
+ */
290
+ async function recoverExistingLink(
291
+ db: Database,
292
+ baseUrl: string,
293
+ row: { id: string; slug: string | null },
294
+ ): Promise<MintedLink | null> {
295
+ const [tracked] = await db
296
+ .select({ id: sql<string | null>`min(${trackedLinks.id}::text)` })
297
+ .from(trackedLinks)
298
+ .where(and(eq(trackedLinks.linkId, row.id), canonicalTrackedRowFilter()));
299
+ const trackedLinkId = tracked?.id ?? null;
300
+ if (!trackedLinkId) return null;
301
+ return {
302
+ linkId: row.id,
303
+ trackedLinkId,
304
+ url: `${baseUrl}/v1/t/c/${trackedLinkId}`,
305
+ slug: row.slug,
306
+ vanityUrl: row.slug ? vanityUrlFor(baseUrl, row.slug) : null,
307
+ existing: true,
308
+ };
309
+ }
310
+
243
311
  export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
244
312
  assertHttpUrl(opts.url);
313
+ if (opts.slug !== undefined && opts.idempotencyKey !== undefined) {
314
+ throw new Error("mintLink: slug and idempotencyKey are mutually exclusive");
315
+ }
245
316
  const type: LinkType = opts.type ?? "public";
246
317
  // A public link must NEVER carry a person token — drop any distinctId.
247
318
  const distinctId = type === "personal" ? (opts.distinctId ?? null) : null;
@@ -267,6 +338,7 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
267
338
  source: opts.source,
268
339
  distinctId,
269
340
  createdBy: opts.createdBy ?? null,
341
+ idempotencyKey: opts.idempotencyKey ?? null,
270
342
  });
271
343
  await tx.insert(trackedLinks).values({
272
344
  id: trackedLinkId,
@@ -278,7 +350,45 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
278
350
  });
279
351
  });
280
352
  } catch (err) {
281
- if (slug && isSlugUniqueViolation(err)) throw new SlugTakenError(slug);
353
+ // Idempotent recovery. NOTE: these queries run AFTER the aborted
354
+ // transaction, on opts.db directly — the tx object is dead.
355
+ if (slug && isSlugUniqueViolation(err)) {
356
+ // A slug re-mint with the SAME destination + type is the same intent —
357
+ // return the existing LIVE link instead of 409ing a retry.
358
+ const [row] = await opts.db
359
+ .select()
360
+ .from(links)
361
+ .where(and(eq(links.slug, slug), isNull(links.archivedAt)))
362
+ .limit(1);
363
+ if (row && row.originalUrl === opts.url && row.type === type) {
364
+ const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
365
+ if (recovered) return recovered;
366
+ }
367
+ // Slug held by an ARCHIVED link (the live lookup misses — archived
368
+ // links keep their slug reserved), a different destination, or a
369
+ // different type → conflict.
370
+ throw new SlugTakenError(slug);
371
+ }
372
+ if (opts.idempotencyKey && isIdempotencyKeyViolation(err)) {
373
+ const [row] = await opts.db
374
+ .select()
375
+ .from(links)
376
+ .where(
377
+ and(
378
+ eq(links.idempotencyKey, opts.idempotencyKey),
379
+ isNull(links.archivedAt),
380
+ ),
381
+ )
382
+ .limit(1);
383
+ if (row && row.originalUrl === opts.url) {
384
+ const recovered = await recoverExistingLink(opts.db, opts.baseUrl, row);
385
+ if (recovered) return recovered;
386
+ }
387
+ if (row) throw new IdempotencyConflictError(opts.idempotencyKey);
388
+ // Defensive: the partial index only covers live rows, so the winning
389
+ // row should always be live — if it vanished, surface the raw error.
390
+ throw err;
391
+ }
282
392
  throw err;
283
393
  }
284
394
 
@@ -288,5 +398,6 @@ export async function mintLink(opts: MintLinkOptions): Promise<MintedLink> {
288
398
  url: `${opts.baseUrl}/v1/t/c/${trackedLinkId}`,
289
399
  slug,
290
400
  vanityUrl: slug ? vanityUrlFor(opts.baseUrl, slug) : null,
401
+ existing: false,
291
402
  };
292
403
  }
@@ -17,6 +17,7 @@ import {
17
17
  assertHttpUrl,
18
18
  canonicalTrackedRowFilter,
19
19
  ensureQrTrackedLink,
20
+ IdempotencyConflictError,
20
21
  isSlugUniqueViolation,
21
22
  mintLink,
22
23
  normalizeSlug,
@@ -118,6 +119,12 @@ const destinationStatSchema = z.object({
118
119
  lastAt: z.string(),
119
120
  });
120
121
 
122
+ // POST-only extension of the shared flat shape: `existing` reports whether the
123
+ // mint recovered an already-live link (idempotent re-mint) instead of
124
+ // inserting. Deliberately NOT on linkSchema — GET/list/PATCH/DELETE have no
125
+ // mint semantics.
126
+ const createdLinkSchema = linkSchema.extend({ existing: z.boolean() });
127
+
121
128
  const linkDetailSchema = linkSchema.extend({
122
129
  clicks: z.array(clickSchema),
123
130
  destinations: z.array(destinationStatSchema),
@@ -183,29 +190,47 @@ const createLinkRoute = createRoute({
183
190
  body: {
184
191
  content: {
185
192
  "application/json": {
186
- schema: z.object({
187
- url: z.string().url(),
188
- type: z.enum(["personal", "public"]).default("public"),
189
- // Optional vanity slug (`/l/:slug`). Normalized lowercase; 409 if
190
- // already taken.
191
- slug: z.string().optional(),
192
- label: z.string().optional(),
193
- description: z.string().optional(),
194
- appendRef: z.boolean().optional(),
195
- campaign: z.string().optional(),
196
- // Honoured ONLY for personal links (the share-safe invariant in
197
- // mintLink drops it for public). A canonical contact key the click
198
- // should stitch the visitor's anon session into.
199
- distinctId: z.string().optional(),
200
- }),
193
+ schema: z
194
+ .object({
195
+ url: z.string().url(),
196
+ type: z.enum(["personal", "public"]).default("public"),
197
+ // Optional vanity slug (`/l/:slug`). Normalized lowercase; 409 if
198
+ // already taken by a different destination (same destination +
199
+ // type recovers the existing link — see idempotencyKey).
200
+ slug: z.string().optional(),
201
+ label: z.string().optional(),
202
+ description: z.string().optional(),
203
+ appendRef: z.boolean().optional(),
204
+ campaign: z.string().optional(),
205
+ // Honoured ONLY for personal links (the share-safe invariant in
206
+ // mintLink drops it for public). A canonical contact key the click
207
+ // should stitch the visitor's anon session into.
208
+ distinctId: z.string().optional(),
209
+ // Honest originating channel: Studio UI mints say "studio", SDK/
210
+ // programmatic mints say "api".
211
+ source: z.enum(["studio", "api"]).default("studio"),
212
+ // Idempotent-mint key for slugless links: same key + same url
213
+ // returns the existing link (existing: true); same key +
214
+ // different url is a 409. Mutually exclusive with slug (a slug
215
+ // IS an idempotency key).
216
+ idempotencyKey: z
217
+ .string()
218
+ .min(1)
219
+ .max(255)
220
+ .regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/)
221
+ .optional(),
222
+ })
223
+ .refine((d) => !(d.slug && d.idempotencyKey), {
224
+ message: "slug and idempotencyKey are mutually exclusive",
225
+ }),
201
226
  },
202
227
  },
203
228
  },
204
229
  },
205
230
  responses: {
206
231
  200: {
207
- content: { "application/json": { schema: linkSchema } },
208
- description: "Minted link",
232
+ content: { "application/json": { schema: createdLinkSchema } },
233
+ description: "Minted link (existing: true = idempotent re-mint)",
209
234
  },
210
235
  400: {
211
236
  content: { "application/json": { schema: errorSchema } },
@@ -213,7 +238,7 @@ const createLinkRoute = createRoute({
213
238
  },
214
239
  409: {
215
240
  content: { "application/json": { schema: errorSchema } },
216
- description: "Slug already taken",
241
+ description: "Slug or idempotency key already taken",
217
242
  },
218
243
  },
219
244
  });
@@ -415,7 +440,7 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
415
440
  db,
416
441
  url: body.url,
417
442
  baseUrl: env.API_PUBLIC_URL,
418
- source: "studio",
443
+ source: body.source,
419
444
  type: body.type,
420
445
  slug: body.slug,
421
446
  label: body.label,
@@ -424,6 +449,7 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
424
449
  campaign: body.campaign,
425
450
  distinctId: body.distinctId,
426
451
  createdBy: resolveActor(c) ?? undefined,
452
+ idempotencyKey: body.idempotencyKey,
427
453
  });
428
454
 
429
455
  const [row] = await db
@@ -436,16 +462,22 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
436
462
  return c.json({ error: "Mint succeeded but link not found" }, 400);
437
463
  }
438
464
 
465
+ // One aggregate path for BOTH fresh and recovered mints: a fresh mint
466
+ // aggregates to clicks:0/scans:0 with the canonical trackedLinkId; a
467
+ // recovered link reports its real counts.
468
+ const agg = await aggregateFor(db, [minted.linkId]);
439
469
  return c.json(
440
- serializeLink(
441
- row,
442
- { clicks: 0, scans: 0, trackedLinkId: minted.trackedLinkId },
443
- env.API_PUBLIC_URL,
444
- ),
470
+ {
471
+ ...serializeLink(row, agg.get(minted.linkId), env.API_PUBLIC_URL),
472
+ existing: minted.existing,
473
+ },
445
474
  200,
446
475
  );
447
476
  } catch (err) {
448
- if (err instanceof SlugTakenError) {
477
+ if (
478
+ err instanceof SlugTakenError ||
479
+ err instanceof IdempotencyConflictError
480
+ ) {
449
481
  return c.json({ error: err.message }, 409);
450
482
  }
451
483
  const message = err instanceof Error ? err.message : "Mint failed";