@12-apps/marketplace 1.12.0 → 1.13.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 (39) hide show
  1. package/ADOPTING.md +44 -0
  2. package/README.md +12 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-nUyZpLzz.d.ts → adapter-CQ4QiZPi.d.ts} +3 -2
  6. package/dist/{chunk-LACBT6NC.js → chunk-4J2KJ3ZW.js} +1 -1
  7. package/dist/{chunk-LACBT6NC.js.map → chunk-4J2KJ3ZW.js.map} +1 -1
  8. package/dist/{chunk-45ZVN5XI.js → chunk-CEWTV2TC.js} +63 -17
  9. package/dist/chunk-CEWTV2TC.js.map +1 -0
  10. package/dist/{chunk-L6FG6T4S.js → chunk-NFJQQWG4.js} +2 -2
  11. package/dist/{chunk-MIPNQ7X5.js → chunk-W57TITU4.js} +2 -2
  12. package/dist/{client-Ctas7WCS.d.ts → client-CCSnylou.d.ts} +1 -1
  13. package/dist/{engine-CIy9P7Cq.d.ts → engine-1KlJ_8jK.d.ts} +1 -1
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +15 -2
  17. package/dist/ifood/index.js +188 -118
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +2 -2
  21. package/dist/keeta/index.d.ts +2 -2
  22. package/dist/keeta/index.js +2 -2
  23. package/dist/manifest/server.d.ts +2 -2
  24. package/dist/manifest/server.js +2 -2
  25. package/dist/rappi/index.d.ts +1 -1
  26. package/dist/rappi/index.js +1 -1
  27. package/dist/server/index.d.ts +2 -2
  28. package/dist/server/index.js +2 -2
  29. package/package.json +1 -1
  30. package/src/core/adapter.ts +2 -1
  31. package/src/core/connection-stamp.ts +61 -0
  32. package/src/core/fetch-order.ts +54 -12
  33. package/src/core/integration.ts +19 -4
  34. package/src/ifood/fetch-order.ts +103 -0
  35. package/src/ifood/index.ts +5 -1
  36. package/src/ifood/normalize.ts +23 -3
  37. package/dist/chunk-45ZVN5XI.js.map +0 -1
  38. /package/dist/{chunk-L6FG6T4S.js.map → chunk-NFJQQWG4.js.map} +0 -0
  39. /package/dist/{chunk-MIPNQ7X5.js.map → chunk-W57TITU4.js.map} +0 -0
@@ -14,7 +14,7 @@ import {
14
14
  answered,
15
15
  outboundResultOf,
16
16
  tokenGrantResultOf
17
- } from "./chunk-LACBT6NC.js";
17
+ } from "./chunk-4J2KJ3ZW.js";
18
18
  import {
19
19
  __name
20
20
  } from "./chunk-7QVYU63E.js";
@@ -475,4 +475,4 @@ export {
475
475
  normalizeOpenDeliveryEventAs,
476
476
  normalizeOpenDeliveryOrderAs
477
477
  };
478
- //# sourceMappingURL=chunk-L6FG6T4S.js.map
478
+ //# sourceMappingURL=chunk-NFJQQWG4.js.map
@@ -18,7 +18,7 @@ import {
18
18
  CatalogueRetryError,
19
19
  FetchOrderRetryError,
20
20
  OutboundRetryError
21
- } from "./chunk-45ZVN5XI.js";
21
+ } from "./chunk-CEWTV2TC.js";
22
22
  import {
23
23
  __name
24
24
  } from "./chunk-7QVYU63E.js";
@@ -651,4 +651,4 @@ export {
651
651
  MARKETPLACE_JOBS,
652
652
  createApiMarketplace
653
653
  };
