@12-apps/marketplace 1.3.0 → 1.4.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.
Files changed (53) hide show
  1. package/ADOPTING.md +47 -0
  2. package/README.md +71 -0
  3. package/dist/99food/index.d.ts +33 -2
  4. package/dist/99food/index.js +34 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-0l_EmuJA.d.ts → adapter-B8QtQ2RA.d.ts} +126 -3
  7. package/dist/{chunk-AYYBRQJV.js → chunk-DPCZVN2C.js} +43 -3
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-XUAFXNOH.js → chunk-EBAIZQPB.js} +395 -4
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/{chunk-RVBTARIY.js → chunk-SZRZTLVU.js} +1 -1
  12. package/dist/chunk-SZRZTLVU.js.map +1 -0
  13. package/dist/{engine-CZsP8KWd.d.ts → engine-o5cm54vC.d.ts} +242 -2
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +14 -2
  17. package/dist/ifood/index.js +164 -1
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +300 -3
  21. package/dist/index.js.map +1 -1
  22. package/dist/manifest/server.d.ts +4 -2
  23. package/dist/manifest/server.js +2 -2
  24. package/dist/rappi/index.d.ts +15 -2
  25. package/dist/rappi/index.js +56 -2
  26. package/dist/rappi/index.js.map +1 -1
  27. package/dist/server/index.d.ts +18 -7
  28. package/dist/server/index.js +4 -2
  29. package/package.json +1 -1
  30. package/prisma/marketplace.prisma +67 -1
  31. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  32. package/src/99food/index.ts +10 -0
  33. package/src/99food/pause.ts +56 -0
  34. package/src/core/adapter.ts +12 -2
  35. package/src/core/engine.ts +37 -0
  36. package/src/core/pause-job.ts +381 -0
  37. package/src/core/pause-port.ts +110 -0
  38. package/src/core/pause-retired.ts +139 -0
  39. package/src/core/pause-store.ts +151 -0
  40. package/src/core/pause-sweep.ts +148 -0
  41. package/src/core/pause.ts +316 -0
  42. package/src/core/ports.ts +11 -0
  43. package/src/ifood/index.ts +4 -0
  44. package/src/ifood/pause.ts +257 -0
  45. package/src/index.ts +24 -0
  46. package/src/rappi/index.ts +11 -0
  47. package/src/rappi/outbound.ts +2 -2
  48. package/src/rappi/pause.ts +98 -0
  49. package/src/server/index.ts +1 -0
  50. package/src/server/jobs.ts +64 -4
  51. package/dist/chunk-AYYBRQJV.js.map +0 -1
  52. package/dist/chunk-RVBTARIY.js.map +0 -1
  53. package/dist/chunk-XUAFXNOH.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { m as CatalogueItem, l as CatalogueImage, a as NormalizedMarketplaceOrder, v as MarketplaceHttp, M as MarketplaceAdapter, e as MarketplaceProvider, t as MarketplaceCredentials, q as CatalogueWarningCode, f as CancellationReason, O as OutboundOrderRef, N as NormalizedEvent, b as CatalogueMenuOptions } from './adapter-0l_EmuJA.js';
1
+ import { p as CatalogueItem, o as CatalogueImage, a as NormalizedMarketplaceOrder, y as MarketplaceHttp, c as MarketplaceAdapter, h as MarketplaceProvider, w as MarketplaceCredentials, t as CatalogueWarningCode, i as CancellationReason, I as OutboundOrderRef, N as NormalizedEvent, b as CatalogueMenuOptions } from './adapter-B8QtQ2RA.js';
2
2
 
3
3
  /**
4
4
  * What the engine needs FROM its host, and nothing more.
@@ -76,6 +76,19 @@ interface MarketplaceDb {
76
76
  count: number;
77
77
  }>;
78
78
  };
79
+ /**
80
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
81
+ * pause model still compiles; `pauseStore` refuses without it (FUT-4851,
82
+ * migration `20261113230000_marketplace_store_pause`).
83
+ */
84
+ marketplaceStorePause?: {
85
+ findFirst(args: unknown): Promise<unknown>;
86
+ findMany(args: unknown): Promise<unknown[]>;
87
+ upsert(args: unknown): Promise<unknown>;
88
+ updateMany(args: unknown): Promise<{
89
+ count: number;
90
+ }>;
91
+ };
79
92
  }
