@12-apps/marketplace 1.10.0 → 1.11.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 (71) hide show
  1. package/ADOPTING.md +36 -0
  2. package/README.md +63 -0
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CYJzu1c9.d.ts → adapter-CD0SfdVS.d.ts} +124 -1
  6. package/dist/{chunk-PYHNM47K.js → chunk-DCWOQ5PN.js} +2 -2
  7. package/dist/{chunk-WVZ2IXFH.js → chunk-OS4TSIFU.js} +190 -12
  8. package/dist/chunk-OS4TSIFU.js.map +1 -0
  9. package/dist/chunk-SGOTN5PX.js +345 -0
  10. package/dist/chunk-SGOTN5PX.js.map +1 -0
  11. package/dist/{chunk-HEXLCTOG.js → chunk-TVZU4HNT.js} +1 -1
  12. package/dist/chunk-TVZU4HNT.js.map +1 -0
  13. package/dist/{chunk-2BA2EHNF.js → chunk-YWMEIMO3.js} +206 -22
  14. package/dist/chunk-YWMEIMO3.js.map +1 -0
  15. package/dist/{client-B4EQCRD_.d.ts → client-11sncog4.d.ts} +1 -1
  16. package/dist/{engine-DK3iV_Kk.d.ts → engine-C_3RK8wC.d.ts} +116 -4
  17. package/dist/hono/index.d.ts +2 -2
  18. package/dist/hono/index.js +3 -3
  19. package/dist/ifood/index.d.ts +5 -2
  20. package/dist/ifood/index.js +125 -7
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +23 -4
  23. package/dist/index.js +264 -21
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -2
  26. package/dist/keeta/index.js +2 -2
  27. package/dist/manifest/index.d.ts +219 -1
  28. package/dist/manifest/index.js +1 -1
  29. package/dist/manifest/server.d.ts +2 -2
  30. package/dist/manifest/server.js +3 -3
  31. package/dist/rappi/index.d.ts +1 -1
  32. package/dist/rappi/index.js +1 -1
  33. package/dist/server/en-US.d.ts +13 -0
  34. package/dist/server/en-US.js +13 -0
  35. package/dist/server/en-US.js.map +1 -1
  36. package/dist/server/index.d.ts +241 -7
  37. package/dist/server/index.js +3 -3
  38. package/dist/server/pt-BR.d.ts +13 -0
  39. package/dist/server/pt-BR.js +13 -0
  40. package/dist/server/pt-BR.js.map +1 -1
  41. package/package.json +1 -1
  42. package/prisma/marketplace.prisma +41 -0
  43. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  44. package/src/core/adapter.ts +21 -0
  45. package/src/core/bulk.ts +43 -8
  46. package/src/core/engine.ts +59 -3
  47. package/src/core/integration.ts +60 -32
  48. package/src/core/link-store.ts +170 -0
  49. package/src/core/linking-port.ts +100 -0
  50. package/src/core/linking.ts +363 -0
  51. package/src/core/merchant-claim.ts +106 -0
  52. package/src/core/ports.ts +3 -0
  53. package/src/ifood/index.ts +4 -0
  54. package/src/ifood/linking.ts +170 -0
  55. package/src/ifood/outbound.ts +10 -3
  56. package/src/index.ts +14 -0
  57. package/src/server/copy.ts +20 -2
  58. package/src/server/en-US.ts +13 -0
  59. package/src/server/index.ts +1 -1
  60. package/src/server/link-routes.ts +140 -0
  61. package/src/server/mcp-link.ts +103 -0
  62. package/src/server/mcp.ts +6 -2
  63. package/src/server/pt-BR.ts +13 -0
  64. package/src/server/routes.ts +5 -2
  65. package/src/server/webhook.ts +86 -0
  66. package/dist/chunk-2BA2EHNF.js.map +0 -1
  67. package/dist/chunk-HEXLCTOG.js.map +0 -1
  68. package/dist/chunk-WVZ2IXFH.js.map +0 -1
  69. package/dist/chunk-ZO4S3LF4.js +0 -254
  70. package/dist/chunk-ZO4S3LF4.js.map +0 -1
  71. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import { O as OutboundResult } from './adapter-CYJzu1c9.js';
1
+ import { O as OutboundResult } from './adapter-CD0SfdVS.js';
2
2
 