654
- //# sourceMappingURL=chunk-MIPNQ7X5.js.map
654
+ //# sourceMappingURL=chunk-W57TITU4.js.map
@@ -1,4 +1,4 @@
1
- import { O as OutboundResult } from './adapter-nUyZpLzz.js';
1
+ import { O as OutboundResult } from './adapter-CQ4QiZPi.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 { a8 as MarketplaceDeliveredBy, ae as MarketplaceLinkAttemptDelegate, u as CatalogueItem, t as CatalogueImage, a as NormalizedMarketplaceOrder, N as NormalizedEvent, ap as StatusStep, i as NormalizedCourierEvent, a3 as MarketplaceCourierFacts, a1 as MarketplaceCourierAnswer, an as PickupCodeValidation, aa as MarketplaceHttp, Z as MarketplaceAppCredentialsPort, c as MarketplaceAdapter, l as MarketplaceProvider, a7 as MarketplaceCredentials, L as CatalogueWarningCode, Y as LinkedMerchant, ad as MarketplaceLifecycle, a4 as MarketplaceCourierStep, a2 as MarketplaceCourierEngine, m as CancellationReason, ak as OutboundOrderRef, b as CatalogueMenuOptions, B as CatalogueReadResult } from './adapter-nUyZpLzz.js';
1
+ import { a8 as MarketplaceDeliveredBy, ae as MarketplaceLinkAttemptDelegate, u as CatalogueItem, t as CatalogueImage, a as NormalizedMarketplaceOrder, N as NormalizedEvent, ap as StatusStep, i as NormalizedCourierEvent, a3 as MarketplaceCourierFacts, a1 as MarketplaceCourierAnswer, an as PickupCodeValidation, aa as MarketplaceHttp, Z as MarketplaceAppCredentialsPort, c as MarketplaceAdapter, l as MarketplaceProvider, a7 as MarketplaceCredentials, Q as CatalogueWarningCode, Y as LinkedMerchant, ad as MarketplaceLifecycle, a4 as MarketplaceCourierStep, a2 as MarketplaceCourierEngine, m as CancellationReason, ak as OutboundOrderRef, b as CatalogueMenuOptions, B as CatalogueReadResult } from './adapter-CQ4QiZPi.js';
2
2
 
3
3
  /** What the engine tells the host about the order a lifecycle event names. */
4
4
  interface MarketplaceLifecycleFacts {
@@ -1,7 +1,7 @@
1
1
  import { Hono, Context } from 'hono';
2
2
  import { ApiMarketplace, MarketplaceApiConfig, MarketplaceActor } from '../server/index.js';
3
- import '../engine-CIy9P7Cq.js';
4
- import '../adapter-nUyZpLzz.js';
3
+ import '../engine-1KlJ_8jK.js';
4
+ import '../adapter-CQ4QiZPi.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-MIPNQ7X5.js";
3
+ } from "../chunk-W57TITU4.js";
4
4
  import "../chunk-SGOTN5PX.js";
5
- import "../chunk-45ZVN5XI.js";
5
+ import "../chunk-CEWTV2TC.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, g as MarketplaceLinking, h as MarketplaceCourierApi, i as NormalizedCourierEvent, M as MarketplaceAvailability, A as AdapterCallContext, S as StorePauseRequest, j as StorePauseResult, k as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-nUyZpLzz.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, A as AdapterCallContext, F as FetchOrderResult, d as PushCatalogue, e as CatalogueItemOut, f as CatalogueReader, g as MarketplaceLinking, h as MarketplaceCourierApi, i as NormalizedCourierEvent, M as MarketplaceAvailability, S as StorePauseRequest, j as StorePauseResult, k as StorePauseRef, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
2
2
 
3
3
  /**
4
4
  * The words the iFood adapter needs from its host, and nothing else.
@@ -30,6 +30,12 @@ interface IfoodAdapterCopy {
30
30
  * connection untestable.
31
31
  */
32
32
  declare function verifyIfoodSignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean;
33
+ /**
34
+ * The order body of a placed-order event, or null when it carries none. Also
35
+ * reads the order iFood serves at `GET /order/v1.0/orders/{id}` (`./fetch-order.ts`),
36
+ * whose fields are the same ones the event's `order` would carry.
37
+ */
38
+ declare function readIfoodOrder(payload: unknown, externalOrderId: string, missingStreetNumber: string): NormalizedMarketplaceOrder | null;
33
39
  /**
34
40
  * Normalize one iFood delivery.
35
41
  *
@@ -42,6 +48,13 @@ declare function normalizeIfoodEvent(payload: unknown, options: {
42
48
  missingStreetNumber: string;
43
49
  }): NormalizedEvent | null;
44
50
 
51
+ /** Fetch one order iFood's event only named. Never throws: no answer is a retry. */
52
+ declare function ifoodFetchOrder(ctx: AdapterCallContext, ref: {
53
+ externalOrderId: string;
54
+ }, options: {
55
+ missingStreetNumber: string;
56
+ }): Promise<FetchOrderResult>;
57
+
45
58
  /** The item's and its product's ids, stable per publication. */
46
59
  declare const ifoodItemId: (ref: string) => string;