80
93
  /**
81
94
  * One order line after the engine has matched it against the SKU map.
@@ -929,6 +942,210 @@ interface OutboundAttempt {
929
942
  maxAttempts: number;
930
943
  }
931
944
 
945
+ /**
946
+ * The pause record: one row per (store, marketplace), the engine's memory of
947
+ * what it asked the marketplace and what the marketplace holds (FUT-4851).
948
+ *
949
+ * Two fields say two different things, and the job reconciles them:
950
+ *
951
+ * - `wanted` is the host's LAST ask (PAUSED or OPEN). The last ask wins: a
952
+ * resume that lands while a pause is in flight, or a pause while a resume
953
+ * is, only rewrites `wanted`, and the job re-reads it after every call.
954
+ * - `state` is where the marketplace stands as far as the engine knows:
955
+ * OPEN → PAUSING → PAUSED → RESUMING → OPEN, or FAILED with a code.
956
+ *
957
+ * What the engine holds on the marketplace is `externalId` (the closure's id,
958
+ * for an `interruption`), `sentUntil` (the end the marketplace was given; the
959
+ * only proof of a `switch` the engine turned off) and `attemptKey` with
960
+ * `attemptUntil` (the key a create goes out under, written BEFORE the call,
961
+ * and the end it carried, kept while its answer is in doubt).
962
+ * `retiredExternalIds` are the closures a renewal replaced, still to be
963
+ * deleted. Nothing else is ever deleted: a closure the owner made by hand is
964
+ * in none of them.
965
+ */
966
+ /** Where the marketplace stands, as far as the engine knows. Vocabulary, not copy. */
967
+ type StorePauseState = "OPEN" | "PAUSING" | "PAUSED" | "RESUMING" | "FAILED";
968
+ /** The host's last ask. */
969
+ type StorePauseWanted = "PAUSED" | "OPEN";
970
+ /**
971
+ * Why a record is FAILED. Machine codes, never a sentence: the host renders
972
+ * them, and the marketplace's own words travel in `failureDetail`.
973
+ *
974
+ * - `UNSUPPORTED`: the marketplace's adapter has no availability capability.
975
+ * - `NOT_CONNECTED`: no credentials or no merchant id on the connection.
976
+ * - `PAUSE_REFUSED` / `RESUME_REFUSED`: the marketplace said no (a final 4xx).
977
+ * - `PAUSE_UNANSWERED` / `RESUME_UNANSWERED`: every attempt failed without an
978
+ * answer (5xx, a timeout, a rate limit), or the sweep gave up waiting.
979
+ */
980
+ type StorePauseFailureCode = "UNSUPPORTED" | "NOT_CONNECTED" | "PAUSE_REFUSED" | "PAUSE_UNANSWERED" | "RESUME_REFUSED" | "RESUME_UNANSWERED";
981
+ /** One record as the engine reads it. */
982
+ interface StorePauseRow {
983
+ id: string;
984
+ clientId: string;
985
+ provider: string;
986
+ state: StorePauseState;
987
+ wanted: StorePauseWanted;
988
+ until: Date | null;
989
+ reason: string | null;
990
+ timeZone: string | null;
991
+ externalId: string | null;
992
+ sentUntil: Date | null;
993
+ attemptKey: string | null;
994
+ attemptUntil: Date | null;
995
+ /** The replaced closures still to delete, oldest first (`./pause-retired.ts` reads and writes it); null when none. */
996
+ retiredExternalIds: string | null;
997
+ failureCode: StorePauseFailureCode | null;
998
+ failureDetail: string | null;
999
+ requestedAt: Date;
1000
+ leaseUntil: Date | null;
1001
+ pausedAt: Date | null;
1002
+ resumedAt: Date | null;
1003
+ failedAt: Date | null;
1004
+ updatedAt: Date | null;
1005
+ }
1006
+ /** The job's wire name. */
1007
+ declare const MARKETPLACE_AVAILABILITY_JOB = "marketplace.availability";
1008
+ /** The job's payload: identifiers only; the ask lives on the row. */
1009
+ interface AvailabilityJobPayload {
1010
+ clientId: string;
1011
+ provider: MarketplaceProvider;
1012
+ }
1013
+ /** How long one run holds a record, so two runs never call the marketplace for it at once. */
1014
+ declare const STORE_PAUSE_LEASE_MS: number;
1015
+ /** The dedupe key of one ask: per record and per ask instant, so a new ask is never swallowed. */
1016
+ declare function availabilityDedupeKey(payload: AvailabilityJobPayload, requestedAt: Date, suffix?: string): string;
1017
+
1018
+ /**
1019
+ * The store pause, as the host calls it (FUT-4851): `pauseStore` when the
1020
+ * kitchen pauses and on every renewal, `resumeStore` the moment the pause is
1021
+ * over, `availabilityState` for the screen. The host owns the debounce; these
1022
+ * calls only record the ask and queue `marketplace.availability`, whose job
1023
+ * makes the calls (`./pause-job.ts`). No path that answers a request reaches
1024
+ * a marketplace.
1025
+ */
1026
+ /** What `pauseStore` did on one marketplace. */
1027
+ type PauseOutcome =
1028
+ /** The ask was recorded and the job queued. */
1029
+ "queued"
1030
+ /** A pause with exactly this end already stands or is on its way. */
1031
+ | "unchanged"
1032
+ /** The marketplace's adapter cannot pause a store: the host says so. */
1033
+ | "unsupported"
1034
+ /** The connection has no credentials or no merchant id. */
1035
+ | "not-connected";
1036
+ /** What `resumeStore` did on one marketplace. */
1037
+ type ResumeOutcome =
1038
+ /** Something of ours stands on the marketplace: the job deletes it. */
1039
+ "queued"
1040
+ /** Nothing of ours stands there: the record is OPEN, and nobody is called. */
1041
+ | "open"
1042
+ /** A resume is already on its way. */
1043
+ | "unchanged";
1044
+ interface PauseStoreInput {
1045
+ clientId: string;
1046
+ /** The kitchen's estimated reopening time: the end every marketplace is given. */
1047
+ until: Date;
1048
+ /** The host's words for the closure (its copy, in the store's language). */
1049
+ reason: string;
1050
+ /** The store's IANA time zone. */
1051
+ timeZone: string;
1052
+ now?: Date;
1053
+ }
1054
+ type PauseStoreResult = {
1055
+ kind: "invalid";
1056
+ code: "UNTIL_NOT_FUTURE" | "TIME_ZONE_INVALID";
1057
+ } | {
1058
+ kind: "ok";
1059
+ marketplaces: {
1060
+ provider: MarketplaceProvider;
1061
+ outcome: PauseOutcome;
1062
+ }[];
1063
+ };
1064
+ /** One marketplace's pause as the screen shows it. */
1065
+ interface StoreAvailabilityView {
1066
+ provider: MarketplaceProvider;
1067
+ /** The adapter can pause a store at all. */
1068
+ supported: boolean;
1069
+ /** `interruption` (an id and an end) or `switch` (on/off); null when unsupported. */
1070
+ kind: "interruption" | "switch" | null;
1071
+ /** The connection has credentials and a merchant id. */
1072
+ connected: boolean;
1073
+ state: StorePauseState;
1074
+ wanted: StorePauseWanted;
1075
+ /** The end the host asked for. */
1076
+ until: Date | null;
1077
+ /** The end the marketplace was given and confirmed. */
1078
+ sentUntil: Date | null;
1079
+ failureCode: StorePauseFailureCode | null;
1080
+ /** The marketplace's own words, verbatim and cut; never copy to show as is. */
1081
+ failureDetail: string | null;
1082
+ pausedAt: Date | null;
1083
+ resumedAt: Date | null;
1084
+ updatedAt: Date | null;
1085
+ }
1086
+
1087
+ /**
1088
+ * The `marketplace.availability` job: bring one marketplace in line with the
1089
+ * host's last ask for one store (FUT-4851).
1090
+ *
1091
+ * The job re-reads the record before every call and after it, so the last ask
1092
+ * wins: a resume that lands while a pause call is in flight finds the closure
1093
+ * that call created recorded, and deletes it on the next step. A run holds a
1094
+ * short lease on the record, so two runs never call one marketplace for one
1095
+ * store at once. The answer rule is the outbound engine's: 2xx done, a final
1096
+ * 4xx FAILED with the marketplace's words, anything else retried by the queue
1097
+ * until the last attempt, which stamps `*_UNANSWERED`.
1098
+ */
1099
+ /** What one run did. */
1100
+ type AvailabilityOutcome = {
1101
+ kind: "skipped";
1102
+ reason: string;
1103
+ } | {
1104
+ kind: "done";
1105
+ state: StorePauseRow["state"];
1106
+ } | {
1107
+ kind: "failed";
1108
+ code: StorePauseFailureCode;
1109
+ };
1110
+ /** Thrown so the queue retries. Its message is what the job log reads. */
1111
+ declare class AvailabilityRetryError extends Error {
1112
+ constructor(message: string);
1113
+ }
1114
+
1115
+ /**
1116
+ * The availability sweep (`marketplace.availability-sweep`, every five
1117
+ * minutes): nothing the engine owes a marketplace for a store's pause is lost,
1118
+ * and no store stays closed past the kitchen's pause (FUT-4851).
1119
+ *
1120
+ * - **Expired**: a pause whose `until` has passed without a renewal is over.
1121
+ * The host stopped renewing (it died, or forgot to resume), so the engine
1122
+ * resumes on its own: the owner's "never closed on a marketplace longer than
1123
+ * the kitchen's own pause". An interruption has already ended on the
1124
+ * marketplace (its delete answers "gone", which is done); a switch would
1125
+ * otherwise stay off for good.
1126
+ * - **Stale**: an ask still PAUSING or RESUMING after the job's own retry span
1127
+ * (a refused enqueue, a dead process) is re-queued; past
1128
+ * {@link OUTBOUND_GIVE_UP_MS} it is FAILED as unanswered.
1129
+ * - **A failed resume that still holds something** is retried each pass until
1130
+ * the give-up: a store must not stay closed because one delete failed.
1131
+ * - **A replaced closure** an extend could not delete is retried.
1132
+ * - **An OPEN record that still holds something** (a pause call whose answer
1133
+ * was lost after a resume landed) goes back to RESUMING and is re-queued.
1134
+ *
1135
+ * Re-queued under a key of its own per pass, as the outbound sweep does. The
1136
+ * job is idempotent by the row and leased, so a duplicate run calls nobody
1137
+ * twice.
1138
+ */
1139
+ /** What one pass did. */
1140
+ interface AvailabilitySweepResult {
1141
+ /** Pauses past their `until`, turned into resumes. */
1142
+ expired: number;
1143
+ /** Asks re-queued. */
1144
+ requeued: number;
1145
+ /** Asks failed as unanswered past the give-up. */
1146
+ givenUp: number;
1147
+ }
1148
+
932
1149
  /** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */
933
1150
  type DeliveryOutcome = {
934
1151
  kind: "ingested";
@@ -1112,6 +1329,29 @@ interface MarketplaceEngine {
1112
1329
  }): Promise<CatalogueDocumentResult>;
1113
1330
  /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
1114
1331
  runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
1332
+ /**
1333
+ * The kitchen paused (or renewed its pause): close the store until `until`
1334
+ * on every live connection whose marketplace can be paused (FUT-4851).
1335
+ * Idempotent: the `until` already standing does nothing; any other, an
1336
+ * earlier one included, renews the closure.
1337
+ */
1338
+ pauseStore(input: PauseStoreInput): Promise<PauseStoreResult>;
1339
+ /** The kitchen's pause is over: delete every closure the engine created, and nothing else. */
1340
+ resumeStore(input: {
1341
+ clientId: string;
1342
+ now?: Date;
1343
+ }): Promise<{
1344
+ marketplaces: {
1345
+ provider: MarketplaceProvider;
1346
+ outcome: ResumeOutcome;
1347
+ }[];
1348
+ }>;
1349
+ /** Where the store's pause stands on each marketplace, for the screen. */
1350
+ availabilityState(clientId: string): Promise<StoreAvailabilityView[]>;
1351
+ /** Bring one marketplace in line with the last ask (the `marketplace.availability` job's body). */
1352
+ runAvailability(payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome>;
1353
+ /** Expire, re-queue and give up on store pauses (the `marketplace.availability-sweep` job's body). */
1354
+ sweepAvailability(now?: Date): Promise<AvailabilitySweepResult>;
1115
1355
  }
