@12-apps/marketplace 1.9.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 (75) hide show
  1. package/ADOPTING.md +63 -1
  2. package/README.md +64 -1
  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-6N2HEV3U.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-BMCERPQX.js → chunk-YWMEIMO3.js} +221 -27
  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-wmW-VuBL.d.ts → engine-C_3RK8wC.d.ts} +207 -64
  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 +280 -26
  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 +223 -2
  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 +246 -8
  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 +47 -0
  43. package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
  44. package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
  45. package/src/core/adapter.ts +21 -0
  46. package/src/core/bulk.ts +77 -15
  47. package/src/core/engine.ts +59 -3
  48. package/src/core/ingest.ts +2 -1
  49. package/src/core/integration.ts +60 -32
  50. package/src/core/link-store.ts +170 -0
  51. package/src/core/linking-port.ts +100 -0
  52. package/src/core/linking.ts +363 -0
  53. package/src/core/menu-links.ts +36 -6
  54. package/src/core/merchant-claim.ts +106 -0
  55. package/src/core/order-types.ts +74 -0
  56. package/src/core/ports.ts +26 -65
  57. package/src/ifood/index.ts +4 -0
  58. package/src/ifood/linking.ts +170 -0
  59. package/src/ifood/outbound.ts +10 -3
  60. package/src/index.ts +14 -0
  61. package/src/server/copy.ts +20 -2
  62. package/src/server/en-US.ts +13 -0
  63. package/src/server/index.ts +1 -1
  64. package/src/server/link-routes.ts +140 -0
  65. package/src/server/mcp-link.ts +103 -0
  66. package/src/server/mcp.ts +13 -4
  67. package/src/server/pt-BR.ts +13 -0
  68. package/src/server/routes.ts +5 -2
  69. package/src/server/webhook.ts +86 -0
  70. package/dist/chunk-6N2HEV3U.js.map +0 -1
  71. package/dist/chunk-BMCERPQX.js.map +0 -1
  72. package/dist/chunk-HEXLCTOG.js.map +0 -1
  73. package/dist/chunk-NP4EYKPO.js +0 -252
  74. package/dist/chunk-NP4EYKPO.js.map +0 -1
  75. /package/dist/{chunk-PYHNM47K.js.map → chunk-DCWOQ5PN.js.map} +0 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The order-side vocabulary the host's order port speaks: what a resolved line
3
+ * is, what the queue shows, what a person stated, and why an order or a
4
+ * cancellation ended. Plain data with no engine dependency; `./ports`
5
+ * re-exports every name, so a host imports them from there as before.
6
+ */
7
+
8
+ /**
9
+ * One order line after the engine has matched it against the SKU map.
10
+ * `subjectRef` is the host catalog id, or null when the SKU was never mapped —
11
+ * never an error, and never a reason to refuse the order. `variationRef` is
12
+ * the variation of `subjectRef` the SKU was mapped to (FUT-4927), or null for
13
+ * the item alone and for every unmapped line.
14
+ */
15
+ export interface ResolvedOrderLine {
16
+ externalSku: string;
17
+ name: string;
18
+ quantity: number;
19
+ unitPriceCents: number;
20
+ note: string | null;
21
+ subjectRef: string | null;
22
+ variationRef: string | null;
23
+ }
24
+
25
+ /** What the acceptance queue shows about an order, resolved by the host. */
26
+ export interface MarketplaceOrderSummary {
27
+ buyerName: string | null;
28
+ totalCents: number;
29
+ unmappedLines: number;
30
+ createdAt: string | null;
31
+ }
32
+
33
+ /**
34
+ * What a person stated beside an accept, for the host's admission to read.
35
+ * Every field is optional and the host decides what it means.
36
+ */
37
+ export interface MarketplaceAdmission {
38
+ /** "Accept anyway": the person was told the order is short and confirmed. */
39
+ admitStockPastZero?: boolean;
40
+ }
41
+
42
+ /** The host's answer: proceed, or refuse with its own coded reason. */
43
+ export type MarketplaceAdmissionResult =
44
+ | { admitted: true }
45
+ | {
46
+ admitted: false;
47
+ /** The host's machine code (`MARKETPLACE_STOCK_ASK`). The route answers 409 with it. */
48
+ code: string;
49
+ /** The host's sentence, in the caller's language. */
50
+ message: string;
51
+ /** Anything the client needs to ask the person (the short lines). */
52
+ details?: unknown;
53
+ };
54
+
55
+ /** Why the engine tells the host to refuse an order. Vocabulary, not copy. */
56
+ export type MarketplaceRefusal = "REJECTED" | "EXPIRED" | "CANCELLED";
57
+
58
+ /**
59
+ * Why the store's own cancellation request FAILED. Vocabulary, not copy.
60
+ *
61
+ * - `REFUSED`: the marketplace judged the request and denied it: its denial
62
+ * event, an answer that is its business refusal, or an adapter that has no
63
+ * cancellation API to call. An adapter that cannot tell a business 4xx from
64
+ * a malformed request (iFood, Rappi) reports every final 4xx as REFUSED.
65
+ * - `UNREACHABLE`: our own request never got a judgement: no credentials or
66
+ * ones that do not open, a token the marketplace did not grant, a request
67
+ * the marketplace calls malformed (99Food's 400), or every attempt failed
68
+ * on the network or a 5xx. Retrying, or fixing the connection, can help.
69
+ * - `TIMEOUT`: no answer inside the marketplace's cancellation window.
70
+ *
71
+ * A host written before `UNREACHABLE` existed treats an unknown value as it
72
+ * treats REFUSED: the order stays and a person finishes in the marketplace's app.
73
+ */
74
+ export type CancellationFailureReason = "REFUSED" | "UNREACHABLE" | "TIMEOUT";
package/src/core/ports.ts CHANGED
@@ -2,9 +2,26 @@ import type { AdapterRegistry } from "./registry";
2
2
  import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