47
60
  declare const ifoodProductId: (ref: string) => string;
@@ -126,4 +139,4 @@ interface IfoodAdapterConfig {
126
139
  /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
127
140
  declare function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter;
128
141
 
129
- export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_COURIER, 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, readIfoodCourierEvent, verifyIfoodSignature };
142
+ export { IFOOD_AVAILABILITY, IFOOD_CANCELLATION_ANSWER_WINDOW_MS, IFOOD_CATALOGUE, IFOOD_CATALOGUE_READER, IFOOD_COURIER, IFOOD_IMAGE_BASE_URL, IFOOD_LINKING, IFOOD_PROVIDER, IFOOD_REASON_CODES, type IfoodAdapterConfig, type IfoodAdapterCopy, type IfoodReasonCode, createIfoodAdapter, ifoodFetchOrder, ifoodItemBody, ifoodItemId, ifoodLocalTime, ifoodPause, ifoodProductId, ifoodResume, normalizeIfoodEvent, readIfoodCourierEvent, readIfoodOrder, verifyIfoodSignature };
@@ -17,7 +17,7 @@ import {
17
17
  answered,
18
18
  outboundResultOf,
19
19
  tokenGrantResultOf
20
- } from "../chunk-LACBT6NC.js";
20
+ } from "../chunk-4J2KJ3ZW.js";
21
21
  import {
22
22
  __name
23
23
  } from "../chunk-7QVYU63E.js";