1116
1356
  /**
1117
1357
  * Mount the engine onto a host.
@@ -1123,4 +1363,4 @@ interface MarketplaceEngine {
1123
1363
  */
1124
1364
  declare function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine;
1125
1365
 
1126
- export { type MarketplaceOrderState as $, type AcceptanceDecision as A, type BulkProblem as B, type CancellationFailureReason as C, type DecideManyResult as D, type ExpirySweepResult as E, type FetchOrderJobPayload as F, type IngestionTarget as G, type IntegrationRowInput as H, type IngestResult as I, MARKETPLACE_FETCH_ORDER_JOB as J, MARKETPLACE_OUTBOUND_JOB as K, type MarketplaceAdmission as L, MARKETPLACE_CATALOGUE_JOB as M, type MarketplaceAdmissionRequest as N, type MarketplaceAdmissionResult as O, type MarketplaceAuditEntry as P, type MarketplaceAuditPort as Q, type MarketplaceCataloguePort as R, type MarketplaceClockPort as S, type MarketplaceDb as T, type MarketplaceEngine as U, type MarketplaceEngineConfig as V, type MarketplaceEnqueuePort as W, type MarketplaceIntegrationView as X, type MarketplaceLogger as Y, type MarketplaceMenuLinkView as Z, type MarketplaceOrderPort as _, type AcceptanceStatus as a, type MarketplaceOrderSummary as a0, type MarketplacePorts as a1, type MarketplaceRefusal as a2, type MarketplaceSecretsPort as a3, type MenuLinkRowInput as a4, OUTBOUND_GIVE_UP_MS as a5, OUTBOUND_STALE_MS as a6, type OutboundAction as a7, type OutboundAttempt as a8, type OutboundJobPayload as a9, type OutboundOutcome as aa, OutboundRetryError as ab, type OutboundSweepResult as ac, type PendingAcceptance as ad, type PendingInboxEvent as ae, type ResolvedOrderLine as af, type SaveMarketplaceIntegrationInput as ag, catalogueDedupeKey as ah, createMarketplaceEngine as ai, outboundDedupeKey as aj, type BulkProblemCode as b, type BulkResult as c, type CancellationStatus as d, type CatalogueAction as e, type CatalogueActionResult as f, type CatalogueDocumentResult as g, type CatalogueFailedAction as h, type CatalogueFailureCode as i, type CatalogueJobPayload as j, type CatalogueOutcome as k, type CataloguePublicationView as l, type CataloguePublishInput as m, type CatalogueRefusalCode as n, CatalogueRetryError as o, type CatalogueStatus as p, type CatalogueTarget as q, type DecidedRow as r, type DecisionInput as s, type DecisionProblem as t, type DecisionProblemCode as u, type DecisionResult as v, type DeliveryOutcome as w, type FetchOrderOutcome as x, FetchOrderRetryError as y, type IngestSettings as z };
1366
+ export { type MarketplaceEnqueuePort as $, type AcceptanceDecision as A, type BulkProblem as B, type CancellationFailureReason as C, type DecideManyResult as D, type DeliveryOutcome as E, type ExpirySweepResult as F, type FetchOrderJobPayload as G, type FetchOrderOutcome as H, FetchOrderRetryError as I, type IngestResult as J, type IngestSettings as K, type IngestionTarget as L, type IntegrationRowInput as M, MARKETPLACE_AVAILABILITY_JOB as N, MARKETPLACE_CATALOGUE_JOB as O, MARKETPLACE_FETCH_ORDER_JOB as P, MARKETPLACE_OUTBOUND_JOB as Q, type MarketplaceAdmission as R, type MarketplaceAdmissionRequest as S, type MarketplaceAdmissionResult as T, type MarketplaceAuditEntry as U, type MarketplaceAuditPort as V, type MarketplaceCataloguePort as W, type MarketplaceClockPort as X, type MarketplaceDb as Y, type MarketplaceEngine as Z, type MarketplaceEngineConfig as _, type AcceptanceStatus as a, type MarketplaceIntegrationView as a0, type MarketplaceLogger as a1, type MarketplaceMenuLinkView as a2, type MarketplaceOrderPort as a3, type MarketplaceOrderState as a4, type MarketplaceOrderSummary as a5, type MarketplacePorts as a6, type MarketplaceRefusal as a7, type MarketplaceSecretsPort as a8, type MenuLinkRowInput as a9, OUTBOUND_GIVE_UP_MS as aa, OUTBOUND_STALE_MS as ab, type OutboundAction as ac, type OutboundAttempt as ad, type OutboundJobPayload as ae, type OutboundOutcome as af, OutboundRetryError as ag, type OutboundSweepResult as ah, type PauseOutcome as ai, type PauseStoreInput as aj, type PauseStoreResult as ak, type PendingAcceptance as al, type PendingInboxEvent as am, type ResolvedOrderLine as an, type ResumeOutcome as ao, STORE_PAUSE_LEASE_MS as ap, type SaveMarketplaceIntegrationInput as aq, type StoreAvailabilityView as ar, type StorePauseFailureCode as as, type StorePauseState as at, type StorePauseWanted as au, availabilityDedupeKey as av, catalogueDedupeKey as aw, createMarketplaceEngine as ax, outboundDedupeKey as ay, type AvailabilityJobPayload as b, type AvailabilityOutcome as c, AvailabilityRetryError as d, type AvailabilitySweepResult as e, type BulkProblemCode as f, type BulkResult as g, type CancellationStatus as h, type CatalogueAction as i, type CatalogueActionResult as j, type CatalogueDocumentResult as k, type CatalogueFailedAction as l, type CatalogueFailureCode as m, type CatalogueJobPayload as n, type CatalogueOutcome as o, type CataloguePublicationView as p, type CataloguePublishInput as q, type CatalogueRefusalCode as r, CatalogueRetryError as s, type CatalogueStatus as t, type CatalogueTarget as u, type DecidedRow as v, type DecisionInput as w, type DecisionProblem as x, type DecisionProblemCode as y, type DecisionResult as z };
@@ -1,7 +1,7 @@
1
1
  import { Hono, Context } from 'hono';