3
3
  import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
4
4
  import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
+ import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
6
+ import type {
7
+ CancellationFailureReason,
8
+ MarketplaceAdmission,
9
+ MarketplaceAdmissionResult,
10
+ MarketplaceOrderSummary,
11
+ MarketplaceRefusal,
12
+ ResolvedOrderLine,
13
+ } from "./order-types";
5
14
  import type { NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
6
15
 
7
16
  export type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
17
+ export type {
18
+ CancellationFailureReason,
19
+ MarketplaceAdmission,
20
+ MarketplaceAdmissionResult,
21
+ MarketplaceOrderSummary,
22
+ MarketplaceRefusal,
23
+ ResolvedOrderLine,
24
+ } from "./order-types";
8
25
 
9
26
  /**
10
27
  * What the engine needs FROM its host, and nothing more.
@@ -94,37 +111,7 @@ export interface MarketplaceDb {
94
111
  create(args: unknown): Promise<unknown>;
95
112
  updateMany(args: unknown): Promise<{ count: number }>;
96
113
  };
97
- }
98
-
99
- /**
100
- * One order line after the engine has matched it against the SKU map.
101
- * `subjectRef` is the host catalog id, or null when the SKU was never mapped —
102
- * never an error, and never a reason to refuse the order.
103
- */
104
- export interface ResolvedOrderLine {
105
- externalSku: string;
106
- name: string;
107
- quantity: number;
108
- unitPriceCents: number;
109
- note: string | null;
110
- subjectRef: string | null;
111
- }
112
-
113
- /** What the acceptance queue shows about an order, resolved by the host. */
114
- export interface MarketplaceOrderSummary {
115
- buyerName: string | null;
116
- totalCents: number;
117
- unmappedLines: number;
118
- createdAt: string | null;
119
- }
120
-
121
- /**
122
- * What a person stated beside an accept, for the host's admission to read.
123
- * Every field is optional and the host decides what it means.
124
- */
125
- export interface MarketplaceAdmission {
126
- /** "Accept anyway": the person was told the order is short and confirmed. */
127
- admitStockPastZero?: boolean;
114
+ marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate; // OPTIONAL, as above; absent: no linking (FUT-5613).
128
115
  }
129
116
 
130
117
  /** One decision as the host's admission sees it, BEFORE the claim commits. */
@@ -142,40 +129,6 @@ export interface MarketplaceAdmissionRequest {
142
129
  db: MarketplaceDb;
143
130
  }
144
131
 
145
- /** The host's answer: proceed, or refuse with its own coded reason. */
146
- export type MarketplaceAdmissionResult =
147
- | { admitted: true }
148
- | {
149
- admitted: false;
150
- /** The host's machine code (`MARKETPLACE_STOCK_ASK`). The route answers 409 with it. */
151
- code: string;
152
- /** The host's sentence, in the caller's language. */
153
- message: string;
154
- /** Anything the client needs to ask the person (the short lines). */
155
- details?: unknown;
156
- };
157
-
158
- /** Why the engine tells the host to refuse an order. Vocabulary, not copy. */
159
- export type MarketplaceRefusal = "REJECTED" | "EXPIRED" | "CANCELLED";
160
-
161
- /**
162
- * Why the store's own cancellation request FAILED. Vocabulary, not copy.
163
- *
164
- * - `REFUSED`: the marketplace judged the request and denied it: its denial
165
- * event, an answer that is its business refusal, or an adapter that has no
166
- * cancellation API to call. An adapter that cannot tell a business 4xx from
167
- * a malformed request (iFood, Rappi) reports every final 4xx as REFUSED.
168
- * - `UNREACHABLE`: our own request never got a judgement: no credentials or
169
- * ones that do not open, a token the marketplace did not grant, a request
170
- * the marketplace calls malformed (99Food's 400), or every attempt failed
171
- * on the network or a 5xx. Retrying, or fixing the connection, can help.
172
- * - `TIMEOUT`: no answer inside the marketplace's cancellation window.
173
- *
174
- * A host written before `UNREACHABLE` existed treats an unknown value as it
175
- * treats REFUSED: the order stays and a person finishes in the marketplace's app.
176
- */
177
- export type CancellationFailureReason = "REFUSED" | "UNREACHABLE" | "TIMEOUT";
178
-
179
132
  /**
180
133
  * The host's domain, as five questions the engine asks and never answers.
181
134
  *
@@ -207,6 +160,13 @@ export interface MarketplaceOrderPort {
207
160
  ): Promise<string>;
208
161
  /** Does this catalog id exist and belong to this tenant? */
209
162
  catalogHas(clientId: string, subjectRef: string): Promise<boolean>;
163
+ /**
164
+ * OPTIONAL. Is `variationRef` a variation of the catalog id `subjectRef`,
165
+ * and this tenant's? Asked before a SKU is mapped to a variation (FUT-4927);
166
+ * `subjectRef` has already passed `catalogHas`. Absent: a mapping that names
167
+ * a variation is refused, and mapping to the item alone works as before.
168
+ */
169
+ catalogHasVariation?(clientId: string, subjectRef: string, variationRef: string): Promise<boolean>;
210
170
  /** The store said yes, or the connection auto-accepts. */
211
171
  onAccepted(clientId: string, orderId: string): Promise<void>;
212
172
  /**
@@ -375,6 +335,7 @@ export interface MarketplacePorts {
375
335
  * catalogue. Absent: every catalogue call answers `UNSUPPORTED`.
376
336
  */
377
337
  catalogue?: MarketplaceCataloguePort;
338
+ appCredentials?: MarketplaceAppCredentialsPort; // OPTIONAL. The software's own app, to link a store (FUT-5613).
378
339
  /** The acceptance window a connection gets when it does not state its own. */
379
340
  defaultAckSlaSeconds: number;
380
341
  /** How many stored deliveries one reconciliation pass re-runs. */
@@ -2,6 +2,7 @@ import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
2
  import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
+ import { IFOOD_LINKING } from "./linking";
5
6
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
6
7
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
7
8
  import { IFOOD_AVAILABILITY } from "./pause";
@@ -79,6 +80,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
79
80
  informStatus: ifoodInformStatus,
80
81
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
81
82
  availability: IFOOD_AVAILABILITY,
83
+ // The distributed-app authorization: a store links the software's own app (FUT-5613).
84
+ linking: IFOOD_LINKING,
82
85
  // No per-order deep link is known, so the portal, where a live order is
83
86
  // on the first screen.
84
87
  appLink: () => IFOOD_PORTAL_URL,
@@ -89,5 +92,6 @@ export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
89
92
  export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
90
93
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
91
94
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
95
+ export { IFOOD_LINKING } from "./linking";
92
96
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
93
97
  export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
@@ -0,0 +1,170 @@
1
+ import { outboundResultOf, type MarketplaceHttpRequest } from "../core/adapter";
2
+ import type { LinkCallContext, LinkCode, LinkGrant, LinkResult, LinkedMerchant, MarketplaceLinking } from "../core/linking-port";
3
+ import { asString, pick } from "../core/payload-read";
4
+ import { IFOOD_API } from "./outbound";
5
+
6
+ /**
7
+ * iFood's DISTRIBUTED-APP authentication, the wire format only (FUT-5613).
8
+ * Read 2026-11-26 off iFood's own pages, served as Markdown at
9
+ * https://developer.ifood.com.br/pt-BR/docs/guides/modules/authentication/distributed.md
10
+ * and .../merchant/endpoints.md:
11
+ *
12
+ * - `POST /authentication/v1.0/oauth/userCode`, form `clientId` → 200
13
+ * `{ userCode, authorizationCodeVerifier, verificationUrl,
14
+ * verificationUrlComplete, expiresIn }` ("valid for 10 minutes", 600).
15
+ * - `POST /authentication/v1.0/oauth/token`, form `grantType=authorization_code`,
16
+ * `clientId`, `clientSecret`, `authorizationCode`, `authorizationCodeVerifier`
17
+ * → 200 `{ accessToken, type: "bearer", expiresIn }` (6 hours by default)
18
+ * and a refresh token ("returns an access token and a refresh token").
19
+ * - The same URL, `grantType=refresh_token`, `clientId`, `clientSecret`,
20
+ * `refreshToken`.
21
+ * - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200
22
+ * `[{ id, name, corporateName }]`: every store the token covers.
23
+ *
24
+ * ESTIMATED, not settled by those pages:
25
+ * - the refresh token's FIELD name in the token answer: the page's table
26
+ * lists only `accessToken`, `type`, `expiresIn`; `refreshToken` (the name
27
+ * the request takes) is read, and the snake-case twin as a fallback;
28
+ * - whether a refresh ROTATES the refresh token: a new one is stored when
29
+ * answered, the old one kept when not;
30
+ * - the refresh token's own lifetime (unstated: "if the refreshToken
31
+ * expires, the user must authorize again"): a refused refresh marks the
32
+ * connection FAILED for the store to link again;
33
+ * - the status of a wrong or used authorization code: any final 4xx is
34
+ * `refused`.
35
+ */
36
+
37
+ const USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
38
+ const TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
39
+ const MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
40
+
41
+ /** iFood's documented lifetime of a user code, used when the answer states none. */
42
+ const USER_CODE_SECONDS = 600;
43
+ /** iFood's documented default lifetime of an access token: 6 hours. */
44
+ const ACCESS_TOKEN_SECONDS = 21_600;
45
+ /** One page of the merchant list; iFood's documented default. */
46
+ const MERCHANT_PAGE_SIZE = 100;
47
+ /** A ceiling on pages read, so a misbehaving answer cannot loop. */
48
+ const MAX_MERCHANT_PAGES = 20;
49
+
50
+ const FORM = { "Content-Type": "application/x-www-form-urlencoded" };
51
+
52
+ function json(body: string): unknown {
53
+ try {
54
+ return body === "" ? null : (JSON.parse(body) as unknown);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /** One call whose 2xx body `read` turns into the value; anything else ends it. */
61
+ async function call<T>(
62
+ ctx: LinkCallContext,
63
+ request: MarketplaceHttpRequest,
64
+ read: (body: unknown) => T | null,
65
+ ): Promise<LinkResult<T>> {
66
+ try {
67
+ const response = await ctx.http(request);
68
+ const result = outboundResultOf(response);
69
+ if (result.kind !== "accepted") return result;
70
+ const value = read(json(response.body));
71
+ return value === null
72
+ ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" }
73
+ : { kind: "ok", value };
74
+ } catch (error) {
75
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
76
+ }
77
+ }
78
+
79
+ const positive = (value: unknown, fallback: number): number =>
80
+ typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
81
+
82
+ function codeOf(body: unknown): LinkCode | null {
83
+ const userCode = asString(pick(body, "userCode"));
84
+ const verifier = asString(pick(body, "authorizationCodeVerifier"));
85
+ const verificationUrl = asString(pick(body, "verificationUrl"));
86
+ if (!userCode || !verifier || !verificationUrl) return null;
87
+ return {
88
+ userCode,
89
+ verifier,
90
+ verificationUrl,
91
+ verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
92
+ expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS),
93
+ };
94
+ }
95
+
96
+ function grantOf(body: unknown, requireRefresh: boolean): LinkGrant | null {
97
+ const accessToken = asString(pick(body, "accessToken"));
98
+ const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
99
+ if (!accessToken || (requireRefresh && !refreshToken)) return null;
100
+ return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
101
+ }
102
+
103
+ function merchantsOf(body: unknown): LinkedMerchant[] | null {
104
+ if (!Array.isArray(body)) return null;
105
+ return body.flatMap((raw: unknown) => {
106
+ const id = asString(pick(raw, "id"));
107
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
108
+ });
109
+ }
110
+
111
+ const tokenRequest = (fields: Record<string, string>): MarketplaceHttpRequest => ({
112
+ method: "POST",
113
+ url: TOKEN_URL,
114
+ headers: FORM,
115
+ body: new URLSearchParams(fields).toString(),
116
+ });
117
+
118
+ /** Every merchant the token covers, page by page until a short page. */
119
+ async function listMerchants(ctx: LinkCallContext, accessToken: string): Promise<LinkResult<LinkedMerchant[]>> {
120
+ const all: LinkedMerchant[] = [];
121
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
122
+ const answer = await call(
123
+ ctx,
124
+ {
125
+ method: "GET",
126
+ url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
127
+ headers: { Authorization: `Bearer ${accessToken}` },
128
+ },
129
+ merchantsOf,
130
+ );
131
+ if (answer.kind !== "ok") return answer;
132
+ all.push(...answer.value);
133
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
134
+ }
135
+ return { kind: "ok", value: all };
136
+ }
137
+
138
+ /** The iFood adapter's linking half. */
139
+ export const IFOOD_LINKING: MarketplaceLinking = {
140
+ requestCode: (ctx) =>
141
+ call(
142
+ ctx,
143
+ { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
144
+ codeOf,
145
+ ),
146
+ exchange: (ctx, input) =>
147
+ call(
148
+ ctx,
149
+ tokenRequest({
150
+ grantType: "authorization_code",
151
+ clientId: ctx.credentials.clientId,
152
+ clientSecret: ctx.credentials.clientSecret,
153
+ authorizationCode: input.authorizationCode,
154
+ authorizationCodeVerifier: input.verifier,
155
+ }),
156
+ (body) => grantOf(body, true),
157
+ ),
158
+ refresh: (ctx, input) =>
159
+ call(
160
+ ctx,
161
+ tokenRequest({
162
+ grantType: "refresh_token",
163
+ clientId: ctx.credentials.clientId,
164
+ clientSecret: ctx.credentials.clientSecret,
165
+ refreshToken: input.refreshToken,
166
+ }),
167
+ (body) => grantOf(body, false),
168
+ ),
169
+ merchants: (ctx, input) => listMerchants(ctx, input.accessToken),
170
+ };
@@ -38,8 +38,13 @@ export const IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
38
38
  /** A token is renewed this long before iFood says it expires. */
39
39
  const TOKEN_MARGIN_MS = 60_000;
40
40
 
41
- /** The token cache key: per environment and merchant app. */
42
- export const ifoodTokenKey = (ctx: AdapterCallContext): string => `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
41
+ /**
42
+ * The token cache key: per environment and merchant app, or, for a store
43
+ * linked through the software's app (FUT-5613), the store's own grant key, so
44
+ * deleting it after a 401 forgets that store's token and nobody else's.
45
+ */
46
+ export const ifoodTokenKey = (ctx: AdapterCallContext): string =>
47
+ ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`;
43
48
 
44
49
  /** iFood's OAuth answer, read defensively: a missing field is "no token". */
45
50
  function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
@@ -55,10 +60,12 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
55
60
 
56
61
  /**
57
62
  * A bearer token for this merchant app, from the per-process cache or a fresh
58
- * client-credentials grant. Keyed by the app's client id, so two stores with
63
+ * client-credentials grant (or, linked, the store's grant). Keyed by the app's client id, so two stores with
59
64
  * two apps never share one. The token lives in memory only.
60
65
  */
61
66
  export async function bearer(ctx: AdapterCallContext): Promise<{ token: string } | OutboundResult> {
67
+ // A linked store: its refresh token buys the token, never a client-credentials grant.
68
+ if (ctx.grant) return ctx.grant.accessToken();
62
69
  const key = ifoodTokenKey(ctx);
63
70
  const cached = ctx.tokens.get(key);
64
71
  if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
package/src/index.ts CHANGED
@@ -28,6 +28,7 @@ export {
28
28
  outboundResultOf,
29
29
  tokenGrantResultOf,
30
30
  type AdapterCallContext,
31
+ type AdapterGrant,
31
32
  type AdapterTokenCache,
32
33
  type CancellationReason,
33
34
  type CancellationRequestInput,
@@ -120,6 +121,7 @@ export type {
120
121
  MarketplaceIntegrationView,
121
122
  SaveMarketplaceIntegrationInput,
122
123
  } from "./core/integration";
124
+ export { MarketplaceMerchantTakenError } from "./core/merchant-claim";
123
125
  export type { MarketplaceMenuLinkView } from "./core/menu-links";
124
126
  export {
125
127
  OutboundRetryError,
@@ -218,3 +220,15 @@ export {
218
220
  type StorePauseWanted,
219
221
  } from "./core/pause-store";
220
222
  export type { AvailabilitySweepResult } from "./core/pause-sweep";
223
+ export type {
224
+ LinkCallContext,
225
+ LinkCode,
226
+ LinkGrant,
227
+ LinkResult,
228
+ LinkedMerchant,
229
+ MarketplaceAppCredentialsPort,
230
+ MarketplaceLinkAttemptDelegate,
231
+ MarketplaceLinking,
232
+ } from "./core/linking-port";
233
+ export type { LinkFailure, LinkFinished, LinkPendingView, LinkRefusalCode } from "./core/linking";
234
+ export type { MarketplaceAuthMode } from "./core/link-store";
@@ -1,8 +1,13 @@
1
1
  import type { BulkProblemCode } from "../core/bulk";
2
2
  import type { DecisionProblemCode } from "../core/cancellation";
3
+ import type { LinkRefusalCode } from "../core/linking";
3
4
 
4
- /** Every problem code a route can answer, decisions and bulk writes alike. */
5
- export type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
5
+ /**
6
+ * Every problem code a route words from `problems`, decisions and bulk writes
7
+ * alike. MERCHANT_TAKEN is worded by `link.problems` instead (FUT-5613), so a
8
+ * host's own pack written against 1.x still compiles.
9
+ */
10
+ export type MarketplaceProblemCode = DecisionProblemCode | Exclude<BulkProblemCode, "MERCHANT_TAKEN">;
6
11
 
7
12
  /**
8
13
  * Every sentence the marketplace routes answer with. Required, no defaults
@@ -22,4 +27,17 @@ export interface MarketplaceServerCopy {
22
27
  orderNoLongerPending: string;
23
28
  /** One sentence per problem code, for each `problems[].message`. */
24
29
  problems: Readonly<Record<MarketplaceProblemCode, string>>;
30
+ /**
31
+ * OPTIONAL in the type, so a host's own pack written against 1.x still
32
+ * compiles: the sentences of the linking routes (FUT-5613). Absent, those
33
+ * routes answer the machine code as `error`. Both shipped packs carry it.
34
+ */
35
+ link?: MarketplaceLinkCopy;
36
+ }
37
+
38
+ /** What the linking routes say: one sentence per refusal, and one for "try again". */
39
+ export interface MarketplaceLinkCopy {
40
+ problems: Readonly<Record<LinkRefusalCode, string>>;
41
+ /** The marketplace did not answer (a timeout, a 5xx, a rate limit). */
42
+ tryAgain: string;
25
43
  }
@@ -19,4 +19,17 @@ export const MARKETPLACE_SERVER_COPY_EN_US = {
19
19
  NOTHING_TO_UPDATE: "Nothing to update.",
20
20
  CATALOG_ITEM_NOT_FOUND: "Product not found.",
21
21
  },
22
+ link: {
23
+ problems: {
24
+ UNAVAILABLE: "Connecting through the app is not available for this marketplace.",
25
+ NO_LINK_IN_PROGRESS: "No connection is in progress. Start again from the first step.",
26
+ LINK_EXPIRED: "The code has expired. Get a new code and repeat the steps.",
27
+ CODE_REFUSED: "The marketplace refused the authorization code. Check the code and paste it again.",
28
+ MARKETPLACE_REFUSED: "The marketplace refused the connection request.",
29
+ NOT_LINKED: "This store is not connected through the app. Connect it again.",
30
+ UNKNOWN_MERCHANT: "This store is not among the ones authorized on the marketplace.",
31
+ MERCHANT_TAKEN: "This marketplace store is already connected to another account.",
32
+ },
33
+ tryAgain: "The marketplace did not answer. Try again in a moment.",
34
+ },
22
35
  } as const satisfies MarketplaceServerCopy;
@@ -29,7 +29,7 @@ export function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketpla
29
29
 
30
30
  export type { MarketplaceActor, MarketplaceApiConfig } from "./http";
31
31
  export type { MarketplaceRoute } from "./routes";
32
- export type { MarketplaceServerCopy } from "./copy";
32
+ export type { MarketplaceLinkCopy, MarketplaceServerCopy } from "./copy";
33
33
  export {
34
34
  MARKETPLACE_DECIDE,
35
35
  MARKETPLACE_MANAGE,
@@ -0,0 +1,140 @@
1
+ import type { WireResponse, WireRoute } from "@12-apps/wiring";
2
+
3
+ import type { MarketplaceIntegrationView } from "../core/integration";
4
+ import type { LinkFailure, LinkPendingView, LinkRefusalCode } from "../core/linking";
5
+ import { MARKETPLACE_MANAGE } from "./contribution";
6
+ import { iso, ok, parse, refuse, type MarketplaceActor, type MarketplaceApiConfig } from "./http";
7
+ import { finishLinkBody, linkMerchantsQuery, linkStateQuery, selectLinkMerchantBody, startLinkBody } from "./mcp-link";
8
+
9
+ /**
10
+ * Linking a store through the software's own marketplace app (FUT-5613), as
11
+ * HTTP, beside the connection routes and behind the same permission:
12
+ *
13
+ * - `GET …/marketplace/link?provider=` — whether linking is available, and the code in progress;
14
+ * - `POST …/marketplace/link/start` — a new portal code (the verifier stays on the server);
15
+ * - `POST …/marketplace/link/finish` — the pasted authorization code, for the store's tokens;
16
+ * - `GET …/marketplace/link/merchants?provider=` — the marketplace stores the grant covers;
17
+ * - `PUT …/marketplace/link/merchant` — which of them this store is.
18
+ *
19
+ * No answer ever carries a token, a verifier or the app's credentials.
20
+ */
21
+
22
+ const BASE = "/admin/:tenantSlug/marketplace/link";
23
+
24
+ /** The HTTP status each refusal answers. */
25
+ const STATUS: Readonly<Record<LinkRefusalCode, number>> = {
26
+ UNAVAILABLE: 409,
27
+ NO_LINK_IN_PROGRESS: 409,
28
+ LINK_EXPIRED: 409,
29
+ CODE_REFUSED: 422,
30
+ MARKETPLACE_REFUSED: 502,
31
+ NOT_LINKED: 409,
32
+ UNKNOWN_MERCHANT: 422,
33
+ MERCHANT_TAKEN: 409,
34
+ };
35
+
36
+ /** A failure as the routes answer it: the host's sentence, the code, and the marketplace's own words. */
37
+ function failed(config: MarketplaceApiConfig, failure: LinkFailure): WireResponse {
38
+ const words = config.copy.link;
39
+ if (failure.kind === "retry") {
40
+ return refuse(503, words?.tryAgain ?? "MARKETPLACE_UNREACHABLE", { code: "MARKETPLACE_UNREACHABLE" });
41
+ }
42
+ return refuse(STATUS[failure.code], words?.problems[failure.code] ?? failure.code, {
43
+ code: failure.code,
44
+ ...(failure.message === null ? {} : { marketplaceStatus: failure.status, marketplaceMessage: failure.message }),
45
+ });
46
+ }
47
+
48
+ const pendingOut = (pending: LinkPendingView | null) => (pending ? { ...pending, expiresAt: pending.expiresAt.toISOString() } : null);
49
+
50
+ function connectionOut(row: MarketplaceIntegrationView) {
51
+ return { ...row, lastEventAt: iso(row.lastEventAt), lastVerifiedAt: iso(row.lastVerifiedAt), archivedAt: iso(row.archivedAt) };
52
+ }
53
+
54
+ /** An unknown provider, before anything is asked of the engine. */
55
+ function unknown(config: MarketplaceApiConfig, id: string): WireResponse | null {
56
+ return config.engine.knows(id) ? null : refuse(422, config.copy.problems.UNKNOWN_PROVIDER, { code: "UNKNOWN_PROVIDER" });
57
+ }
58
+
59
+ function readRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
60
+ const { engine, copy } = config;
61
+ return [
62
+ {
63
+ method: "GET",
64
+ path: BASE,
65
+ permission: MARKETPLACE_MANAGE,
66
+ handle: async ({ actor, query }) => {
67
+ const parsed = parse(linkStateQuery, query, copy);
68
+ if (!parsed.ok) return parsed.response;
69
+ const refusal = unknown(config, parsed.value.provider);
70
+ if (refusal) return refusal;
71
+ const state = await engine.linkState({ clientId: actor.clientId, ...parsed.value });
72
+ return ok({ available: state.available, pending: pendingOut(state.pending) });
73
+ },
74
+ },
75
+ {
76
+ method: "GET",
77
+ path: `${BASE}/merchants`,
78
+ permission: MARKETPLACE_MANAGE,
79
+ handle: async ({ actor, query }) => {
80
+ const parsed = parse(linkMerchantsQuery, query, copy);
81
+ if (!parsed.ok) return parsed.response;
82
+ const refusal = unknown(config, parsed.value.provider);
83
+ if (refusal) return refusal;
84
+ const result = await engine.linkedMerchants({ clientId: actor.clientId, provider: parsed.value.provider });
85
+ return result.kind === "listed" ? ok(result.merchants) : failed(config, result);
86
+ },
87
+ },
88
+ ];
89
+ }
90
+
91
+ function writeRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
92
+ const { engine, copy } = config;
93
+ return [
94
+ {
95
+ method: "POST",
96
+ path: `${BASE}/start`,
97
+ permission: MARKETPLACE_MANAGE,
98
+ handle: async ({ actor, body }) => {
99
+ const parsed = parse(startLinkBody, body, copy);
100
+ if (!parsed.ok) return parsed.response;
101
+ const refusal = unknown(config, parsed.value.provider);
102
+ if (refusal) return refusal;
103
+ const result = await engine.startLink({ clientId: actor.clientId, ...parsed.value });
104
+ return result.kind === "started" ? ok(pendingOut(result.pending)) : failed(config, result);
105
+ },
106
+ },
107
+ {
108
+ method: "POST",
109
+ path: `${BASE}/finish`,
110
+ permission: MARKETPLACE_MANAGE,
111
+ handle: async ({ actor, body }) => {
112
+ const parsed = parse(finishLinkBody, body, copy);
113
+ if (!parsed.ok) return parsed.response;
114
+ const refusal = unknown(config, parsed.value.provider);
115
+ if (refusal) return refusal;
116
+ const result = await engine.finishLink({ clientId: actor.clientId, actorId: actor.userId ?? null, ...parsed.value });
117
+ if (result.kind !== "linked") return failed(config, result);
118
+ return ok({ integration: connectionOut(result.integration), merchants: result.merchants });
119
+ },
120
+ },
121
+ {
122
+ method: "PUT",
123
+ path: `${BASE}/merchant`,
124
+ permission: MARKETPLACE_MANAGE,
125
+ handle: async ({ actor, body }) => {
126
+ const parsed = parse(selectLinkMerchantBody, body, copy);
127
+ if (!parsed.ok) return parsed.response;
128
+ const refusal = unknown(config, parsed.value.provider);
129
+ if (refusal) return refusal;
130
+ const result = await engine.selectLinkedMerchant({ clientId: actor.clientId, ...parsed.value });
131
+ return result.kind === "selected" ? ok({ integration: connectionOut(result.integration) }) : failed(config, result);
132
+ },
133
+ },
134
+ ];
135
+ }
136
+
137
+ /** The linking routes, in mount order. */
138
+ export function linkRoutes(config: MarketplaceApiConfig): WireRoute<MarketplaceActor>[] {
139
+ return [...readRoutes(config), ...writeRoutes(config)];
140
+ }