@@ -702,120 +702,6 @@ async function tracking(ctx, order) {
702
702
  __name(tracking, "tracking");
703
703
  var IFOOD_COURIER = { validatePickupCode, tracking };
704
704
 
705
- // src/ifood/linking.ts
706
- var USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
707
- var TOKEN_URL2 = `${IFOOD_API}/authentication/v1.0/oauth/token`;
708
- var MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
709
- var USER_CODE_SECONDS = 600;
710
- var ACCESS_TOKEN_SECONDS = 21600;
711
- var MERCHANT_PAGE_SIZE = 100;
712
- var MAX_MERCHANT_PAGES = 20;
713
- var FORM = { "Content-Type": "application/x-www-form-urlencoded" };
714
- function json(body) {
715
- try {
716
- return body === "" ? null : JSON.parse(body);
717
- } catch {
718
- return null;
719
- }
720
- }
721
- __name(json, "json");
722
- async function call3(ctx, request, read2) {
723
- try {
724
- const response = await ctx.http(request);
725
- const result = outboundResultOf(response);
726
- if (result.kind !== "accepted") return result;
727
- const value = read2(json(response.body));
728
- return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
729
- } catch (error) {
730
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
731
- }
732
- }
733
- __name(call3, "call");
734
- var positive = /* @__PURE__ */ __name((value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback, "positive");
735
- function codeOf(body) {
736
- const userCode = asString(pick(body, "userCode"));
737
- const verifier = asString(pick(body, "authorizationCodeVerifier"));
738
- const verificationUrl = asString(pick(body, "verificationUrl"));
739
- if (!userCode || !verifier || !verificationUrl) return null;
740
- return {
741
- userCode,
742
- verifier,
743
- verificationUrl,
744
- verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
745
- expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS)
746
- };
747
- }
748
- __name(codeOf, "codeOf");
749
- function grantOf(body, requireRefresh) {
750
- const accessToken = asString(pick(body, "accessToken"));
751
- const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
752
- if (!accessToken || requireRefresh && !refreshToken) return null;
753
- return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
754
- }
755
- __name(grantOf, "grantOf");
756
- function merchantsOf(body) {
757
- if (!Array.isArray(body)) return null;
758
- return body.flatMap((raw) => {
759
- const id = asString(pick(raw, "id"));
760
- return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
761
- });
762
- }
763
- __name(merchantsOf, "merchantsOf");
764
- var tokenRequest = /* @__PURE__ */ __name((fields) => ({
765
- method: "POST",
766
- url: TOKEN_URL2,
767
- headers: FORM,
768
- body: new URLSearchParams(fields).toString()
769
- }), "tokenRequest");
770
- async function listMerchants(ctx, accessToken) {
771
- const all = [];
772
- for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
773
- const answer = await call3(
774
- ctx,
775
- {
776
- method: "GET",
777
- url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
778
- headers: { Authorization: `Bearer ${accessToken}` }
779
- },
780
- merchantsOf
781
- );
782
- if (answer.kind !== "ok") return answer;
783
- all.push(...answer.value);
784
- if (answer.value.length < MERCHANT_PAGE_SIZE) break;
785
- }
786
- return { kind: "ok", value: all };
787
- }
788
- __name(listMerchants, "listMerchants");
789
- var IFOOD_LINKING = {
790
- requestCode: /* @__PURE__ */ __name((ctx) => call3(
791
- ctx,
792
- { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
793
- codeOf
794
- ), "requestCode"),
795
- exchange: /* @__PURE__ */ __name((ctx, input) => call3(
796
- ctx,
797
- tokenRequest({
798
- grantType: "authorization_code",
799
- clientId: ctx.credentials.clientId,
800
- clientSecret: ctx.credentials.clientSecret,
801
- authorizationCode: input.authorizationCode,
802
- authorizationCodeVerifier: input.verifier
803
- }),
804
- (body) => grantOf(body, true)
805
- ), "exchange"),
806
- refresh: /* @__PURE__ */ __name((ctx, input) => call3(
807
- ctx,
808
- tokenRequest({
809
- grantType: "refresh_token",
810
- clientId: ctx.credentials.clientId,
811
- clientSecret: ctx.credentials.clientSecret,
812
- refreshToken: input.refreshToken
813
- }),
814
- (body) => grantOf(body, false)
815
- ), "refresh"),
816
- merchants: /* @__PURE__ */ __name((ctx, input) => listMerchants(ctx, input.accessToken), "merchants")
817
- };
818
-
819
705
  // src/ifood/normalize.ts
820
706
  var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
821
707
  var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
@@ -915,7 +801,7 @@ function optional(key, value) {
915
801
  return value === void 0 ? {} : { [key]: value };
916
802
  }
917
803
  __name(optional, "optional");
918
- function readOrder(payload, externalOrderId, missingStreetNumber) {
804
+ function readIfoodOrder(payload, externalOrderId, missingStreetNumber) {
919
805
  const order = pick(payload, "order") ?? payload;
920
806
  const rawItems = pick(order, "items");
921
807
  const lines = (Array.isArray(rawItems) ? rawItems : []).map(readLine).filter((line) => line !== null);
@@ -948,7 +834,13 @@ function readOrder(payload, externalOrderId, missingStreetNumber) {
948
834
  pickupCode: firstString(order, [["delivery", "pickupCode"]])
949
835
  };
950
836
  }
951
- __name(readOrder, "readOrder");
837
+ __name(readIfoodOrder, "readIfoodOrder");
838
+ function placedOrder(payload, placed, externalOrderId, missingStreetNumber) {
839
+ if (!placed) return { order: null };
840
+ const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);
841
+ return order ? { order } : { order: null, orderToFetch: true };
842
+ }
843
+ __name(placedOrder, "placedOrder");
952
844
  function normalizeIfoodEvent(payload, options) {
953
845
  const externalOrderId = firstString(payload, [["orderId"], ["order", "id"], ["id"]]);
954
846
  if (!externalOrderId) return null;
@@ -966,7 +858,7 @@ function normalizeIfoodEvent(payload, options) {
966
858
  eventType,
967
859
  externalMerchantId: firstString(payload, [["merchantId"], ["merchant", "id"]]),
968
860
  externalOrderId,
969
- order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
861
+ ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),
970
862
  cancelled,
971
863
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
972
864
  ...LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {},
@@ -975,6 +867,180 @@ function normalizeIfoodEvent(payload, options) {
975
867
  }
976
868
  __name(normalizeIfoodEvent, "normalizeIfoodEvent");
977
869
 
870
+ // src/ifood/fetch-order.ts
871
+ var orderResourceUrl = /* @__PURE__ */ __name((externalOrderId) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`, "orderResourceUrl");
872
+ async function getOrder(ctx, externalOrderId) {
873
+ const auth = await bearer(ctx);
874
+ if (!("token" in auth)) {
875
+ return auth.kind === "accepted" ? { kind: "retry", reason: "iFood answered the token grant without a token" } : auth;
876
+ }
877
+ const response = await ctx.http({
878
+ method: "GET",
879
+ url: orderResourceUrl(externalOrderId),
880
+ headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" }
881
+ });
882
+ return { response };
883
+ }
884
+ __name(getOrder, "getOrder");
885
+ function orderOf(body, externalOrderId, missingStreetNumber) {
886
+ let parsed2;
887
+ try {
888
+ parsed2 = JSON.parse(body);
889
+ } catch {
890
+ return { kind: "retry", reason: "iFood answered the order read with a body that is not JSON" };
891
+ }
892
+ const named = firstString(parsed2, [["id"]]);
893
+ if (named !== null && named !== externalOrderId) {
894
+ return { kind: "refused", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };
895
+ }
896
+ const order = readIfoodOrder(parsed2, externalOrderId, missingStreetNumber);
897
+ if (!order) return { kind: "refused", status: 200, message: "iFood answered an order with no items" };
898
+ return { kind: "order", order: { ...order, externalMerchantId: firstString(parsed2, [["merchant", "id"]]) } };
899
+ }
900
+ __name(orderOf, "orderOf");
901
+ function failureOf3(response) {
902
+ const message = response.body.slice(0, 300);
903
+ if (response.status === 401 || response.status === 403) {
904
+ return { kind: "refused", status: response.status, message, own: true };
905
+ }
906
+ if (response.status === 404) return { kind: "retry", reason: `status 404: ${message}` };
907
+ const result = outboundResultOf(response);
908
+ return result.kind === "accepted" ? { kind: "retry", reason: `status ${response.status}` } : result;
909
+ }
910
+ __name(failureOf3, "failureOf");
911
+ async function ifoodFetchOrder(ctx, ref, options) {
912
+ try {
913
+ let answer = await getOrder(ctx, ref.externalOrderId);
914
+ if ("response" in answer && answer.response.status === 401) {
915
+ ctx.tokens.delete(ifoodTokenKey(ctx));
916
+ answer = await getOrder(ctx, ref.externalOrderId);
917
+ }
918
+ if (!("response" in answer)) return answer;
919
+ const { response } = answer;
920
+ if (response.status >= 200 && response.status < 300) {
921
+ return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);
922
+ }
923
+ return failureOf3(response);
924
+ } catch (error) {
925
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
926
+ }
927
+ }
928
+ __name(ifoodFetchOrder, "ifoodFetchOrder");
929
+
930
+ // src/ifood/linking.ts
931
+ var USER_CODE_URL = `${IFOOD_API}/authentication/v1.0/oauth/userCode`;
932
+ var TOKEN_URL2 = `${IFOOD_API}/authentication/v1.0/oauth/token`;
933
+ var MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
934
+ var USER_CODE_SECONDS = 600;
935
+ var ACCESS_TOKEN_SECONDS = 21600;
936
+ var MERCHANT_PAGE_SIZE = 100;
937
+ var MAX_MERCHANT_PAGES = 20;
938
+ var FORM = { "Content-Type": "application/x-www-form-urlencoded" };
939
+ function json(body) {
940
+ try {
941
+ return body === "" ? null : JSON.parse(body);
942
+ } catch {
943
+ return null;
944
+ }
945
+ }
946
+ __name(json, "json");
947
+ async function call3(ctx, request, read2) {
948
+ try {
949
+ const response = await ctx.http(request);
950
+ const result = outboundResultOf(response);
951
+ if (result.kind !== "accepted") return result;
952
+ const value = read2(json(response.body));
953
+ return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
954
+ } catch (error) {
955
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
956
+ }
957
+ }
958
+ __name(call3, "call");
959
+ var positive = /* @__PURE__ */ __name((value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback, "positive");
960
+ function codeOf(body) {
961
+ const userCode = asString(pick(body, "userCode"));
962
+ const verifier = asString(pick(body, "authorizationCodeVerifier"));
963
+ const verificationUrl = asString(pick(body, "verificationUrl"));
964
+ if (!userCode || !verifier || !verificationUrl) return null;
965
+ return {
966
+ userCode,
967
+ verifier,
968
+ verificationUrl,
969
+ verificationUrlComplete: asString(pick(body, "verificationUrlComplete")) ?? verificationUrl,
970
+ expiresInSeconds: positive(pick(body, "expiresIn"), USER_CODE_SECONDS)
971
+ };
972
+ }
973
+ __name(codeOf, "codeOf");
974
+ function grantOf(body, requireRefresh) {
975
+ const accessToken = asString(pick(body, "accessToken"));
976
+ const refreshToken = asString(pick(body, "refreshToken")) ?? asString(pick(body, "refresh_token"));
977
+ if (!accessToken || requireRefresh && !refreshToken) return null;
978
+ return { accessToken, refreshToken, expiresInSeconds: positive(pick(body, "expiresIn"), ACCESS_TOKEN_SECONDS) };
979
+ }
980
+ __name(grantOf, "grantOf");
981
+ function merchantsOf(body) {
982
+ if (!Array.isArray(body)) return null;
983
+ return body.flatMap((raw) => {
984
+ const id = asString(pick(raw, "id"));
985
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
986
+ });
987
+ }
988
+ __name(merchantsOf, "merchantsOf");
989
+ var tokenRequest = /* @__PURE__ */ __name((fields) => ({
990
+ method: "POST",
991
+ url: TOKEN_URL2,
992
+ headers: FORM,
993
+ body: new URLSearchParams(fields).toString()
994
+ }), "tokenRequest");
995
+ async function listMerchants(ctx, accessToken) {
996
+ const all = [];
997
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
998
+ const answer = await call3(
999
+ ctx,
1000
+ {
1001
+ method: "GET",
1002
+ url: `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`,
1003
+ headers: { Authorization: `Bearer ${accessToken}` }
1004
+ },
1005
+ merchantsOf
1006
+ );
1007
+ if (answer.kind !== "ok") return answer;
1008
+ all.push(...answer.value);
1009
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
1010
+ }
1011
+ return { kind: "ok", value: all };
1012
+ }
1013
+ __name(listMerchants, "listMerchants");
1014
+ var IFOOD_LINKING = {
1015
+ requestCode: /* @__PURE__ */ __name((ctx) => call3(
1016
+ ctx,
1017
+ { method: "POST", url: USER_CODE_URL, headers: FORM, body: new URLSearchParams({ clientId: ctx.credentials.clientId }).toString() },
1018
+ codeOf
1019
+ ), "requestCode"),
1020
+ exchange: /* @__PURE__ */ __name((ctx, input) => call3(
1021
+ ctx,
1022
+ tokenRequest({
1023
+ grantType: "authorization_code",
1024
+ clientId: ctx.credentials.clientId,
1025
+ clientSecret: ctx.credentials.clientSecret,
1026
+ authorizationCode: input.authorizationCode,
1027
+ authorizationCodeVerifier: input.verifier
1028
+ }),
1029
+ (body) => grantOf(body, true)
1030
+ ), "exchange"),
1031
+ refresh: /* @__PURE__ */ __name((ctx, input) => call3(
1032
+ ctx,
1033
+ tokenRequest({
1034
+ grantType: "refresh_token",
1035
+ clientId: ctx.credentials.clientId,
1036
+ clientSecret: ctx.credentials.clientSecret,
1037
+ refreshToken: input.refreshToken
1038
+ }),
1039
+ (body) => grantOf(body, false)
1040
+ ), "refresh"),
1041
+ merchants: /* @__PURE__ */ __name((ctx, input) => listMerchants(ctx, input.accessToken), "merchants")
1042
+ };
1043
+
978
1044
  // src/ifood/pause.ts
979
1045
  var interruptionsUrl = /* @__PURE__ */ __name((merchantId) => `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`, "interruptionsUrl");
980
1046
  async function call4(ctx, request) {
@@ -1174,6 +1240,8 @@ function createIfoodAdapter(config) {
1174
1240
  catalogueReader: IFOOD_CATALOGUE_READER,
1175
1241
  confirm: /* @__PURE__ */ __name((ctx, order) => ifoodConfirm(ctx, order), "confirm"),
1176
1242
  requestCancellation: ifoodRequestCancellation,
1243
+ // iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).
1244
+ fetchOrder: /* @__PURE__ */ __name((ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions), "fetchOrder"),
1177
1245
  statusSupported: ifoodStatusSupported,
1178
1246
  informStatus: ifoodInformStatus,
1179
1247
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
@@ -1199,6 +1267,7 @@ export {
1199
1267
  IFOOD_PROVIDER,
1200
1268
  IFOOD_REASON_CODES,
1201
1269
  createIfoodAdapter,
1270
+ ifoodFetchOrder,
1202
1271
  ifoodItemBody,
1203
1272
  ifoodItemId,
1204
1273
  ifoodLocalTime,
@@ -1207,6 +1276,7 @@ export {
1207
1276
  ifoodResume,
1208
1277
  normalizeIfoodEvent,
1209
1278
  readIfoodCourierEvent,
1279
+ readIfoodOrder,
1210
1280
  verifyIfoodSignature
1211
1281
  };
1212
1282
  //# sourceMappingURL=index.js.map