3
3
  /**
4
4
  * The HTTP half every Open Delivery adapter shares: the token grant and its
@@ -1,4 +1,4 @@
1
- import { Q as MarketplaceDeliveredBy, q as CatalogueItem, p as CatalogueImage, a as NormalizedMarketplaceOrder, N as NormalizedEvent, a3 as StatusStep, T as MarketplaceHttp, c as MarketplaceAdapter, i as MarketplaceProvider, L as MarketplaceCredentials, H as CatalogueWarningCode, W as MarketplaceLifecycle, j as CancellationReason, a0 as OutboundOrderRef, b as CatalogueMenuOptions, w as CatalogueReadResult } from './adapter-CYJzu1c9.js';
1
+ import { Z as MarketplaceDeliveredBy, a3 as MarketplaceLinkAttemptDelegate, s as CatalogueItem, r as CatalogueImage, a as NormalizedMarketplaceOrder, N as NormalizedEvent, ac as StatusStep, $ as MarketplaceHttp, V as MarketplaceAppCredentialsPort, c as MarketplaceAdapter, j as MarketplaceProvider, Y as MarketplaceCredentials, J as CatalogueWarningCode, U as LinkedMerchant, a2 as MarketplaceLifecycle, k as CancellationReason, a9 as OutboundOrderRef, b as CatalogueMenuOptions, y as CatalogueReadResult } from './adapter-CD0SfdVS.js';
2
2
 
3
3
  /** What the engine tells the host about the order a lifecycle event names. */
4
4
  interface MarketplaceLifecycleFacts {
@@ -187,6 +187,7 @@ interface MarketplaceDb {
187
187
  count: number;
188
188
  }>;
189
189
  };
190
+ marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate;
190
191
  }
191
192
  /** One decision as the host's admission sees it, BEFORE the claim commits. */