2
2
  import { ApiMarketplace, MarketplaceApiConfig, MarketplaceActor } from '../server/index.js';
3
- import '../engine-CZsP8KWd.js';
4
- import '../adapter-0l_EmuJA.js';
3
+ import '../engine-o5cm54vC.js';
4
+ import '../adapter-B8QtQ2RA.js';
5
5
  import '@12-apps/wiring';
6
6
  import 'zod';
7
7
 
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  createApiMarketplace
3
- } from "../chunk-AYYBRQJV.js";
3
+ } from "../chunk-DPCZVN2C.js";
4
4
  import "../chunk-UYFYGGCS.js";
5
- import "../chunk-XUAFXNOH.js";
5
+ import "../chunk-EBAIZQPB.js";
6
6
  import {
7
7
  __name
8
8
  } from "../chunk-7QVYU63E.js";
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, c as PushCatalogue, d as CatalogueItemOut, M as MarketplaceAdapter } from '../adapter-0l_EmuJA.js';
1
+ import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, f as StorePauseResult, g as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-B8QtQ2RA.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -50,6 +50,18 @@ declare function ifoodItemBody(item: CatalogueItemOut, category: string, image:
50
50
  /** iFood's catalogue capability. */
51
51
  declare const IFOOD_CATALOGUE: PushCatalogue;
52
52
 
53
+ /**
54
+ * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.
55
+ * Read the same whether iFood honours the offset or reads the store's clock.
56
+ */
57
+ declare function ifoodLocalTime(date: Date, timeZone: string): string;
58
+ /** Close the store until `request.until`: find one a lost answer created under the key, else create it. */
59
+ declare function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult>;
60
+ /** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */
61
+ declare function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult>;
62
+ /** iFood's availability capability: interruptions, no extend. */
63
+ declare const IFOOD_AVAILABILITY: MarketplaceAvailability;
64
+
53
65
  /**
54
66
  * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.
55
67
  *
@@ -76,4 +88,4 @@ interface IfoodAdapterConfig {
76
88
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
77
89
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
78
90
 
79
- export { IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodProductId, normalizeIfoodEvent, verifyIfoodSignature };
91
+ export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };
@@ -12,7 +12,7 @@ import {
12
12
  import {
13
13
  answered,
14
14
  outboundResultOf
15
- } from "../chunk-RVBTARIY.js";
15
+ } from "../chunk-SZRZTLVU.js";
16
16
  import {
17
17
  __name
18
18
  } from "../chunk-7QVYU63E.js";
@@ -383,6 +383,163 @@ function normalizeIfoodEvent(payload, options) {
383
383
  }
384
384
  __name(normalizeIfoodEvent, "normalizeIfoodEvent");
385
385
 
386
+ // src/ifood/pause.ts
387
+ var interruptionsUrl = /* @__PURE__ */ __name((merchantId) => `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`, "interruptionsUrl");
388
+ async function call2(ctx, request) {
389
+ const auth = await bearer(ctx);
390
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
391
+ const response = await ctx.http({
392
+ method: request.method,
393
+ url: request.url,
394
+ headers: {
395
+ Authorization: `Bearer ${auth.token}`,
396
+ ...request.json === void 0 ? {} : { "Content-Type": "application/json" }
397
+ },
398
+ ...request.json === void 0 ? {} : { body: JSON.stringify(request.json) }
399
+ });
400
+ if (response.status !== 401) return response;
401
+ ctx.tokens.delete(ifoodTokenKey(ctx));
402
+ return { kind: "retry", reason: "iFood refused the token" };
403
+ }
404
+ __name(call2, "call");
405
+ var settled = /* @__PURE__ */ __name((value) => "kind" in value, "settled");
406
+ function notOk(response) {
407
+ const result = outboundResultOf(response);
408
+ return result.kind === "accepted" ? null : result;
409
+ }
410
+ __name(notOk, "notOk");
411
+ async function listInterruptions(ctx, merchantId) {
412
+ const response = await call2(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
413
+ if (settled(response)) return response;
414
+ const failure = notOk(response);
415
+ if (failure) return failure;
416
+ try {
417
+ const parsed = JSON.parse(response.body === "" ? "[]" : response.body);
418
+ if (!Array.isArray(parsed)) return [];
419
+ return parsed.flatMap((entry) => {
420
+ const value = entry ?? {};
421
+ if (typeof value.id !== "string") return [];
422
+ return [
423
+ {
424
+ id: value.id,
425
+ end: typeof value.end === "string" ? value.end : null,
426
+ description: typeof value.description === "string" ? value.description : null
427
+ }
428
+ ];
429
+ });
430
+ } catch {
431
+ return { kind: "retry", reason: "iFood answered the interruption list with something that is not JSON" };
432
+ }
433
+ }
434
+ __name(listInterruptions, "listInterruptions");
435
+ function sameEnd(end, until, timeZone) {
436
+ const sent = ifoodLocalTime(until, timeZone);
437
+ if (end === sent) return true;
438
+ if (/(?:[zZ]|[+-]\d{2}:?\d{2})$/u.test(end)) {
439
+ const parsed = Date.parse(end);
440
+ return !Number.isNaN(parsed) && Math.floor(parsed / 1e3) === Math.floor(until.getTime() / 1e3);
441
+ }
442
+ return end.slice(0, 19) === sent.slice(0, 19);
443
+ }
444
+ __name(sameEnd, "sameEnd");
445
+ function ours(list, key, sent, keep = []) {
446
+ const candidates = list.filter((entry) => !keep.includes(entry.id));
447
+ const byKey = candidates.find((entry) => entry.id === key);
448
+ if (byKey || !sent) return byKey;
449
+ return candidates.find(
450
+ (entry) => entry.description === sent.reason && entry.end !== null && sameEnd(entry.end, sent.until, sent.timeZone)
451
+ );
452
+ }
453
+ __name(ours, "ours");
454
+ function wallClock(date, timeZone) {
455
+ const format = new Intl.DateTimeFormat("en-US", {
456
+ timeZone,
457
+ hourCycle: "h23",
458
+ year: "numeric",
459
+ month: "2-digit",
460
+ day: "2-digit",
461
+ hour: "2-digit",
462
+ minute: "2-digit",
463
+ second: "2-digit"
464
+ });
465
+ const clock = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
466
+ for (const part of format.formatToParts(date)) {
467
+ if (part.type in clock) clock[part.type] = Number(part.value);
468
+ }
469
+ return clock;
470
+ }
471
+ __name(wallClock, "wallClock");
472
+ var pad = /* @__PURE__ */ __name((value, width = 2) => String(value).padStart(width, "0"), "pad");
473
+ function ifoodLocalTime(date, timeZone) {
474
+ const local = wallClock(date, timeZone);
475
+ const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);
476
+ const offset = Math.round((asUtc - Math.floor(date.getTime() / 1e3) * 1e3) / 6e4);
477
+ const abs = Math.abs(offset);
478
+ return `${pad(local.year, 4)}-${pad(local.month)}-${pad(local.day)}T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}${offset < 0 ? "-" : "+"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
479
+ }
480
+ __name(ifoodLocalTime, "ifoodLocalTime");
481
+ function createdId(body, sent) {
482
+ try {
483
+ const id = JSON.parse(body).id;
484
+ return typeof id === "string" && id !== "" ? id : sent;
485
+ } catch {
486
+ return sent;
487
+ }
488
+ }
489
+ __name(createdId, "createdId");
490
+ function ifoodPause(ctx, request) {
491
+ return answeredPause(async () => {
492
+ const list = await listInterruptions(ctx, request.merchantId);
493
+ if (!Array.isArray(list)) return list;
494
+ const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
495
+ if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
496
+ const response = await call2(ctx, {
497
+ method: "POST",
498
+ url: interruptionsUrl(request.merchantId),
499
+ json: {
500
+ id: request.key,
501
+ description: request.reason,
502
+ start: ifoodLocalTime(ctx.now, request.timeZone),
503
+ end: ifoodLocalTime(request.until, request.timeZone)
504
+ }
505
+ });
506
+ if (settled(response)) return response;
507
+ const failure = notOk(response);
508
+ if (failure) return failure;
509
+ return { kind: "paused", externalId: createdId(response.body, request.key), until: request.until };
510
+ });
511
+ }
512
+ __name(ifoodPause, "ifoodPause");
513
+ function ifoodResume(ctx, ref) {
514
+ return answered(async () => {
515
+ let id = ref.externalId;
516
+ if (id === null && ref.key !== null) {
517
+ const list = await listInterruptions(ctx, ref.merchantId);
518
+ if (!Array.isArray(list)) return list;
519
+ id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;
520
+ }
521
+ if (id === null) return { kind: "accepted" };
522
+ const response = await call2(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
523
+ if (settled(response)) return response;
524
+ if (response.status === 404) return { kind: "accepted" };
525
+ return outboundResultOf(response);
526
+ });
527
+ }
528
+ __name(ifoodResume, "ifoodResume");
529
+ async function answeredPause(run) {
530
+ try {
531
+ return await run();
532
+ } catch (error) {
533
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
534
+ }
535
+ }
536
+ __name(answeredPause, "answeredPause");
537
+ var IFOOD_AVAILABILITY = {
538
+ kind: "interruption",
539
+ pause: ifoodPause,
540
+ resume: ifoodResume
541
+ };
542
+
386
543
  // src/ifood/index.ts
387
544
  var IFOOD_PROVIDER = "IFOOD";
388
545
  var ITEM_UNAVAILABLE = "503";
@@ -419,6 +576,8 @@ function createIfoodAdapter(config) {
419
576
  catalogue: IFOOD_CATALOGUE,
420
577
  confirm: /* @__PURE__ */ __name((ctx, order) => ifoodConfirm(ctx, order), "confirm"),
421
578
  requestCancellation: ifoodRequestCancellation,
579
+ // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
580
+ availability: IFOOD_AVAILABILITY,
422
581
  // No per-order deep link is known, so the portal, where a live order is
423
582
  // on the first screen.
424
583
  appLink: /* @__PURE__ */ __name(() => IFOOD_PORTAL_URL, "appLink")
@@ -426,6 +585,7 @@ function createIfoodAdapter(config) {
426
585
  }
427
586
  __name(createIfoodAdapter, "createIfoodAdapter");
428
587
  export {
588
+ IFOOD_AVAILABILITY,
429
589
  IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
430
590
  IFOOD_CATALOGUE,
431
591
  IFOOD_PROVIDER,
@@ -433,7 +593,10 @@ export {
433
593
  createIfoodAdapter,
434
594
  ifoodItemBody,
435
595
  ifoodItemId,
596
+ ifoodLocalTime,
597
+ ifoodPause,
436
598
  ifoodProductId,
599
+ ifoodResume,
437
600
  normalizeIfoodEvent,
438
601
  verifyIfoodSignature
439
602
  };