192
193
  interface MarketplaceAdmissionRequest {
@@ -389,6 +390,7 @@ interface MarketplacePorts {
389
390
  * catalogue. Absent: every catalogue call answers `UNSUPPORTED`.
390
391
  */
391
392
  catalogue?: MarketplaceCataloguePort;
393
+ appCredentials?: MarketplaceAppCredentialsPort;
392
394
  /** The acceptance window a connection gets when it does not state its own. */
393
395
  defaultAckSlaSeconds: number;
394
396
  /** How many stored deliveries one reconciliation pass re-runs. */
@@ -454,6 +456,18 @@ interface ExpirySweepResult {
454
456
  tenants: number;
455
457
  }
456
458
 
459
+ /**
460
+ * A LINKED connection's secrets and tokens (FUT-5613).
461
+ *
462
+ * The sealed `credentials` blob of a linked connection holds the store's
463
+ * refresh token and nothing of the app: the app's client id and secret are
464
+ * the host's configuration (`appCredentials`), read at each use so a rotation
465
+ * there reaches every store at once. The access token lives in the engine's
466
+ * per-process token cache only, like every other marketplace token.
467
+ */
468
+ /** How a connection authenticates. */
469
+ type MarketplaceAuthMode = "CREDENTIALS" | "LINKED";
470
+
457
471
  /**
458
472
  * The (tenant, marketplace) connection repository .
459
473
  *
@@ -488,6 +502,12 @@ interface MarketplaceIntegrationView {
488
502
  lastVerifiedAt: Date | null;
489
503
  /** Archived connections ingest nothing; null while live. */
490
504
  archivedAt: Date | null;
505
+ /**
506
+ * How the connection authenticates (FUT-5613): CREDENTIALS, the store's own
507
+ * app; LINKED, the software's app the store authorized. Always set by this
508
+ * version; optional in the type so a view built by hand against 1.x compiles.
509
+ */
510
+ authMode?: MarketplaceAuthMode;
491
511
  }
492
512
  /** What a save may change. Absent keys leave their column alone. */
493
513
  interface SaveMarketplaceIntegrationInput {
@@ -564,7 +584,9 @@ interface MarketplaceMenuLinkView {
564
584
  * link `(store, provider, externalSku)`.
565
585
  */
566
586
  /** Why a bulk row was refused. Vocabulary, not copy. */
567
- type BulkProblemCode = "DUPLICATE" | "UNKNOWN_PROVIDER" | "NOTHING_TO_UPDATE" | "NOT_FOUND" | "CATALOG_ITEM_NOT_FOUND";
587
+ type BulkProblemCode = "DUPLICATE" | "UNKNOWN_PROVIDER" | "NOTHING_TO_UPDATE" | "NOT_FOUND" | "CATALOG_ITEM_NOT_FOUND"
588
+ /** Another store's live connection holds the merchant id this row sets, or revives (FUT-5613). */
589
+ | "MERCHANT_TAKEN";
568
590
  interface BulkProblem {
569
591
  path: (string | number)[];
570
592
  code: BulkProblemCode;
@@ -998,6 +1020,48 @@ interface IngestSettings {
998
1020
  followStatus?: boolean;
999
1021
  }
1000
1022
 
1023
+ /** Why a linking call did nothing. Vocabulary, not copy: the host words each. */
1024
+ type LinkRefusalCode =
1025
+ /** No app configured for this marketplace, the adapter links nothing, or the host has no link table. */
1026
+ "UNAVAILABLE"
1027
+ /** `finish` with no `start` before it (or after another finish used it). */
1028
+ | "NO_LINK_IN_PROGRESS"
1029
+ /** The portal code's ten minutes are over: start again. */
1030
+ | "LINK_EXPIRED"
1031
+ /** The marketplace refused the authorization code (wrong, used, or for another code). */
1032
+ | "CODE_REFUSED"
1033
+ /** The marketplace refused another call (the code request, the merchant list). */
1034
+ | "MARKETPLACE_REFUSED"
1035
+ /** `selectMerchant` on a connection that is not linked, or is archived. */
1036
+ | "NOT_LINKED"
1037
+ /** The merchant is not one the grant covers. */
1038
+ | "UNKNOWN_MERCHANT"
1039
+ /** Another store's live connection already holds that merchant. */
1040
+ | "MERCHANT_TAKEN";
1041
+ /** A linking call that did nothing: refused for good, or worth trying again. */
1042
+ type LinkFailure = {
1043
+ kind: "refused";
1044
+ code: LinkRefusalCode;
1045
+ status: number | null;
1046
+ message: string | null;
1047
+ } | {
1048
+ kind: "retry";
1049
+ reason: string;
1050
+ };
1051
+ /** A linking in progress, as a person sees it: never the verifier. */
1052
+ interface LinkPendingView {
1053
+ userCode: string;
1054
+ verificationUrl: string;
1055
+ verificationUrlComplete: string;
1056
+ expiresAt: Date;
1057
+ }
1058
+ /** What `finishLink` answers: the connection, and the merchants the grant covers (null when they could not be listed). */
1059
+ interface LinkFinished {
1060
+ kind: "linked";
1061
+ integration: MarketplaceIntegrationView;
1062
+ merchants: LinkedMerchant[] | null;
1063
+ }
1064
+
1001
1065
  /**
1002
1066
  * The outbound job's name and payload — what a decision QUEUES.
1003
1067
  *
@@ -1388,7 +1452,7 @@ interface MarketplaceEngine {
1388
1452
  providers?: readonly string[];
1389
1453
  includeArchived?: boolean;
1390
1454
  }): Promise<MarketplaceIntegrationView[]>;
1391
- /** Create or patch ONE connection (the bulk call's single-row form, with no audit). */
1455
+ /** Create or patch ONE connection (the bulk call's single-row form, with no audit). Throws MarketplaceMerchantTakenError. */
1392
1456
  saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;
1393
1457
  /** Create, patch, archive or unarchive many connections, all-or-nothing. */
1394
1458
  upsertIntegrations(input: {
@@ -1397,6 +1461,54 @@ interface MarketplaceEngine {
1397
1461
  rows: readonly IntegrationRowInput[];
1398
1462
  validateOnly?: boolean;
1399
1463
  }): Promise<BulkResult<MarketplaceIntegrationView>>;
1464
+ /**
1465
+ * Whether this store can link this marketplace through the software's own
1466
+ * app (FUT-5613), and the linking it left in progress. `available` is false
1467
+ * when the adapter links nothing, the host configured no app for it, or the
1468
+ * link table is not composed: the store's own credentials still work.
1469
+ */
1470
+ linkState(input: {
1471
+ clientId: string;
1472
+ provider: MarketplaceProvider;
1473
+ environment?: "SANDBOX" | "PRODUCTION";
1474
+ }): Promise<{
1475
+ available: boolean;
1476
+ pending: LinkPendingView | null;
1477
+ }>;
1478
+ /** Ask for the portal code; the verifier stays sealed server-side. Replaces an earlier attempt. */
1479
+ startLink(input: {
1480
+ clientId: string;
1481
+ provider: MarketplaceProvider;
1482
+ environment?: "SANDBOX" | "PRODUCTION";
1483
+ }): Promise<{
1484
+ kind: "started";
1485
+ pending: LinkPendingView;
1486
+ } | LinkFailure>;
1487
+ /** Exchange the pasted authorization code for the store's tokens; select the merchant when only one. */
1488
+ finishLink(input: {
1489
+ clientId: string;
1490
+ provider: MarketplaceProvider;
1491
+ authorizationCode: string;
1492
+ actorId: string | null;
1493
+ enabled?: boolean;
1494
+ }): Promise<LinkFinished | LinkFailure>;
1495
+ /** The merchants a linked connection's grant covers. */
1496
+ linkedMerchants(input: {
1497
+ clientId: string;
1498
+ provider: MarketplaceProvider;
1499
+ }): Promise<{
1500
+ kind: "listed";
1501
+ merchants: LinkedMerchant[];
1502
+ } | LinkFailure>;
1503
+ /** Choose the marketplace store of a linked connection whose grant covers several. */
1504
+ selectLinkedMerchant(input: {
1505
+ clientId: string;
1506
+ provider: MarketplaceProvider;
1507
+ merchantId: string;
1508
+ }): Promise<{
1509
+ kind: "selected";
1510
+ integration: MarketplaceIntegrationView;
1511
+ } | LinkFailure>;
1400
1512
  /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */
1401
1513
  menuLinks(input: {
1402
1514
  clientId: string;
@@ -1532,4 +1644,4 @@ interface MarketplaceEngine {
1532
1644
  */
1533
1645
  declare function createMarketplaceEngine(config: MarketplaceEngineConfig): MarketplaceEngine;
1534
1646
 
1535
- export { type MarketplaceEngineConfig 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 InformStatusInput as J, type IngestResult as K, type IngestSettings as L, type IngestionTarget as M, type IntegrationRowInput as N, MARKETPLACE_AVAILABILITY_JOB as O, MARKETPLACE_CATALOGUE_JOB as P, MARKETPLACE_FETCH_ORDER_JOB as Q, MARKETPLACE_OUTBOUND_JOB as R, type MarketplaceAdmission as S, type MarketplaceAdmissionRequest as T, type MarketplaceAdmissionResult as U, type MarketplaceAuditEntry as V, type MarketplaceAuditPort as W, type MarketplaceCataloguePort as X, type MarketplaceClockPort as Y, type MarketplaceDb as Z, type MarketplaceEngine as _, type AcceptanceStatus as a, type MarketplaceEnqueuePort as a0, type MarketplaceIntegrationView as a1, type MarketplaceLifecycleAnswer as a2, type MarketplaceLifecycleFacts as a3, type MarketplaceLogger as a4, type MarketplaceMenuLinkView as a5, type MarketplaceOrderPort as a6, type MarketplaceOrderState as a7, type MarketplaceOrderSummary as a8, type MarketplacePorts as a9, createMarketplaceEngine as aA, outboundDedupeKey as aB, type MarketplaceRefusal as aa, type MarketplaceSecretsPort as ab, type MenuLinkRowInput as ac, OUTBOUND_GIVE_UP_MS as ad, OUTBOUND_STALE_MS as ae, type OutboundAction as af, type OutboundAttempt as ag, type OutboundJobPayload as ah, type OutboundOutcome as ai, OutboundRetryError as aj, type OutboundSweepResult as ak, type PauseOutcome as al, type PauseStoreInput as am, type PauseStoreResult as an, type PendingAcceptance as ao, type PendingInboxEvent as ap, type ResolvedOrderLine as aq, type ResumeOutcome as ar, STORE_PAUSE_LEASE_MS as as, type SaveMarketplaceIntegrationInput as at, type StoreAvailabilityView as au, type StorePauseFailureCode as av, type StorePauseState as aw, type StorePauseWanted as ax, availabilityDedupeKey as ay, catalogueDedupeKey as az, 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 };
1647
+ export { type MarketplaceAuthMode 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 InformStatusInput as J, type IngestResult as K, type IngestSettings as L, type IngestionTarget as M, type IntegrationRowInput as N, type LinkFailure as O, type LinkFinished as P, type LinkPendingView as Q, type LinkRefusalCode as R, MARKETPLACE_AVAILABILITY_JOB as S, MARKETPLACE_CATALOGUE_JOB as T, MARKETPLACE_FETCH_ORDER_JOB as U, MARKETPLACE_OUTBOUND_JOB as V, type MarketplaceAdmission as W, type MarketplaceAdmissionRequest as X, type MarketplaceAdmissionResult as Y, type MarketplaceAuditEntry as Z, type MarketplaceAuditPort as _, type AcceptanceStatus as a, type MarketplaceCataloguePort as a0, type MarketplaceClockPort as a1, type MarketplaceDb as a2, type MarketplaceEngine as a3, type MarketplaceEngineConfig as a4, type MarketplaceEnqueuePort as a5, type MarketplaceIntegrationView as a6, type MarketplaceLifecycleAnswer as a7, type MarketplaceLifecycleFacts as a8, type MarketplaceLogger as a9, type StorePauseFailureCode as aA, type StorePauseState as aB, type StorePauseWanted as aC, availabilityDedupeKey as aD, catalogueDedupeKey as aE, createMarketplaceEngine as aF, outboundDedupeKey as aG, type MarketplaceMenuLinkView as aa, type MarketplaceOrderPort as ab, type MarketplaceOrderState as ac, type MarketplaceOrderSummary as ad, type MarketplacePorts as ae, type MarketplaceRefusal as af, type MarketplaceSecretsPort as ag, type MenuLinkRowInput as ah, OUTBOUND_GIVE_UP_MS as ai, OUTBOUND_STALE_MS as aj, type OutboundAction as ak, type OutboundAttempt as al, type OutboundJobPayload as am, type OutboundOutcome as an, OutboundRetryError as ao, type OutboundSweepResult as ap, type PauseOutcome as aq, type PauseStoreInput as ar, type PauseStoreResult as as, type PendingAcceptance as at, type PendingInboxEvent as au, type ResolvedOrderLine as av, type ResumeOutcome as aw, STORE_PAUSE_LEASE_MS as ax, type SaveMarketplaceIntegrationInput as ay, type StoreAvailabilityView as az, 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-DK3iV_Kk.js';
4
- import '../adapter-CYJzu1c9.js';
3
+ import '../engine-C_3RK8wC.js';
4
+ import '../adapter-CD0SfdVS.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-WVZ2IXFH.js";
4
- import "../chunk-ZO4S3LF4.js";
5
- import "../chunk-2BA2EHNF.js";
3
+ } from "../chunk-OS4TSIFU.js";
4
+ import "../chunk-SGOTN5PX.js";
5
+ import "../chunk-YWMEIMO3.js";
6
6
  import {
7
7
  __name
8
8
  } from "../chunk-7QVYU63E.js";
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, g as StorePauseResult, h as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CYJzu1c9.js';
1
+ import { N as NormalizedEvent, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, g as MarketplaceLinking, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, h as StorePauseResult, i as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CD0SfdVS.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -53,6 +53,9 @@ declare const IFOOD_CATALOGUE: PushCatalogue;
53
53
  /** iFood's catalogue read. */
54
54
  declare const IFOOD_CATALOGUE_READER: CatalogueReader;
55
55
 
56
+ /** The iFood adapter's linking half. */
57
+ declare const IFOOD_LINKING: MarketplaceLinking;
58
+
56
59
  /**
57
60
  * iFood's catalogue answer mapped into the engine's {@link CatalogueSnapshotItem}
58
61
  * (FUT-951). Pure and offline: `./catalogue-read.ts` makes the calls.
@@ -118,4 +121,4 @@ interface IfoodAdapterConfig {
118
121
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
119
122
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
120
123
 
121
- export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_IMAGE_BASE_URL, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };
124
+ export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_IMAGE_BASE_URL, IFOOD_LINKING, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, verifyIfoodSignature };
@@ -17,7 +17,7 @@ import {
17
17
  answered,
18
18
  outboundResultOf,
19
19
  tokenGrantResultOf
20
- } from "../chunk-HEXLCTOG.js";
20
+ } from "../chunk-TVZU4HNT.js";
21
21
  import {
22
22
  __name
23
23
  } from "../chunk-7QVYU63E.js";
@@ -44,7 +44,7 @@ var TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
44
44
  var orderUrl = /* @__PURE__ */ __name((externalOrderId, action) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`, "orderUrl");
45
45
  var IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
46
46
  var TOKEN_MARGIN_MS = 6e4;
47
- var ifoodTokenKey = /* @__PURE__ */ __name((ctx) => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`, "ifoodTokenKey");
47
+ var ifoodTokenKey = /* @__PURE__ */ __name((ctx) => ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`, "ifoodTokenKey");
48
48
  function tokenOf(body) {
49
49
  try {
50
50
  const parsed = JSON.parse(body);
@@ -57,6 +57,7 @@ function tokenOf(body) {
57
57
  }
58
58
  __name(tokenOf, "tokenOf");
59
59
  async function bearer(ctx) {
60
+ if (ctx.grant) return ctx.grant.accessToken();
60
61
  const key = ifoodTokenKey(ctx);
61
62
  const cached = ctx.tokens.get(key);
62
63
  if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
@@ -557,6 +558,120 @@ var IFOOD_CATALOGUE_READER = {
557
558
  }, "read")
558
559
  };
559
560
 
561
+ // src/ifood/linking.ts
562
+ var USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
563
+ var TOKEN_URL2 = `${IFOOD_API}/authentication/v1.0/oauth/token`;
564
+ var MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
565
+ var USER_CODE_SECONDS = 600;
566
+ var ACCESS_TOKEN_SECONDS = 21600;
567
+ var MERCHANT_PAGE_SIZE = 100;
568
+ var MAX_MERCHANT_PAGES = 20;
569
+ var FORM = { "Content-Type": "application/x-www-form-urlencoded" };
570
+ function json(body) {
571
+ try {
572
+ return body === "" ? null : JSON.parse(body);
573
+ } catch {
574
+ return null;
575
+ }
576
+ }
577
+ __name(json, "json");
578
+ async function call2(ctx, request, read2) {
579
+ try {
580
+ const response = await ctx.http(request);
581
+ const result = outboundResultOf(response);
582
+ if (result.kind !== "accepted") return result;
583
+ const value = read2(json(response.body));
584
+ return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
585
+ } catch (error) {
586
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
587
+ }
588
+ }
589
+ __name(call2, "call");
590
+ var positive = /* @__PURE__ */ __name((value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback, "positive");
591
+ function codeOf(body) {
592
+ const userCode = asString(pick(body, "userCode"));
593
+ const verifier = asString(pick(body, "authorizationCodeVerifier"));
594
+ const verificationUrl = asString(pick(body, "verificationUrl"));
595
+ if (!userCode || !verifier || !verificationUrl) return null;
596
+ return {
597
+ userCode,
598
+ verifier,
599
+ verificationUrl,
600
+ verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
601
+ expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS)
602
+ };
603
+ }
604
+ __name(codeOf, "codeOf");
605
+ function grantOf(body, requireRefresh) {
606
+ const accessToken = asString(pick(body, "accessToken"));
607
+ const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
608
+ if (!accessToken || requireRefresh && !refreshToken) return null;
609
+ return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
610
+ }
611
+ __name(grantOf, "grantOf");
612
+ function merchantsOf(body) {
613
+ if (!Array.isArray(body)) return null;
614
+ return body.flatMap((raw) => {
615
+ const id = asString(pick(raw, "id"));
616
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
617
+ });
618
+ }
619
+ __name(merchantsOf, "merchantsOf");
620
+ var tokenRequest = /* @__PURE__ */ __name((fields) => ({
621
+ method: "POST",
622
+ url: TOKEN_URL2,
623
+ headers: FORM,
624
+ body: new URLSearchParams(fields).toString()
625
+ }), "tokenRequest");
626
+ async function listMerchants(ctx, accessToken) {
627
+ const all = [];
628
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
629
+ const answer = await call2(
630
+ ctx,
631
+ {
632
+ method: "GET",
633
+ url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
634
+ headers: { Authorization: `Bearer ${accessToken}` }
635
+ },
636
+ merchantsOf
637
+ );
638
+ if (answer.kind !== "ok") return answer;
639
+ all.push(...answer.value);
640
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
641
+ }
642
+ return { kind: "ok", value: all };
643
+ }
644
+ __name(listMerchants, "listMerchants");
645
+ var IFOOD_LINKING = {
646
+ requestCode: /* @__PURE__ */ __name((ctx) => call2(
647
+ ctx,
648
+ { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
649
+ codeOf
650
+ ), "requestCode"),
651
+ exchange: /* @__PURE__ */ __name((ctx, input) => call2(
652
+ ctx,
653
+ tokenRequest({
654
+ grantType: "authorization_code",
655
+ clientId: ctx.credentials.clientId,
656
+ clientSecret: ctx.credentials.clientSecret,
657
+ authorizationCode: input.authorizationCode,
658
+ authorizationCodeVerifier: input.verifier
659
+ }),
660
+ (body) => grantOf(body, true)
661
+ ), "exchange"),
662
+ refresh: /* @__PURE__ */ __name((ctx, input) => call2(
663
+ ctx,
664
+ tokenRequest({
665
+ grantType: "refresh_token",
666
+ clientId: ctx.credentials.clientId,
667
+ clientSecret: ctx.credentials.clientSecret,
668
+ refreshToken: input.refreshToken
669
+ }),
670
+ (body) => grantOf(body, false)
671
+ ), "refresh"),
672
+ merchants: /* @__PURE__ */ __name((ctx, input) => listMerchants(ctx, input.accessToken), "merchants")
673
+ };
674
+
560
675
  // src/ifood/normalize.ts
561
676
  var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
562
677
  var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
@@ -712,7 +827,7 @@ __name(normalizeIfoodEvent, "normalizeIfoodEvent");
712
827
 
713
828
  // src/ifood/pause.ts
714
829
  var interruptionsUrl = /* @__PURE__ */ __name((merchantId) => `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`, "interruptionsUrl");
715
- async function call2(ctx, request) {
830
+ async function call3(ctx, request) {
716
831
  const auth = await bearer(ctx);
717
832
  if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
718
833
  const response = await ctx.http({
@@ -728,7 +843,7 @@ async function call2(ctx, request) {
728
843
  ctx.tokens.delete(ifoodTokenKey(ctx));
729
844
  return { kind: "retry", reason: "iFood refused the token" };
730
845
  }
731
- __name(call2, "call");
846
+ __name(call3, "call");
732
847
  var settled = /* @__PURE__ */ __name((value) => "kind" in value, "settled");
733
848
  function notOk(response) {
734
849
  const result = outboundResultOf(response);
@@ -736,7 +851,7 @@ function notOk(response) {
736
851
  }
737
852
  __name(notOk, "notOk");
738
853
  async function listInterruptions(ctx, merchantId) {
739
- const response = await call2(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
854
+ const response = await call3(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
740
855
  if (settled(response)) return response;
741
856
  const failure = notOk(response);
742
857
  if (failure) return failure;
@@ -820,7 +935,7 @@ function ifoodPause(ctx, request) {
820
935
  if (!Array.isArray(list2)) return list2;
821
936
  const landed = ours(list2, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
822
937
  if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
823
- const response = await call2(ctx, {
938
+ const response = await call3(ctx, {
824
939
  method: "POST",
825
940
  url: interruptionsUrl(request.merchantId),
826
941
  json: {
@@ -846,7 +961,7 @@ function ifoodResume(ctx, ref) {
846
961
  id = ours(list2, ref.key, ref.sent, ref.keep)?.id ?? null;
847
962
  }
848
963
  if (id === null) return { kind: "accepted" };
849
- const response = await call2(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
964
+ const response = await call3(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
850
965
  if (settled(response)) return response;
851
966
  if (response.status === 404) return { kind: "accepted" };
852
967
  return outboundResultOf(response);
@@ -913,6 +1028,8 @@ function createIfoodAdapter(config) {
913
1028
  informStatus: ifoodInformStatus,
914
1029
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
915
1030
  availability: IFOOD_AVAILABILITY,
1031
+ // The distributed-app authorization: a store links the software's own app (FUT-5613).
1032
+ linking: IFOOD_LINKING,
916
1033
  // No per-order deep link is known, so the portal, where a live order is
917
1034
  // on the first screen.
918
1035
  appLink: /* @__PURE__ */ __name(() => IFOOD_PORTAL_URL, "appLink")
@@ -925,6 +1042,7 @@ export {
925
1042
  IFOOD_CATALOGUE,
926
1043
  IFOOD_CATALOGUE_READER,
927
1044
  IFOOD_IMAGE_BASE_URL,
1045
+ IFOOD_LINKING,
928
1046
  IFOOD_PROVIDER,
929
1047
  IFOOD_REASON_CODES,
930
1048
  createIfoodAdapter,