@modainteract/moda-interact-shared 4.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -112,8 +112,8 @@ import { runCommerceTurn, type RunnerTool } from
112
112
  | `ToolDescriptorSchema`, `definitionToMcpDescriptor` | Full versioned Tool descriptor versus the MCP-facing name/description/inputSchema projection. The server-only execution definition is not exposed as model instructions. |
113
113
  | `CommerceManifestSchema` | Resolved immutable release contract. Each selected Capability identifies one Feature and one exact Tool descriptor; `featureBehaviours` contains one behaviour prompt for each represented Feature. Commerce provides the manifest; callers validate it. |
114
114
  | `GrantedToolSchema`, `GrantedToolsSchema` | Pinned Tool identity, exact Tool revision, name/version and sorted originating Capability keys selected for a conversation. One Tool reused by several Capabilities is emitted once with all Capability provenance. |
115
- | `CommerceConversationGrantSchema` | Persisted conversation permission snapshot. Background stores the resolved release, selected Capability keys and granted Tools and reuses them on later turns. Empty Capability/Tool selections are valid. |
116
- | `CommerceTurnIdentitySchema`, `CommerceAssertionSchema` | Turn identity and resolve/execute assertion shapes. These do not sign or verify JWT signatures; transport/authentication belongs to the services. |
115
+ | `CommerceConversationGrantSchema` | Persisted conversation permission snapshot. Background owns it and stores the resolved release, selected Capability keys and granted Tools for reuse on later turns. Empty Capability/Tool selections are valid. |
116
+ | `CommerceTurnIdentitySchema`, `CommerceAssertionSchema` | Background-owned turn identity and resolve/execute assertion shapes. These do not sign or verify JWT signatures; transport/authentication belongs to the services. |
117
117
  | `selectCapabilities` | Pure selection over ordinary Feature Capabilities plus caller-supplied Feature eligibility facts. There is no BASE/RECOVERY_POLICY Capability kind or mandatory `conversation_core`. |
118
118
  | `deduplicateTools` | Builds the granted-Tool union from one Tool descriptor per selected Capability while retaining deterministic Capability provenance. |
119
119
  | `manifestMatchesGrant`, `currentlyGrantedTools` | Compare pinned selection and current availability. Do not replace signature, tenant, lease or persistence checks. |
@@ -121,6 +121,11 @@ import { runCommerceTurn, type RunnerTool } from
121
121
  | `CommerceBasketSchema`, `CommerceProductSchema`, `CommerceOfferSchema`, `CommerceEvidenceSchema`, `CommerceAlternativeSchema` | Bounded commerce facts/evidence exchanged between services. Parsing does not prove external facts are true or current. |
122
122
  | `CommerceToolResultSchema`, `commerceToolResultSchema` | Standard result envelope; the factory accepts a specific data schema. |
123
123
 
124
+ Background owns conversation, grant and turn state. MCP receives authenticated
125
+ shop identity and may forward only already accepted opaque adapter context, such
126
+ as `CommerceOutreachToolContextSchema`; it does not interpret that context as
127
+ conversation authority.
128
+
124
129
  The direct release contract is Feature/Capability/Tool based. A selected Capability
125
130
  contains exactly one `featureId` and one exact `toolDescriptor`; Feature behaviour
126
131
  is carried separately and exactly once for each represented Feature. For example:
@@ -2388,20 +2393,34 @@ Type-only exports:
2388
2393
 
2389
2394
  The existing `/commerce` entrypoint exports `CommerceCategoryCandidateSchema`,
2390
2395
  `CommerceCategoryResolutionSchema`, `CommerceOptionalLookupUnavailableSchema`,
2391
- `CommerceConversationToolContextSchema`, and
2392
- `CommerceProductRecommendationSelectionSchema`, with matching inferred types.
2396
+ and `CommerceProductRecommendationSelectionSchema`, with matching inferred types.
2393
2397
  The product input/output dictionaries include category resolution and flat,
2394
2398
  category-aware search. Recommendation selection contains identifiers and quantity,
2395
2399
  not model-authored prices or savings; applicability and cross-field relationships
2396
2400
  remain service policy.
2397
2401
 
2398
- `CommerceBuiltInToolDescriptorSchema`, `CommerceBuiltInToolGrantSchema`,
2399
- `commerceDiscountBuiltInDescriptors`, and `commerceBuiltInToolContractPayload`
2400
- define the two code-owned discount reads. Their checked-in SHA256 hashes cover
2401
- the name, version, description, bounded input schema and actual generated output
2402
- schema using canonical JSON. The helper returns canonical text; hashing is
2403
- injected by the trusted Node adapter. Reading these exports needs no Node crypto
2404
- or provider/database configuration.
2402
+ `CommerceBuiltInToolDescriptorSchema`, `CommerceBuiltInToolGrantSchema`, and
2403
+ `commerceDiscountBuiltInDescriptors` define the two code-owned discount reads.
2404
+ Their durable identity is the canonical tool name and `definitionVersion`; the
2405
+ strict descriptor and grant schemas reject extra fields. Reading these exports
2406
+ needs no provider/database configuration.
2407
+
2408
+ The corrected built-in identities are exactly
2409
+ `commerce_get_discount_options@2.0.0` and
2410
+ `commerce_get_discount_details@2.0.0`. Their strict descriptor/grant schemas reject
2411
+ legacy `1.0.0`; the coordinated pre-production Database/consumer migration must
2412
+ finish before corrected consumers run. No legacy version union is supported.
2413
+
2414
+ Only discount offer `startsAt`/`endsAt` and discount condition-facts
2415
+ `observedAt`/`unavailableAt` use the internal Shared-owned UTC validator:
2416
+ `YYYY-MM-DDTHH:mm:ssZ` or `YYYY-MM-DDTHH:mm:ss.<digits>Z`, with one or more
2417
+ fractional digits when the fraction is present. Seconds and uppercase `T`/`Z`
2418
+ are required; Gregorian dates and clock ranges are validated, including leap-year
2419
+ rules. Minute-only times, numeric offsets, leap seconds, invalid calendar dates
2420
+ and surrounding whitespace are rejected. Values are validated without coercion
2421
+ or normalization. Existing nullability and offer start-before-end checks remain.
2422
+ The exported general `DateSchema` and all its non-discount uses are unchanged.
2423
+ This correction is independent of Zod's `z.iso.datetime` implementation.
2405
2424
 
2406
2425
  Grants and runner descriptors now explicitly distinguish published identities
2407
2426
  from `kind: "BUILT_IN"`. Built-ins have no fabricated tool/revision IDs or
@@ -2417,9 +2436,10 @@ inside `status: "OK"`; hard errors, stale turns and required referrals retain
2417
2436
  their existing semantics. Details permit bounded nullable scalars and depth five;
2418
2437
  input depth stays three and details payloads stay at 16KiB.
2419
2438
 
2420
- These inferred output/grant changes require the coordinated **4.0.0** publication
2421
- and consumer migrations in the separate release task. This source change does
2422
- not bump package metadata or publish to a registry.
2439
+ The timestamp/version correction and prior identity cleanup require a coordinated
2440
+ breaking package publication and consumer migrations in the separate release task
2441
+ (ARCH-058-SHARED-006). This source change does not bump package metadata or publish
2442
+ to a registry.
2423
2443
 
2424
2444
  Run `npm run test:product-discovery-contracts` for the focused contracts/runner
2425
2445
  fixtures. To execute the actual Commerce-owned projector/publication integration,
@@ -277,14 +277,12 @@ var CommerceBuiltInToolNameSchema = z3.enum([
277
277
  var CommerceBuiltInToolGrantSchema = z3.strictObject({
278
278
  kind: z3.enum(["BUILT_IN"]).meta({ maxLength: 8 }),
279
279
  toolName: CommerceBuiltInToolNameSchema,
280
- definitionVersion: z3.enum(["1.0.0"]).meta({ maxLength: 5 }),
281
- contractHash: HashSchema
280
+ definitionVersion: z3.enum(["2.0.0"]).meta({ maxLength: 5 })
282
281
  });
283
282
  var CommerceBuiltInToolDescriptorSchema = z3.strictObject({
284
283
  kind: z3.enum(["BUILT_IN"]).meta({ maxLength: 8 }),
285
284
  name: CommerceBuiltInToolNameSchema,
286
- definitionVersion: z3.enum(["1.0.0"]).meta({ maxLength: 5 }),
287
- contractHash: HashSchema,
285
+ definitionVersion: z3.enum(["2.0.0"]).meta({ maxLength: 5 }),
288
286
  description: z3.string().min(1).max(4096),
289
287
  inputSchema: InputSchemaSchema
290
288
  });
@@ -311,6 +309,7 @@ var POLICY_OPERATIONS = [
311
309
  "recovery.getBasket",
312
310
  "shopify.searchProducts",
313
311
  "discounts.getOptions",
312
+ "discounts.getDetails",
314
313
  "discounts.evaluate",
315
314
  "products.findQualifying",
316
315
  "products.findSimilar"
@@ -526,11 +525,45 @@ var POLICY_OPERATION_DESCRIPTORS = POLICY_OPERATIONS.map(
526
525
  );
527
526
 
528
527
  // src/commerce/built-in-tools.ts
529
- import { z as z6 } from "zod";
530
-
531
- // src/commerce/schemas.ts
532
- import { z as z5 } from "zod";
533
- import { validRange } from "semver";
528
+ function immutable(value) {
529
+ for (const child of Object.values(value))
530
+ if (child && typeof child === "object") immutable(child);
531
+ return Object.freeze(value);
532
+ }
533
+ var commerceDiscountBuiltInDescriptors = immutable([
534
+ {
535
+ kind: "BUILT_IN",
536
+ name: "commerce_get_discount_options",
537
+ definitionVersion: "2.0.0",
538
+ description: "Read the current shop's permitted discount options.",
539
+ inputSchema: {
540
+ type: "object",
541
+ properties: {
542
+ limit: { type: "integer", minimum: 1, maximum: 50 },
543
+ cursor: { type: ["string", "null"], maxLength: 2048 }
544
+ },
545
+ additionalProperties: false
546
+ }
547
+ },
548
+ {
549
+ kind: "BUILT_IN",
550
+ name: "commerce_get_discount_details",
551
+ definitionVersion: "2.0.0",
552
+ description: "Read details for a permitted discount in the current shop.",
553
+ inputSchema: {
554
+ type: "object",
555
+ properties: { offerId: { type: "string", minLength: 1, maxLength: 128 } },
556
+ required: ["offerId"],
557
+ additionalProperties: false
558
+ }
559
+ }
560
+ ]);
561
+ function isTrustedCommerceBuiltInDescriptor(value) {
562
+ return commerceDiscountBuiltInDescriptors.some((expected) => canonicalJson(expected) === canonicalJson(value));
563
+ }
564
+ function isTrustedCommerceBuiltInGrant(value) {
565
+ return commerceDiscountBuiltInDescriptors.some((expected) => value.toolName === expected.name && value.definitionVersion === expected.definitionVersion);
566
+ }
534
567
 
535
568
  // src/commerce/response.ts
536
569
  import { z as z4 } from "zod";
@@ -709,6 +742,8 @@ function finalResponseToolSchema(definition) {
709
742
  }
710
743
 
711
744
  // src/commerce/schemas.ts
745
+ import { z as z5 } from "zod";
746
+ import { validRange } from "semver";
712
747
  var CommerceTurnIdentitySchema = z5.strictObject({
713
748
  contractVersion: ContractVersionSchema,
714
749
  shopId: IdSchema,
@@ -798,7 +833,7 @@ var CommerceManifestSchema = z5.strictObject({
798
833
  });
799
834
  }
800
835
  if (union.size + v.builtInTools.length !== v.grantedTools.length || !distinct(v.builtInTools.map((tool) => tool.name)) || v.builtInTools.some((tool) => !isTrustedCommerceBuiltInDescriptor(tool)) || v.grantedTools.some((t) => {
801
- if (isBuiltInTool(t)) return !v.builtInTools.some((descriptor) => descriptor.name === t.toolName && descriptor.definitionVersion === t.definitionVersion && descriptor.contractHash === t.contractHash && isTrustedCommerceBuiltInGrant(t));
836
+ if (isBuiltInTool(t)) return !v.builtInTools.some((descriptor) => descriptor.name === t.toolName && descriptor.definitionVersion === t.definitionVersion && isTrustedCommerceBuiltInGrant(t));
802
837
  const expected = union.get(t.toolId)?.tool;
803
838
  return !expected || expected.toolRevisionId !== t.toolRevisionId || expected.toolName !== t.toolName || expected.definitionVersion !== t.definitionVersion || JSON.stringify([...new Set(expected.capabilityKeys)].sort()) !== JSON.stringify(t.capabilityKeys);
804
839
  }))
@@ -886,13 +921,23 @@ var CommerceProductSchema = z5.strictObject({
886
921
  saleEvidence: CommerceProductSaleEvidenceSchema.nullable().optional(),
887
922
  observedAt: DateSchema
888
923
  });
924
+ var discountUtcPattern = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?Z(?![\s\S])/;
925
+ var CommerceDiscountDateTimeSchema = z5.string().regex(discountUtcPattern).refine((value) => {
926
+ const match = discountUtcPattern.exec(value);
927
+ if (!match) return false;
928
+ const [year, month, day, hour, minute, second] = match.slice(1).map(Number);
929
+ if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59) return false;
930
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
931
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
932
+ return day >= 1 && day <= daysInMonth[month - 1];
933
+ }, "Expected a valid UTC discount timestamp with seconds");
889
934
  var CommerceOfferSchema = z5.strictObject({
890
935
  offerId: IdSchema,
891
936
  title: z5.string().min(1).max(512),
892
937
  method: z5.enum(["AUTOMATIC", "CODE"]),
893
938
  code: z5.string().min(1).max(128).nullable(),
894
- startsAt: DateSchema.nullable(),
895
- endsAt: DateSchema.nullable(),
939
+ startsAt: CommerceDiscountDateTimeSchema.nullable(),
940
+ endsAt: CommerceDiscountDateTimeSchema.nullable(),
896
941
  support: z5.enum(["SUPPORTED", "UNSUPPORTED", "UNKNOWN"]),
897
942
  reasonCodes: z5.array(z5.string().min(1).max(64)).max(16)
898
943
  }).refine(
@@ -912,9 +957,9 @@ var CommerceDiscountCombinationFactsSchema = z5.strictObject({
912
957
  var CommerceDiscountConditionFactsSchema = z5.strictObject({
913
958
  provider: z5.enum(["SHOPIFY", "WOOCOMMERCE"]),
914
959
  completeness: z5.enum(["COMPLETE", "PARTIAL", "UNKNOWN"]),
915
- observedAt: DateSchema,
960
+ observedAt: CommerceDiscountDateTimeSchema,
916
961
  providerStatus: z5.string().max(64),
917
- unavailableAt: DateSchema.nullable(),
962
+ unavailableAt: CommerceDiscountDateTimeSchema.nullable(),
918
963
  discountKind: z5.enum([
919
964
  "PERCENTAGE",
920
965
  "FIXED_AMOUNT",
@@ -1065,12 +1110,6 @@ var CommerceOptionalLookupUnavailableSchema = z5.strictObject({
1065
1110
  outcome: z5.enum(["UNAVAILABLE"]).meta({ maxLength: 11 }),
1066
1111
  reasonCode: z5.enum(["TEMPORARY_UNAVAILABLE"]).meta({ maxLength: 21 })
1067
1112
  });
1068
- var CommerceConversationToolContextSchema = z5.strictObject({
1069
- purpose: z5.enum(["CONVERSATION"]).meta({ maxLength: 12 }),
1070
- conversationId: IdSchema,
1071
- inboundVersion: z5.number().int().positive(),
1072
- grantId: IdSchema.nullable()
1073
- });
1074
1113
  var CommerceProductRecommendationSelectionSchema = z5.strictObject({
1075
1114
  productRecommendationVersion: z5.enum(["1"]).meta({ maxLength: 1 }).optional(),
1076
1115
  productRecommendations: z5.array(z5.strictObject({
@@ -1213,58 +1252,6 @@ function productBelongsToDomain(product, verifiedDomain) {
1213
1252
  }
1214
1253
  }
1215
1254
 
1216
- // src/commerce/built-in-tools.ts
1217
- function immutable(value) {
1218
- for (const child of Object.values(value))
1219
- if (child && typeof child === "object") immutable(child);
1220
- return Object.freeze(value);
1221
- }
1222
- var commerceDiscountBuiltInDescriptors = immutable([
1223
- {
1224
- kind: "BUILT_IN",
1225
- name: "commerce_get_discount_options",
1226
- definitionVersion: "1.0.0",
1227
- contractHash: "a0a4a88c7920a25a31657a03761b6556419189aeab251261a58e2dfb83a3bdcb",
1228
- description: "Read the current shop's permitted discount options.",
1229
- inputSchema: {
1230
- type: "object",
1231
- properties: {
1232
- limit: { type: "integer", minimum: 1, maximum: 50 },
1233
- cursor: { type: ["string", "null"], maxLength: 2048 }
1234
- },
1235
- additionalProperties: false
1236
- }
1237
- },
1238
- {
1239
- kind: "BUILT_IN",
1240
- name: "commerce_get_discount_details",
1241
- definitionVersion: "1.0.0",
1242
- contractHash: "776f6bc6ac1800c75744c2ffa7357f07a32be2b61309b1d71abf0493a2de316f",
1243
- description: "Read details for a permitted discount in the current shop.",
1244
- inputSchema: {
1245
- type: "object",
1246
- properties: { offerId: { type: "string", minLength: 1, maxLength: 128 } },
1247
- required: ["offerId"],
1248
- additionalProperties: false
1249
- }
1250
- }
1251
- ]);
1252
- function commerceBuiltInToolContractPayload(descriptor) {
1253
- return canonicalJson({
1254
- name: descriptor.name,
1255
- definitionVersion: descriptor.definitionVersion,
1256
- description: descriptor.description,
1257
- inputSchema: descriptor.inputSchema,
1258
- outputSchema: z6.toJSONSchema(CommerceToolOutputs[descriptor.name], { io: "output", unrepresentable: "any" })
1259
- });
1260
- }
1261
- function isTrustedCommerceBuiltInDescriptor(value) {
1262
- return commerceDiscountBuiltInDescriptors.some((expected) => canonicalJson(expected) === canonicalJson(value));
1263
- }
1264
- function isTrustedCommerceBuiltInGrant(value) {
1265
- return commerceDiscountBuiltInDescriptors.some((expected) => value.toolName === expected.name && value.definitionVersion === expected.definitionVersion && value.contractHash === expected.contractHash);
1266
- }
1267
-
1268
1255
  export {
1269
1256
  MONEY_PATTERN,
1270
1257
  safeName,
@@ -1318,7 +1305,6 @@ export {
1318
1305
  CommerceToolRevisionIdentitySchema,
1319
1306
  POLICY_OPERATION_DESCRIPTORS,
1320
1307
  commerceDiscountBuiltInDescriptors,
1321
- commerceBuiltInToolContractPayload,
1322
1308
  isTrustedCommerceBuiltInDescriptor,
1323
1309
  isTrustedCommerceBuiltInGrant,
1324
1310
  CommerceResponseContractSchema,
@@ -1351,7 +1337,6 @@ export {
1351
1337
  CommerceCategoryCandidateSchema,
1352
1338
  CommerceCategoryResolutionSchema,
1353
1339
  CommerceOptionalLookupUnavailableSchema,
1354
- CommerceConversationToolContextSchema,
1355
1340
  CommerceProductRecommendationSelectionSchema,
1356
1341
  CommerceResponseDispositionSchema,
1357
1342
  CommerceAnswerPresentationSelectionSchema,
@@ -1361,4 +1346,4 @@ export {
1361
1346
  CommerceToolOutputs,
1362
1347
  productBelongsToDomain
1363
1348
  };
1364
- //# sourceMappingURL=chunk-HR7T3UEW.js.map
1349
+ //# sourceMappingURL=chunk-6OBYUIQ3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commerce/subset.ts","../src/commerce/external.ts","../src/commerce/definitions.ts","../src/commerce/definition-size.ts","../src/commerce/built-in-tools.ts","../src/commerce/response.ts","../src/commerce/schemas.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { canonicalJson, jsonBytes } from \"./canonical-json\";\nexport type Json =\n null | boolean | number | string | Json[] | { [key: string]: Json };\nexport type SubsetSchema = {\n type: string | [string, \"null\"];\n description?: string;\n properties?: Record<string, SubsetSchema>;\n required?: string[];\n additionalProperties?: false;\n items?: SubsetSchema;\n enum?: Array<string | number | boolean | null>;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n minItems?: number;\n maxItems?: number;\n pattern?: string;\n};\nexport const MONEY_PATTERN = \"^[0-9]{1,18}(\\\\.[0-9]{1,6})?$\";\nexport const safeName = (name: string) =>\n /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(name) &&\n ![\"__proto__\", \"prototype\", \"constructor\"].includes(name);\nexport const safePath = (path: string) =>\n path.length <= 256 && path.split(\".\").every(safeName);\nconst keywords = [\n \"type\",\n \"description\",\n \"properties\",\n \"required\",\n \"additionalProperties\",\n \"items\",\n \"enum\",\n \"minLength\",\n \"maxLength\",\n \"minimum\",\n \"maximum\",\n \"minItems\",\n \"maxItems\",\n];\nexport function validateSubset(\n value: unknown,\n mode: \"input\" | \"details\",\n): value is SubsetSchema {\n let propertyCount = 0;\n const maxDepth = mode === \"input\" ? 3 : 5;\n function walk(raw: unknown, depth: number): boolean {\n if (\n depth > maxDepth ||\n !raw ||\n typeof raw !== \"object\" ||\n Array.isArray(raw)\n )\n return false;\n const s = raw as SubsetSchema;\n if (\n Object.keys(s).some(\n (k) => !keywords.includes(k) && !(mode === \"input\" && k === \"pattern\"),\n )\n )\n return false;\n const nullable = Array.isArray(s.type);\n if (\n nullable &&\n (s.type.length !== 2 || s.type[1] !== \"null\" ||\n (mode === \"details\" && [\"object\", \"array\"].includes(s.type[0])))\n )\n return false;\n const type = typeof s.type === \"string\" ? s.type : s.type[0];\n if (\n ![\n \"object\",\n \"string\",\n \"integer\",\n \"boolean\",\n \"array\",\n ...(mode === \"details\" ? [\"number\"] : []),\n ].includes(type)\n )\n return false;\n if (\n s.description !== undefined &&\n (typeof s.description !== \"string\" || s.description.length > 1000)\n )\n return false;\n const specific: Record<string, string[]> = {\n object: [\"properties\", \"required\", \"additionalProperties\"],\n array: [\"items\", \"minItems\", \"maxItems\"],\n string: [\"minLength\", \"maxLength\", \"pattern\"],\n integer: [\"minimum\", \"maximum\"],\n number: [\"minimum\", \"maximum\"],\n boolean: [],\n };\n if (\n Object.keys(s).some(\n (k) =>\n ![\"type\", \"description\", \"enum\"].includes(k) &&\n !specific[type].includes(k),\n )\n )\n return false;\n if (\n s.enum !== undefined &&\n (!Array.isArray(s.enum) ||\n s.enum.length < 1 ||\n s.enum.length > (mode === \"input\" ? 32 : 20) ||\n new Set(s.enum.map((v) => canonicalJson(v))).size !== s.enum.length ||\n s.enum.some((v) =>\n v === null\n ? !nullable\n : typeof v !== (type === \"integer\" ? \"number\" : type) ||\n (type === \"integer\" && !Number.isSafeInteger(v)) ||\n typeof v === \"object\",\n ))\n )\n return false;\n for (const [lo, hi] of [\n [\"minLength\", \"maxLength\"],\n [\"minItems\", \"maxItems\"],\n [\"minimum\", \"maximum\"],\n ] as const) {\n if (\n s[lo] !== undefined &&\n (typeof s[lo] !== \"number\" || !Number.isFinite(s[lo]))\n )\n return false;\n if (\n s[hi] !== undefined &&\n (typeof s[hi] !== \"number\" || !Number.isFinite(s[hi]))\n )\n return false;\n if (\n lo !== \"minimum\" &&\n [s[lo], s[hi]].some(\n (v) => v !== undefined && (!Number.isSafeInteger(v) || v < 0),\n )\n )\n return false;\n if (s[lo] !== undefined && s[hi] !== undefined && s[lo]! > s[hi]!)\n return false;\n }\n if (type === \"string\")\n return (\n s.maxLength !== undefined &&\n s.maxLength <= 4096 &&\n (s.pattern === undefined || s.pattern === MONEY_PATTERN)\n );\n if (type === \"array\")\n return (\n s.maxItems !== undefined &&\n s.maxItems <= (mode === \"input\" ? 100 : 20) &&\n walk(s.items, depth + 1)\n );\n if (type === \"object\") {\n if (\n s.additionalProperties !== false ||\n !s.properties ||\n typeof s.properties !== \"object\" ||\n Array.isArray(s.properties)\n )\n return false;\n const names = Object.keys(s.properties);\n propertyCount += names.length;\n if (\n propertyCount > 32 ||\n names.some((n) => !safeName(n)) ||\n (s.required !== undefined &&\n (!Array.isArray(s.required) ||\n new Set(s.required).size !== s.required.length ||\n s.required.some((n) => !names.includes(n))))\n )\n return false;\n return Object.values(s.properties).every((child) =>\n walk(child, depth + 1),\n );\n }\n return true;\n }\n try {\n return (\n jsonBytes(value) <= 32768 &&\n walk(value, 1) &&\n (value as SubsetSchema).type === \"object\"\n );\n } catch {\n return false;\n }\n}\nexport const InputSchemaSchema = z.custom<SubsetSchema>((v) =>\n validateSubset(v, \"input\"),\n);\nexport const DetailsSchemaSchema = z.custom<SubsetSchema>((v) =>\n validateSubset(v, \"details\"),\n);\nexport function matchesSubset(schema: SubsetSchema, value: unknown): boolean {\n const nullable = Array.isArray(schema.type);\n const type = typeof schema.type === \"string\" ? schema.type : schema.type[0];\n if (value === null)\n return nullable && (!schema.enum || schema.enum.includes(null));\n if (schema.enum && !schema.enum.includes(value as never)) return false;\n if (type === \"string\")\n return (\n typeof value === \"string\" &&\n value.length >= (schema.minLength ?? 0) &&\n value.length <= schema.maxLength! &&\n (!schema.pattern || new RegExp(schema.pattern).test(value))\n );\n if (type === \"boolean\") return typeof value === \"boolean\";\n if (type === \"integer\" || type === \"number\")\n return (\n typeof value === \"number\" &&\n Number.isFinite(value) &&\n (type !== \"integer\" || Number.isSafeInteger(value)) &&\n value >= (schema.minimum ?? -Infinity) &&\n value <= (schema.maximum ?? Infinity)\n );\n if (type === \"array\")\n return (\n Array.isArray(value) &&\n value.length >= (schema.minItems ?? 0) &&\n value.length <= schema.maxItems! &&\n value.every((v) => matchesSubset(schema.items!, v))\n );\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const obj = value as Record<string, unknown>;\n return (\n Object.keys(obj).every((k) => Object.hasOwn(schema.properties!, k)) &&\n (schema.required ?? []).every((k) => Object.hasOwn(obj, k)) &&\n Object.entries(obj).every(([k, v]) =>\n matchesSubset(schema.properties![k], v),\n )\n );\n}\nexport function compileSubset(schema: SubsetSchema, mode: \"input\" | \"details\") {\n if (!validateSubset(schema, mode)) throw new TypeError(\"Unsupported schema\");\n return z.custom<Record<string, Json>>((value) => {\n try {\n return (\n jsonBytes(value) <= (mode === \"details\" ? 16384 : 131072) &&\n matchesSubset(schema, value)\n );\n } catch {\n return false;\n }\n });\n}\n","import { z } from \"zod\";\nimport { DateSchema, IdSchema } from \"./primitives\";\nimport { safeName, safePath } from \"./subset\";\nimport { jsonBytes } from \"./canonical-json\";\n\nconst utf8 = (value: string, maximum: number) => new TextEncoder().encode(value).length <= maximum;\nconst scalar = z.union([z.string().refine((value) => utf8(value, 2048)), z.number().finite(), z.boolean()]);\nexport const ExternalQueryValueSchema = scalar;\nconst scalarOrNull = z.union([scalar, z.null()]);\nconst record = <T extends z.ZodTypeAny>(item: T, max: number) => z.record(z.string().refine(safeName), item).refine((value) => Object.keys(value).length <= max);\n\nexport const ExternalQueryMappingSchema = z.union([\n z.strictObject({ input: z.string().refine(safeName), omitIfMissing: z.literal(true).optional() }),\n z.strictObject({ literal: scalar }),\n]);\nexport const ExternalQueryMappingsSchema = record(ExternalQueryMappingSchema, 32).superRefine((value, ctx) => {\n const reserved = /^(authorization|cookie|set-cookie|host|x-api-key|api_key|apikey|access_token|token|secret|password)$/i;\n for (const key of Object.keys(value)) if (reserved.test(key)) ctx.addIssue({ code: \"custom\", path: [key], message: \"Reserved query key\" });\n});\nexport const ExternalPathSchema = z.string().max(1024).refine((value) =>\n utf8(value, 1024) && /^\\/(?:[A-Za-z0-9._~-]+\\/)*[A-Za-z0-9._~-]*\\/?$/.test(value) &&\n !value.includes(\"//\") && !value.includes(\"%\") && !value.includes(\"\\\\\") &&\n !value.includes(\"?\") && !value.includes(\"#\") && !value.includes(\"{\") && !value.includes(\"}\") &&\n value.split(\"/\").every((segment) => segment !== \".\" && segment !== \"..\"),\n);\nconst mediaType = z.string().min(1).max(128).refine((value) => value === value.toLowerCase() && /^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$/.test(value));\nconst jsonMime = (value: string) => value === \"application/json\" || /^application\\/[a-z0-9!#$&^_.+-]+\\+json$/.test(value);\nconst textMime = (value: string) => /^text\\/[a-z0-9!#$&^_.+-]+$/.test(value) || value === \"application/xml\" || /^application\\/[a-z0-9!#$&^_.+-]+\\+xml$/.test(value) || jsonMime(value);\nexport const ExternalResponseFormatSchema = z.strictObject({ mode: z.enum([\"JSON\", \"TEXT\"]), mediaTypes: z.array(mediaType).min(1).max(8).refine((values) => new Set(values).size === values.length) }).refine((value) => value.mediaTypes.every(value.mode === \"JSON\" ? jsonMime : textMime));\nexport const FieldProjectionSchema = record(z.strictObject({ path: z.string().refine(safePath), omitIfMissing: z.literal(true).optional() }), 32).refine((value) => Object.keys(value).length >= 1);\nexport const ResponseFilterSchema = z.discriminatedUnion(\"op\", [\n z.strictObject({ path: z.string().refine(safePath), op: z.enum([\"EQ\", \"NE\", \"GT\", \"GTE\", \"LT\", \"LTE\", \"CONTAINS\", \"STARTS_WITH\"]), value: scalarOrNull }),\n z.strictObject({ path: z.string().refine(safePath), op: z.literal(\"IN\"), values: z.array(scalarOrNull).min(1).max(20) }),\n]);\nconst visualObject = z.strictObject({ kind: z.literal(\"OBJECT\"), fields: FieldProjectionSchema });\nconst visualList = z.strictObject({ kind: z.literal(\"LIST\"), fields: FieldProjectionSchema, filters: z.array(ResponseFilterSchema).max(8), sort: z.union([z.null(), z.strictObject({ path: z.string().refine(safePath), direction: z.enum([\"ASC\", \"DESC\"]) })]), limit: z.int().min(1).max(20) });\nexport const VisualResponseProcessingSchema = z.union([visualObject, visualList]);\nexport const ResponseProcessingSchema = z.union([VisualResponseProcessingSchema, z.strictObject({ kind: z.literal(\"JAVASCRIPT\"), runtimeVersion: z.literal(\"quickjs-sync.v1\"), source: z.string().min(1).refine((value) => utf8(value, 16384)) })]);\nexport const TransformResponseSchema = z.strictObject({ status: z.int().min(200).max(299), contentType: z.string().min(1).max(128), bodyText: z.string().refine((value) => utf8(value, 262144)), json: z.union([z.null(), z.json()]) });\nexport const TransformSampleSchema = z.strictObject({ status: z.int().min(200).max(299), contentType: z.string().min(1).max(128), bodyText: z.string().refine((value) => utf8(value, 262144)) }).refine((value) => jsonBytes(value) <= 524288);\nconst boundedValues = z.custom<Record<string, unknown>>((value) => {\n const visit = (node: unknown, depth: number): boolean =>\n depth <= 20 && (node === null || typeof node === \"string\" || typeof node === \"boolean\" || (typeof node === \"number\" && Number.isFinite(node)) ||\n (Array.isArray(node) && node.every((child) => visit(child, depth + 1))) ||\n (!!node && typeof node === \"object\" && !Array.isArray(node) && Object.getPrototypeOf(node) === Object.prototype && Object.entries(node).every(([key, child]) => ![\"__proto__\", \"prototype\", \"constructor\"].includes(key) && visit(child, depth + 1))));\n try { return !!value && typeof value === \"object\" && !Array.isArray(value) && visit(value, 1) && jsonBytes(value) <= 49152; } catch { return false; }\n});\nexport const ExternalHttpResultDataSchema = z.strictObject({ source: z.literal(\"EXTERNAL_HTTP\"), connectionRevisionId: IdSchema, observedAt: DateSchema, values: boundedValues });\nexport const ConnectionRevisionViewSchema = z.strictObject({ id: IdSchema, connectionId: IdSchema, revisionNumber: z.int().positive(), origin: z.string().min(1).max(2048), scope: z.enum([\"PLATFORM\", \"PER_SHOP\"]), authMode: z.enum([\"NONE\", \"BEARER\", \"API_KEY\"]), authHeader: z.string().min(1).max(128).nullable(), documentation: z.string().max(16000), createdAt: z.iso.datetime({ offset: false }) });\nexport const ConnectionViewSchema = z.strictObject({ id: IdSchema, key: z.string().regex(/^[a-z][a-z0-9_]{0,127}$/), displayName: z.string().min(1).max(255), description: z.string().max(4096), enabled: z.boolean(), editVersion: z.int().positive(), revisions: z.array(ConnectionRevisionViewSchema) });\nexport const CredentialStatusSchema = z.strictObject({ connectionRevisionId: IdSchema, shopId: IdSchema.nullable(), configured: z.boolean(), editVersion: z.int().positive().nullable(), updatedAt: z.iso.datetime({ offset: false }).nullable() });\nexport const ConnectionCommandSchema = z.strictObject({ operationId: IdSchema, reason: z.string().trim().min(1).max(1000) });\nexport const RevisionInputSchema = z.strictObject({ origin: z.string().min(1).max(2048), scope: z.enum([\"PLATFORM\", \"PER_SHOP\"]), authMode: z.enum([\"NONE\", \"BEARER\", \"API_KEY\"]), authHeader: z.string().min(1).max(128).nullable(), documentation: z.string().max(16000) });\nexport const ConnectionIssueSchema = z.strictObject({ path: z.string().max(256), message: z.string().min(1).max(512) });\nexport const ConnectionResultSchema = <T extends z.ZodType>(value: T) => z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"ok\"), value }),\n z.strictObject({ kind: z.literal(\"not-found\") }),\n z.strictObject({ kind: z.literal(\"forbidden\") }),\n z.strictObject({ kind: z.literal(\"unavailable\") }),\n z.strictObject({ kind: z.literal(\"invalid\"), issues: z.array(ConnectionIssueSchema).max(32) }),\n z.strictObject({ kind: z.literal(\"conflict\"), code: z.enum([\"STALE_CAS\", \"CONFLICTING_REPLAY\"]) }),\n]);\nexport type ExternalResponseFormat = z.infer<typeof ExternalResponseFormatSchema>;\nexport type FieldProjection = z.infer<typeof FieldProjectionSchema>;\nexport type ResponseFilter = z.infer<typeof ResponseFilterSchema>;\nexport type VisualResponseProcessing = z.infer<typeof VisualResponseProcessingSchema>;\nexport type ResponseProcessing = z.infer<typeof ResponseProcessingSchema>;\nexport type TransformResponse = z.infer<typeof TransformResponseSchema>;\nexport type TransformSample = z.infer<typeof TransformSampleSchema>;\nexport type ExternalHttpResultData = z.infer<typeof ExternalHttpResultDataSchema>;\nexport type ConnectionRevisionView = z.infer<typeof ConnectionRevisionViewSchema>;\nexport type ConnectionView = z.infer<typeof ConnectionViewSchema>;\nexport type CredentialStatus = z.infer<typeof CredentialStatusSchema>;\nexport type ConnectionCommand = z.infer<typeof ConnectionCommandSchema>;\nexport type RevisionInput = z.infer<typeof RevisionInputSchema>;\nexport type ConnectionResult<T> =\n | { kind: \"ok\"; value: T }\n | { kind: \"not-found\" | \"forbidden\" | \"unavailable\" }\n | { kind: \"invalid\"; issues: Array<z.infer<typeof ConnectionIssueSchema>> }\n | { kind: \"conflict\"; code: \"STALE_CAS\" | \"CONFLICTING_REPLAY\" };\nexport type VisualResponseProcessorInput = { source: unknown; processing: VisualResponseProcessing; limits: { maxResults: number; deadlineAt: number }; signal: AbortSignal };\nexport type VisualResponseProcessorResult = { ok: true; values: Record<string, unknown> } | { ok: false; code: \"INVALID_RESPONSE\" | \"DEADLINE\" | \"CANCELLED\" };\nexport type CodeResponseProcessorInput = { response: TransformResponse; processing: Extract<ResponseProcessing, { kind: \"JAVASCRIPT\" }>; limits: { maxResults: number; deadlineAt: number }; signal: AbortSignal };\nexport type CodeResponseProcessorResult = { ok: true; values: Record<string, unknown> } | { ok: false; code: \"INVALID_RESPONSE\" | \"DEADLINE\" | \"CANCELLED\" | \"THROTTLED\"; diagnostic?: { code: \"SYNTAX_ERROR\" | \"EXECUTION_ERROR\" | \"INVALID_OUTPUT\" | \"RESOURCE_LIMIT\" | \"RUNTIME_UNAVAILABLE\"; line: number | null; column: number | null } };\n","import { z } from \"zod\";\nimport { gt } from \"semver\";\nimport {\n boundedJson,\n ContractVersionSchema,\n IdSchema,\n SemverSchema,\n HashSchema,\n distinct,\n} from \"./primitives\";\nimport {\n InputSchemaSchema,\n DetailsSchemaSchema,\n safeName,\n safePath,\n type SubsetSchema,\n compileSubset,\n} from \"./subset\";\nimport { canonicalJson } from \"./canonical-json\";\nimport {\n definitionFitsStorage,\n DEFINITION_SIZE_MESSAGE,\n} from \"./definition-size\";\nimport {\n ExternalPathSchema,\n ExternalQueryMappingsSchema,\n ExternalQueryValueSchema,\n ExternalResponseFormatSchema,\n ResponseProcessingSchema,\n} from \"./external\";\nexport const ToolNameSchema = z\n .string()\n .regex(/^[a-z][a-z0-9_]{0,127}$/)\n .refine((n) => n !== \"finalResponse\");\nexport const PublishedGrantedToolSchema = z.strictObject({\n toolId: IdSchema,\n toolRevisionId: IdSchema,\n toolName: ToolNameSchema,\n definitionVersion: SemverSchema,\n capabilityKeys: z\n .array(IdSchema)\n .min(1)\n .max(32)\n .refine((v) => distinct(v) && v.join(\"\\0\") === [...v].sort().join(\"\\0\")),\n});\nexport const PublishedToolDescriptorSchema = z.strictObject({\n toolId: IdSchema,\n toolRevisionId: IdSchema,\n name: ToolNameSchema,\n definitionVersion: SemverSchema,\n description: z.string().min(1).max(4096),\n inputSchema: InputSchemaSchema,\n});\nexport const CommerceBuiltInToolNameSchema = z.enum([\n \"commerce_get_discount_options\", \"commerce_get_discount_details\",\n]).meta({maxLength: 29});\nexport const CommerceBuiltInToolGrantSchema = z.strictObject({\n kind: z.enum([\"BUILT_IN\"]).meta({maxLength: 8}),\n toolName: CommerceBuiltInToolNameSchema,\n definitionVersion: z.enum([\"2.0.0\"]).meta({maxLength: 5}),\n});\nexport const CommerceBuiltInToolDescriptorSchema = z.strictObject({\n kind: z.enum([\"BUILT_IN\"]).meta({maxLength: 8}),\n name: CommerceBuiltInToolNameSchema,\n definitionVersion: z.enum([\"2.0.0\"]).meta({maxLength: 5}),\n description: z.string().min(1).max(4096),\n inputSchema: InputSchemaSchema,\n});\nexport type PublishedGrantedTool = z.infer<typeof PublishedGrantedToolSchema>;\nexport type PublishedToolDescriptor = z.infer<typeof PublishedToolDescriptorSchema>;\nexport type CommerceBuiltInToolGrant = z.infer<typeof CommerceBuiltInToolGrantSchema>;\nexport type CommerceBuiltInToolDescriptor = z.infer<typeof CommerceBuiltInToolDescriptorSchema>;\nexport const GrantedToolSchema = z.union([PublishedGrantedToolSchema, CommerceBuiltInToolGrantSchema]);\nexport const ToolDescriptorSchema = z.union([PublishedToolDescriptorSchema, CommerceBuiltInToolDescriptorSchema]);\nexport const GrantedToolsSchema = z.array(GrantedToolSchema).max(32).refine(values => {\n const published = values.filter((value): value is PublishedGrantedTool => !(\"kind\" in value));\n return distinct(values.map(value => value.toolName)) && distinct(published.map(value => value.toolId));\n});\nexport const isBuiltInTool = <T extends GrantedTool | ToolDescriptor>(\n value: T,\n): value is Extract<T, {kind: \"BUILT_IN\"}> => \"kind\" in value && value.kind === \"BUILT_IN\";\n\nconst MappingSchema = z.union([\n z.strictObject({\n input: z.string().refine(safeName),\n omitIfMissing: z.literal(true).optional(),\n }),\n z.strictObject({ literal: boundedJson(8192) }),\n]);\nconst MappingsSchema = z\n .record(z.string().refine(safeName), MappingSchema)\n .refine((v) => Object.keys(v).length <= 32);\nexport const POLICY_OPERATIONS = [\n \"taxonomy.resolveCategories\",\n \"products.search\",\n \"products.get\",\n \"shipping.getInformation\",\n \"recovery.getBasket\",\n \"shopify.searchProducts\",\n \"discounts.getOptions\",\n \"discounts.getDetails\",\n \"discounts.evaluate\",\n \"products.findQualifying\",\n \"products.findSimilar\",\n] as const;\nexport const ExternalHttpExecutionSchema = z\n .strictObject({\n kind: z.literal(\"EXTERNAL_HTTP\"),\n executorVersion: z.literal(\"1.0.0\"),\n connectionRevisionId: IdSchema,\n method: z.literal(\"GET\"),\n path: ExternalPathSchema,\n query: ExternalQueryMappingsSchema,\n responseFormat: ExternalResponseFormatSchema,\n resultPath: z.string().refine((value) => value === \"\" || safePath(value)),\n responseProcessing: ResponseProcessingSchema,\n resultSchema: DetailsSchemaSchema,\n })\n .superRefine((value, ctx) => {\n if (value.responseProcessing.kind === \"JAVASCRIPT\" && value.resultPath !== \"\")\n ctx.addIssue({ code: \"custom\", path: [\"resultPath\"], message: \"JAVASCRIPT processing requires an empty resultPath\" });\n if (value.responseProcessing.kind !== \"JAVASCRIPT\" && value.responseFormat.mode !== \"JSON\")\n ctx.addIssue({ code: \"custom\", path: [\"responseFormat\", \"mode\"], message: \"Visual processing requires JSON\" });\n });\nexport const CommerceExecutionSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"SHOPIFY_STOREFRONT_QUERY\"),\n executorVersion: z.literal(\"1.0.0\"),\n apiVersion: z.literal(\"2026-07\"),\n schemaHash: HashSchema,\n document: z\n .string()\n .min(1)\n .refine((v) => new TextEncoder().encode(v).length <= 16384),\n operationName: z.string().refine(safeName),\n variables: MappingsSchema,\n resultPath: z.string().refine(safePath),\n }),\n z.strictObject({\n kind: z.literal(\"POLICY_OPERATION\"),\n operation: z.enum(POLICY_OPERATIONS),\n operationVersion: z.literal(\"1.0.0\"),\n arguments: MappingsSchema,\n }),\n ExternalHttpExecutionSchema,\n]);\nexport type ExternalHttpExecution = Extract<\n z.infer<typeof CommerceExecutionSchema>,\n { kind: \"EXTERNAL_HTTP\" }\n>;\nfunction tokensValid(text: string, root: \"result\" | \"item\") {\n if (/[<>]/.test(text)) return false;\n const residue = text.replace(/\\{\\{([^{}]+)\\}\\}/g, (_all, path: string) =>\n path.startsWith(root + \".\") && safePath(path.slice(root.length + 1))\n ? \"\"\n : \"{{invalid}}\",\n );\n return !residue.includes(\"{{\") && !residue.includes(\"}}\");\n}\nconst fixed = z\n .string()\n .max(4096)\n .refine((v) => !/[<>]|\\{\\{|\\}\\}/.test(v));\nexport const ResponseTemplateSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"text\"),\n text: z\n .string()\n .max(4096)\n .refine((v) => tokensValid(v, \"result\")),\n unavailable: fixed,\n }),\n z.strictObject({\n kind: z.literal(\"items\"),\n itemsPath: z.string().refine(safePath),\n item: z\n .string()\n .max(4096)\n .refine((v) => tokensValid(v, \"item\")),\n empty: fixed,\n unavailable: fixed,\n }),\n]);\nconst identity = {\n name: ToolNameSchema,\n definitionVersion: SemverSchema,\n description: z.string().min(1).max(4096),\n};\nconst forbiddenInput =\n /^(shopid|customerid|checkoutrecoveryid|conversationid|grantid|releaseid|token|accesstoken|domain|headers|url|graphql|document|authorization)$/i;\nconst forbiddenExternalInput = /^(authorization|cookie|set-cookie|host|x-api-key|api_key|apikey|access_token|token|secret|password)$/i;\nexport const CommerceToolDefinitionSchema = z\n .strictObject({\n ...identity,\n inputSchema: InputSchemaSchema,\n execution: CommerceExecutionSchema,\n responseTemplate: ResponseTemplateSchema,\n })\n .refine(definitionFitsStorage, { message: DEFINITION_SIZE_MESSAGE })\n .superRefine((d, ctx) => {\n const properties = d.inputSchema.properties!;\n const containsAuthority = (schema: SubsetSchema): boolean =>\n Object.entries(schema.properties ?? {}).some(\n ([name, child]) =>\n forbiddenInput.test(name) || containsAuthority(child),\n ) || !!(schema.items && containsAuthority(schema.items));\n if (containsAuthority(d.inputSchema))\n ctx.addIssue({\n code: \"custom\",\n message: \"Authority/credential inputs are forbidden\",\n });\n const mapping =\n d.execution.kind === \"POLICY_OPERATION\"\n ? d.execution.arguments\n : d.execution.kind === \"SHOPIFY_STOREFRONT_QUERY\"\n ? d.execution.variables\n : d.execution.query;\n for (const [name, m] of Object.entries(mapping))\n if (\"input\" in m && !Object.hasOwn(properties, m.input))\n ctx.addIssue({\n code: \"custom\",\n path: [\"execution\", name],\n message: \"Unknown mapped input\",\n });\n if (d.execution.kind === \"EXTERNAL_HTTP\")\n for (const [name, mapping] of Object.entries(d.execution.query))\n if (\"input\" in mapping) {\n const target = properties[mapping.input];\n const type = target && (Array.isArray(target.type) ? target.type[0] : target.type);\n if (forbiddenExternalInput.test(mapping.input) || ![\"string\", \"integer\", \"boolean\"].includes(type ?? \"\"))\n ctx.addIssue({ code: \"custom\", path: [\"execution\", \"query\", name], message: \"External mappings require a top-level scalar input\" });\n }\n });\nconst draftObject = boundedJson(65536).refine(\n (v) => !!v && typeof v === \"object\" && !Array.isArray(v),\n);\nexport const CommerceToolDraftDefinitionSchema = z\n .strictObject({\n ...identity,\n inputSchema: draftObject,\n execution: draftObject,\n responseTemplate: draftObject,\n })\n .refine(definitionFitsStorage, { message: DEFINITION_SIZE_MESSAGE });\nexport type CommerceToolDefinition = z.infer<\n typeof CommerceToolDefinitionSchema\n>;\nexport type CommerceToolDraftDefinition = z.infer<\n typeof CommerceToolDraftDefinitionSchema\n>;\nexport type GrantedTool = z.infer<typeof GrantedToolSchema>;\nexport type ToolDescriptor = z.infer<typeof ToolDescriptorSchema>;\n/** Commerce owns schema-backed GraphQL parsing, restrictions and output derivation. */\nexport interface CommerceDefinitionCompiler {\n compile(\n execution: CommerceToolDefinition[\"execution\"],\n input: SubsetSchema,\n ): {\n outputSchema: SubsetSchema;\n validateMappedArguments: (\n mapping: CommerceToolDefinition[\"execution\"],\n ) => boolean;\n };\n}\nfunction externalOutputSchema(execution: ExternalHttpExecution): SubsetSchema {\n return {\n type: \"object\",\n properties: { values: execution.resultSchema },\n required: [\"values\"],\n additionalProperties: false,\n };\n}\nfunction scalarSchema(schema: SubsetSchema | undefined) {\n const type = schema && (Array.isArray(schema.type) ? schema.type[0] : schema.type);\n return !!schema && [\"string\", \"integer\", \"number\", \"boolean\"].includes(type ?? \"\");\n}\nfunction visualPublicationCompatible(execution: ExternalHttpExecution) {\n if (execution.responseProcessing.kind === \"JAVASCRIPT\") return true;\n const processing = execution.responseProcessing;\n const schema = execution.resultSchema;\n if (processing.kind === \"LIST\") {\n const items = schema.properties?.items;\n if (!items || items.type !== \"array\" || !(schema.required ?? []).includes(\"items\")) return false;\n if (Object.keys(schema.properties ?? {}).some((name) => name !== \"items\")) return false;\n if (items.minItems !== undefined && items.minItems > 0) return false;\n if (items.maxItems !== undefined && items.maxItems < processing.limit) return false;\n }\n const output = processing.kind === \"OBJECT\"\n ? schema\n : schema.properties?.items?.items;\n if (!output || output.type !== \"object\" || !output.properties || output.additionalProperties !== false) return false;\n const fields = processing.fields;\n if (Object.keys(output.properties).some((name) => !Object.hasOwn(fields, name) || !scalarSchema(output.properties![name]))) return false;\n if (Object.keys(fields).some((name) => !Object.hasOwn(output.properties!, name))) return false;\n return (output.required ?? []).every((name) => !fields[name]?.omitIfMissing);\n}\nfunction at(schema: SubsetSchema, path: string) {\n let current: SubsetSchema | undefined = schema;\n for (const part of path.split(\".\")) current = current?.properties?.[part];\n return current;\n}\nexport function validateDefinitionForPublication(\n raw: unknown,\n compiler: CommerceDefinitionCompiler,\n) {\n const definition = CommerceToolDefinitionSchema.parse(raw);\n if (definition.execution.kind === \"EXTERNAL_HTTP\" && !visualPublicationCompatible(definition.execution))\n throw new TypeError(\"External visual projection is incompatible with resultSchema\");\n const compiled =\n definition.execution.kind === \"EXTERNAL_HTTP\"\n ? { outputSchema: externalOutputSchema(definition.execution), validateMappedArguments: () => true }\n : compiler.compile(definition.execution, definition.inputSchema);\n if (!compiled.validateMappedArguments(definition.execution))\n throw new TypeError(\"Invalid variable/operation mapping\");\n const template = definition.responseTemplate;\n const schema =\n template.kind === \"text\"\n ? compiled.outputSchema\n : at(compiled.outputSchema, template.itemsPath)?.items;\n if (!schema) throw new TypeError(\"Unknown template items path\");\n const text = template.kind === \"text\" ? template.text : template.item;\n for (const match of text.matchAll(/\\{\\{(?:result|item)\\.([^{}]+)\\}\\}/g)) {\n const target = at(schema, match[1]);\n const type =\n target && (Array.isArray(target.type) ? target.type[0] : target.type);\n if (!type || [\"object\", \"array\"].includes(type))\n throw new TypeError(\"Unknown or nonscalar template path\");\n }\n return definition;\n}\nexport function definitionToMcpDescriptor(definition: CommerceToolDefinition) {\n const d = CommerceToolDefinitionSchema.parse(definition);\n return {\n name: d.name,\n description: d.description,\n inputSchema: d.inputSchema,\n };\n}\nexport function mapToolArguments(\n definition: CommerceToolDefinition,\n raw: unknown,\n) {\n const input = compileSubset(definition.inputSchema, \"input\").parse(raw);\n const mapping =\n definition.execution.kind === \"POLICY_OPERATION\"\n ? definition.execution.arguments\n : definition.execution.kind === \"SHOPIFY_STOREFRONT_QUERY\"\n ? definition.execution.variables\n : definition.execution.query;\n const result: Record<string, unknown> = Object.create(null);\n for (const [key, m] of Object.entries(mapping)) {\n if (\"literal\" in m) result[key] = m.literal;\n else if (Object.hasOwn(input, m.input)) {\n const value = input[m.input];\n if (definition.execution.kind === \"EXTERNAL_HTTP\" && !ExternalQueryValueSchema.safeParse(value).success)\n throw new TypeError(\"Invalid external mapped scalar\");\n result[key] = value;\n }\n else if (!m.omitIfMissing) throw new TypeError(\"Missing mapped input\");\n }\n return result;\n}\nexport const toolHashInput = (definition: CommerceToolDefinition) => ({\n contractVersion: ContractVersionSchema.value,\n definition: CommerceToolDefinitionSchema.parse(definition),\n});\n/** Publication adapters supply the actual highest published version from persistence. */\nexport function validateDefinitionVersion(\n proposed: string,\n highestPublished: string | null,\n) {\n SemverSchema.parse(proposed);\n if (highestPublished === null) return proposed === \"1.0.0\";\n SemverSchema.parse(highestPublished);\n return gt(proposed, highestPublished);\n}\nexport const CommerceToolIdentitySchema = z.strictObject({\n id: IdSchema,\n name: ToolNameSchema,\n enabled: z.boolean(),\n});\nexport const CommerceToolRevisionIdentitySchema = z.strictObject({\n toolId: IdSchema,\n toolRevisionId: IdSchema,\n definitionVersion: SemverSchema,\n contentHash: HashSchema,\n});\nexport const POLICY_OPERATION_DESCRIPTORS = POLICY_OPERATIONS.map(\n (operation) => ({ operation, operationVersion: \"1.0.0\" as const }),\n);\n","import { canonicalJson } from \"./canonical-json\";\n\n/** Bytes of PostgreSQL jsonb::text for JSON.stringify-serialized values.\n * jsonb adds spaces after separators and expands exponent-form JSON numbers.\n * Key ordering changes no byte counts. This is not the canonical hash encoder.\n */\nexport function definitionStorageBytes(value: unknown): number {\n const normalized: unknown = JSON.parse(canonicalJson(value));\n const bytes = (s: string) => new TextEncoder().encode(s).length;\n function size(v: unknown): number {\n if (typeof v === \"number\") {\n const text = JSON.stringify(v);\n if (!text.includes(\"e\")) return text.length;\n const [coefficient, exponent] = text.split(\"e\");\n const sign = coefficient.startsWith(\"-\") ? 1 : 0;\n const unsigned = coefficient.slice(sign);\n const digits = unsigned.replace(\".\", \"\").length;\n const point =\n (unsigned.indexOf(\".\") < 0 ? unsigned.length : unsigned.indexOf(\".\")) +\n Number(exponent);\n return (\n sign +\n (point <= 0 ? 2 - point + digits : point >= digits ? point : digits + 1)\n );\n }\n if (Array.isArray(v))\n return (\n 2 +\n Math.max(0, v.length - 1) * 2 +\n v.reduce((sum, item) => sum + size(item), 0)\n );\n if (v && typeof v === \"object\") {\n const entries = Object.entries(v);\n return (\n 2 +\n Math.max(0, entries.length - 1) * 2 +\n entries.reduce(\n (sum, [key, item]) =>\n sum + bytes(JSON.stringify(key)) + 2 + size(item),\n 0,\n )\n );\n }\n return bytes(JSON.stringify(v));\n }\n return size(normalized);\n}\nexport const definitionFitsStorage = (value: unknown): boolean => {\n try {\n return definitionStorageBytes(value) <= 65536;\n } catch {\n return false;\n }\n};\nexport const DEFINITION_SIZE_MESSAGE =\n \"Definition exceeds the 65536-byte jsonb text limit\";\n","import { canonicalJson } from \"./canonical-json\";\nimport type { CommerceBuiltInToolDescriptor, CommerceBuiltInToolGrant } from \"./definitions\";\n\nfunction immutable<T extends object>(value: T): T {\n for (const child of Object.values(value))\n if (child && typeof child === \"object\") immutable(child);\n return Object.freeze(value);\n}\n\n/** Code-owned descriptors with stable name/version identities. */\nexport const commerceDiscountBuiltInDescriptors: readonly CommerceBuiltInToolDescriptor[] = immutable<CommerceBuiltInToolDescriptor[]>([\n {\n kind: \"BUILT_IN\", name: \"commerce_get_discount_options\", definitionVersion: \"2.0.0\",\n description: \"Read the current shop's permitted discount options.\",\n inputSchema: {\n type: \"object\", properties: {\n limit: {type: \"integer\", minimum: 1, maximum: 50},\n cursor: {type: [\"string\", \"null\"], maxLength: 2048},\n }, additionalProperties: false,\n },\n },\n {\n kind: \"BUILT_IN\", name: \"commerce_get_discount_details\", definitionVersion: \"2.0.0\",\n description: \"Read details for a permitted discount in the current shop.\",\n inputSchema: {\n type: \"object\", properties: {offerId: {type: \"string\", minLength: 1, maxLength: 128}},\n required: [\"offerId\"], additionalProperties: false,\n },\n },\n]);\n\nexport function isTrustedCommerceBuiltInDescriptor(value: CommerceBuiltInToolDescriptor): boolean {\n return commerceDiscountBuiltInDescriptors.some(expected => canonicalJson(expected) === canonicalJson(value));\n}\nexport function isTrustedCommerceBuiltInGrant(value: CommerceBuiltInToolGrant): boolean {\n return commerceDiscountBuiltInDescriptors.some(expected =>\n value.toolName === expected.name && value.definitionVersion === expected.definitionVersion);\n}\n","import { z } from \"zod\";\nimport { IdSchema, LanguageSchema } from \"./primitives\";\nimport { DetailsSchemaSchema, compileSubset, type Json } from \"./subset\";\nimport {\n jsonBytes,\n responseContractCanonicalJson,\n type Digest,\n} from \"./canonical-json\";\nimport { canonicaliseLanguageTag } from \"../internationalization\";\nexport const CommerceResponseContractSchema = z\n .strictObject({\n version: z.literal(\"response.v1\"),\n instructions: z.string().min(1).max(8000),\n detailsSchema: DetailsSchemaSchema,\n })\n .refine((v) => jsonBytes(v) <= 32768);\nexport type CommerceResponseContract = z.infer<\n typeof CommerceResponseContractSchema\n>;\nexport const EMPTY_RESPONSE_CONTRACT: CommerceResponseContract = {\n version: \"response.v1\",\n instructions:\n \"Write a concise, natural WhatsApp reply supported by the available facts. Return an empty details object.\",\n detailsSchema: {\n type: \"object\",\n properties: {},\n required: [],\n additionalProperties: false,\n },\n};\nexport const ReferralReasonSchema = z.enum([\n \"INSUFFICIENT_TOOLS\",\n \"UNVERIFIABLE_FACTS\",\n \"TOOL_UNAVAILABLE\",\n \"TOOL_REVOKED\",\n]);\n\nconst DetectedLanguageTagSchema = z\n .string()\n .min(1)\n .max(128)\n .transform((value, ctx) => {\n const canonical = canonicaliseLanguageTag(value);\n\n if (!canonical) {\n ctx.addIssue({\n code: \"custom\",\n message: \"Invalid detected language tag\",\n });\n return z.NEVER;\n }\n\n return canonical;\n });\n\nexport const CommerceFinalResponseSchema = z\n .strictObject({\n answerKind: z.enum([\"ANSWER\", \"REFER_TO_STORE\"]),\n replyText: z.string().min(1).max(4096),\n referralReason: ReferralReasonSchema.nullable(),\n detectedLanguageTag: DetectedLanguageTagSchema.nullable(),\n detectedLanguageConfidence: z.number().min(0).max(1).nullable(),\n evidenceIds: z\n .array(IdSchema)\n .max(3)\n .refine((v) => new Set(v).size === v.length),\n details: z.record(z.string(), z.unknown()).refine((v) => {\n try {\n return jsonBytes(v) <= 16384;\n } catch {\n return false;\n }\n }),\n })\n .superRefine((value, ctx) => {\n\n if (value.answerKind === \"ANSWER\") {\n if (value.referralReason !== null) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"referralReason\"],\n message: \"ANSWER must not include a referral reason\",\n });\n }\n }\n\n if (value.answerKind === \"REFER_TO_STORE\") {\n if (value.referralReason === null) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"referralReason\"],\n message: \"REFER_TO_STORE requires a referral reason\",\n });\n }\n\n if (value.evidenceIds.length !== 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"evidenceIds\"],\n message: \"REFER_TO_STORE must not include evidence\",\n });\n }\n\n if (Object.keys(value.details).length !== 0) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"details\"],\n message: \"REFER_TO_STORE must not include details\",\n });\n }\n }\n });\nexport type CommerceFinalResponse = z.infer<typeof CommerceFinalResponseSchema>;\nexport function finalResponseSchema(definition: CommerceResponseContract) {\n const contract = CommerceResponseContractSchema.parse(definition);\n const details = compileSubset(contract.detailsSchema, \"details\");\n return CommerceFinalResponseSchema.refine(\n (v) =>\n v.answerKind === \"REFER_TO_STORE\" || details.safeParse(v.details).success,\n {\n path: [\"details\"],\n message: \"Details do not match pinned contract\",\n },\n );\n}\nexport function verifyResponseContract(\n definition: unknown,\n hash: string,\n digest: Digest,\n) {\n const parsed = CommerceResponseContractSchema.parse(definition);\n if (\n !/^[a-f0-9]{64}$/.test(hash) ||\n digest(responseContractCanonicalJson(parsed)) !== hash\n )\n throw new TypeError(\"Incompatible response contract\");\n return parsed;\n}\n/** JSON Schema branches retain the immutable envelope; only ANSWER details vary. */\nexport function finalResponseToolSchema(definition: CommerceResponseContract) {\n const contract = CommerceResponseContractSchema.parse(definition);\n const properties = {\n answerKind: { enum: [\"ANSWER\", \"REFER_TO_STORE\"] },\n replyText: { type: \"string\", minLength: 1, maxLength: 4096 },\n referralReason: {\n enum: [\n null,\n \"INSUFFICIENT_TOOLS\",\n \"UNVERIFIABLE_FACTS\",\n \"TOOL_UNAVAILABLE\",\n \"TOOL_REVOKED\",\n ],\n },\n detectedLanguageTag: { type: [\"string\", \"null\"], maxLength: 128 },\n detectedLanguageConfidence: {\n type: [\"number\", \"null\"],\n minimum: 0,\n maximum: 1,\n },\n evidenceIds: {\n type: \"array\",\n maxItems: 3,\n uniqueItems: true,\n items: { type: \"string\", maxLength: 128 },\n },\n details: { type: \"object\" },\n };\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n allOf: [\n {\n oneOf: [\n {\n properties: {\n answerKind: { const: \"ANSWER\" },\n referralReason: { type: \"null\" },\n details: contract.detailsSchema,\n },\n },\n {\n properties: {\n answerKind: { const: \"REFER_TO_STORE\" },\n referralReason: { enum: ReferralReasonSchema.options },\n evidenceIds: { maxItems: 0 },\n details: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n },\n },\n ],\n },\n {\n oneOf: [\n {\n properties: {\n detectedLanguageTag: { type: \"null\" },\n detectedLanguageConfidence: { type: \"null\" },\n },\n },\n {\n properties: {\n detectedLanguageTag: { type: \"string\" },\n detectedLanguageConfidence: { type: \"number\" },\n },\n },\n ],\n },\n ],\n } as unknown as Json;\n}\n","import { z } from \"zod\";\nimport { validRange } from \"semver\";\nimport {\n ContractVersionSchema as V,\n IdSchema as ID,\n SemverSchema,\n HashSchema,\n DateSchema,\n MoneySchema,\n CurrencySchema,\n distinct,\n boundedJson,\n} from \"./primitives\";\nimport { GrantedToolsSchema, PublishedToolDescriptorSchema, CommerceBuiltInToolDescriptorSchema, isBuiltInTool, type PublishedGrantedTool } from \"./definitions\";\nimport { isTrustedCommerceBuiltInDescriptor, isTrustedCommerceBuiltInGrant } from \"./built-in-tools\";\nimport { CommerceResponseContractSchema } from \"./response\";\nimport { canonicalJson, jsonBytes } from \"./canonical-json\";\nexport const CommerceTurnIdentitySchema = z.strictObject({\n contractVersion: V,\n shopId: ID,\n checkoutRecoveryId: ID,\n conversationId: ID,\n inboundVersion: z.number().int().positive(),\n});\nexport type CommerceTurnIdentity = z.infer<typeof CommerceTurnIdentitySchema>;\nexport const CommerceConversationGrantSchema = z\n .strictObject({\n id: ID,\n shopId: ID,\n conversationId: ID,\n initialInboundVersion: z.number().int().positive(),\n releaseId: ID,\n selectedCapabilityKeys: z\n .array(ID)\n .max(32)\n .refine(distinct),\n grantedTools: GrantedToolsSchema,\n runnerVersion: SemverSchema,\n createdAt: DateSchema,\n expiresAt: DateSchema.nullable(),\n })\n .superRefine((v, c) => {\n if (v.expiresAt && Date.parse(v.expiresAt) <= Date.parse(v.createdAt))\n c.addIssue({ code: \"custom\", message: \"Invalid grant retention date\" });\n if (\n jsonBytes(v.grantedTools) > 65536 ||\n jsonBytes(v.selectedCapabilityKeys) > 8192 ||\n v.grantedTools.some((t) =>\n isBuiltInTool(t) ? !isTrustedCommerceBuiltInGrant(t) : t.capabilityKeys.some((k) => !v.selectedCapabilityKeys.includes(k)),\n )\n )\n c.addIssue({ code: \"custom\", message: \"Unselected grant provenance\" });\n });\nexport type CommerceConversationGrant = z.infer<\n typeof CommerceConversationGrantSchema\n>;\nexport const CommerceManifestSchema = z\n .strictObject({\n contractVersion: V,\n releaseId: ID,\n runnerCompatibility: z\n .string()\n .min(1)\n .max(128)\n .refine((v) => !!validRange(v)),\n capabilities: z\n .array(\n z.strictObject({\n capabilityId: ID,\n key: ID,\n featureId: ID,\n position: z.number().int().nonnegative(),\n toolDescriptor: PublishedToolDescriptorSchema,\n }),\n )\n .max(32),\n featureBehaviours: z\n .array(\n z.strictObject({\n featureId: ID,\n behaviourPrompt: z.string().max(32000),\n }),\n )\n .max(32),\n selectedCapabilityKeys: z.array(ID).max(32).refine(distinct),\n builtInTools: z.array(CommerceBuiltInToolDescriptorSchema).max(2).default([]),\n grantedTools: GrantedToolsSchema,\n responseContract: CommerceResponseContractSchema,\n responseContractHash: HashSchema,\n })\n .superRefine((v, c) => {\n if (jsonBytes(v) > 262144)\n c.addIssue({ code: \"custom\", message: \"Manifest exceeds output limit\" });\n const keys = v.capabilities.map((x) => x.key);\n const capabilityIds = v.capabilities.map((x) => x.capabilityId);\n const representedFeatures = [...new Set(v.capabilities.map((x) => x.featureId))];\n const behaviourFeatureIds = v.featureBehaviours.map((x) => x.featureId);\n if (\n !distinct(keys) ||\n !distinct(capabilityIds) ||\n JSON.stringify(keys) !== JSON.stringify(v.selectedCapabilityKeys) ||\n v.capabilities.some(\n (x, i) => i > 0 && x.position <= v.capabilities[i - 1].position,\n ) ||\n !distinct(behaviourFeatureIds) ||\n JSON.stringify(representedFeatures) !== JSON.stringify(behaviourFeatureIds)\n )\n c.addIssue({\n code: \"custom\",\n message: \"Invalid capability ordering/selection\",\n });\n const union = new Map<\n string,\n { tool: PublishedGrantedTool; descriptor: string }\n >();\n for (const cap of v.capabilities) {\n const d = cap.toolDescriptor;\n const old = union.get(d.toolId);\n const descriptor = canonicalJson(d);\n if (old) {\n if (old.descriptor !== descriptor)\n c.addIssue({\n code: \"custom\",\n message: \"Conflicting tool revisions/descriptors\",\n });\n old.tool.capabilityKeys.push(cap.key);\n } else\n union.set(d.toolId, {\n descriptor,\n tool: {\n toolId: d.toolId,\n toolRevisionId: d.toolRevisionId,\n toolName: d.name,\n definitionVersion: d.definitionVersion,\n capabilityKeys: [cap.key],\n },\n });\n }\n if (\n union.size + v.builtInTools.length !== v.grantedTools.length ||\n !distinct(v.builtInTools.map(tool => tool.name)) ||\n v.builtInTools.some(tool => !isTrustedCommerceBuiltInDescriptor(tool)) ||\n v.grantedTools.some((t) => {\n if (isBuiltInTool(t)) return !v.builtInTools.some(descriptor =>\n descriptor.name === t.toolName && descriptor.definitionVersion === t.definitionVersion &&\n isTrustedCommerceBuiltInGrant(t));\n const expected = union.get(t.toolId)?.tool;\n return (\n !expected ||\n expected.toolRevisionId !== t.toolRevisionId ||\n expected.toolName !== t.toolName ||\n expected.definitionVersion !== t.definitionVersion ||\n JSON.stringify([...new Set(expected.capabilityKeys)].sort()) !==\n JSON.stringify(t.capabilityKeys)\n );\n })\n )\n c.addIssue({\n code: \"custom\",\n message: \"Grant must equal selected capability set\",\n });\n });\nexport type CommerceManifest = z.infer<typeof CommerceManifestSchema>;\nexport const CommerceReleaseIdentitySchema = z.strictObject({\n contractVersion: V,\n releaseId: ID,\n runnerCompatibility: z\n .string()\n .min(1)\n .max(128)\n .refine((v) => !!validRange(v)),\n});\nexport const CommerceResolveAssertionSchema = CommerceTurnIdentitySchema.extend(\n { purpose: z.literal(\"resolve\") },\n);\nexport const CommerceExecuteAssertionSchema = CommerceTurnIdentitySchema.extend(\n { purpose: z.literal(\"execute\"), grantId: ID, releaseId: ID },\n);\nexport const CommerceAssertionSchema = z.discriminatedUnion(\"purpose\", [\n CommerceResolveAssertionSchema,\n CommerceExecuteAssertionSchema,\n]);\nconst qty = z.number().int().min(1).max(999);\nexport const CommerceProposalSchema = z\n .strictObject({\n operations: z\n .array(\n z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"ADD\"),\n variantId: ID,\n quantity: qty,\n }),\n z.strictObject({\n kind: z.literal(\"REPLACE\"),\n lineId: ID,\n variantId: ID,\n quantity: qty,\n }),\n ]),\n )\n .min(1)\n .max(3),\n })\n .refine((v) =>\n distinct(\n v.operations.flatMap((o) => (o.kind === \"REPLACE\" ? [o.lineId] : [])),\n ),\n );\nexport const CommerceBasketSchema = z\n .strictObject({\n basketId: ID,\n source: z.enum([\"RECOVERY_SNAPSHOT\", \"PROPOSED\"]),\n observedAt: DateSchema,\n currency: CurrencySchema.nullable(),\n lines: z\n .array(\n z.strictObject({\n lineId: ID,\n productId: ID.nullable(),\n variantId: ID.nullable(),\n quantity: qty.nullable(),\n unitPrice: MoneySchema.nullable(),\n }),\n )\n .max(100),\n fingerprint: HashSchema,\n unknownFields: z.array(z.string().min(1).max(256)).max(128),\n })\n .refine((v) => distinct(v.lines.map((line) => line.lineId)));\nexport const CommerceProductSaleEvidenceSchema = z.strictObject({\n regularPrice: MoneySchema.nullable(),\n salePrice: MoneySchema.nullable(),\n observedAt: DateSchema,\n});\nexport type CommerceProductSaleEvidence =\n z.infer<typeof CommerceProductSaleEvidenceSchema>;\n\nexport const CommerceProductSchema = z.strictObject({\n productId: ID,\n variantId: ID.nullable(),\n title: z.string().min(1).max(512),\n url: z\n .url({ protocol: /^https$/ })\n .refine((v) => {\n const u = new URL(v);\n return !u.username && !u.password && !u.port;\n })\n .nullable(),\n available: z.boolean().nullable(),\n unitPrice: MoneySchema.nullable(),\n currency: CurrencySchema.nullable(),\n productType: z.string().max(512).nullable(),\n vendor: z.string().max(512).nullable(),\n categories: z.array(z.string()).optional(),\n categoryIds: z.array(ID).max(128).optional(),\n collectionIds: z.array(ID).max(128).optional(),\n imageUrl: z.string().nullable().optional(),\n saleEvidence: CommerceProductSaleEvidenceSchema.nullable().optional(),\n observedAt: DateSchema,\n});\n// Discount outputs own their UTC wire syntax; general DateSchema remains unchanged.\n// The final lookahead requires absolute end-of-input (unlike JavaScript's $).\nconst discountUtcPattern = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.[0-9]+)?Z(?![\\s\\S])/;\nconst CommerceDiscountDateTimeSchema = z.string().regex(discountUtcPattern).refine(value => {\n const match = discountUtcPattern.exec(value);\n if (!match) return false;\n const [year, month, day, hour, minute, second] = match.slice(1).map(Number);\n if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59) return false;\n const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n return day >= 1 && day <= daysInMonth[month - 1];\n}, \"Expected a valid UTC discount timestamp with seconds\");\n\nexport const CommerceOfferSchema = z\n .strictObject({\n offerId: ID,\n title: z.string().min(1).max(512),\n method: z.enum([\"AUTOMATIC\", \"CODE\"]),\n code: z.string().min(1).max(128).nullable(),\n startsAt: CommerceDiscountDateTimeSchema.nullable(),\n endsAt: CommerceDiscountDateTimeSchema.nullable(),\n support: z.enum([\"SUPPORTED\", \"UNSUPPORTED\", \"UNKNOWN\"]),\n reasonCodes: z.array(z.string().min(1).max(64)).max(16),\n })\n .refine(\n (v) =>\n (v.startsAt === null ||\n v.endsAt === null ||\n Date.parse(v.startsAt) < Date.parse(v.endsAt)) &&\n (v.method !== \"AUTOMATIC\" || v.code === null),\n );\nexport const CommerceDiscountCombinationFactsSchema = z.strictObject({\n discountClasses: z.array(z.enum([\"ORDER\", \"PRODUCT\", \"SHIPPING\"])).max(3).nullable(),\n shopifyPlus: z.boolean().nullable(),\n combinesWith: z.strictObject({\n orderDiscounts: z.boolean().nullable(),\n productDiscounts: z.boolean().nullable(),\n shippingDiscounts: z.boolean().nullable(),\n }).nullable(),\n discountTags: z.array(z.string().min(1).max(128)).max(64).nullable(),\n allowedSameLineProductTags: z.array(z.string().min(1).max(128)).max(64).nullable(),\n});\nexport type CommerceDiscountCombinationFacts = z.infer<\n typeof CommerceDiscountCombinationFactsSchema\n>;\nexport const CommerceDiscountConditionFactsSchema = z.strictObject({\n provider: z.enum([\"SHOPIFY\", \"WOOCOMMERCE\"]),\n completeness: z.enum([\"COMPLETE\", \"PARTIAL\", \"UNKNOWN\"]),\n observedAt: CommerceDiscountDateTimeSchema,\n providerStatus: z.string().max(64),\n unavailableAt: CommerceDiscountDateTimeSchema.nullable(),\n discountKind: z.enum([\n \"PERCENTAGE\",\n \"FIXED_AMOUNT\",\n \"FREE_SHIPPING\",\n \"BUY_X_GET_Y\",\n \"OTHER\",\n \"UNKNOWN\",\n ]),\n discountValue: MoneySchema.nullable(),\n discountCurrency: CurrencySchema.nullable(),\n targeting: z.strictObject({\n kind: z.enum([\n \"ALL\",\n \"PRODUCTS\",\n \"VARIANTS\",\n \"CATEGORIES\",\n \"COLLECTIONS\",\n \"MIXED\",\n \"UNKNOWN\",\n ]),\n includedProductIds: z.array(ID).max(128),\n includedVariantIds: z.array(ID).max(128),\n includedCategoryIds: z.array(ID).max(128),\n includedCollectionIds: z.array(ID).max(128),\n excludedProductIds: z.array(ID).max(128),\n excludedVariantIds: z.array(ID).max(128),\n excludedCategoryIds: z.array(ID).max(128),\n excludedCollectionIds: z.array(ID).max(128),\n }),\n minimumSubtotal: MoneySchema.nullable(),\n maximumSubtotal: MoneySchema.nullable(),\n subtotalRequirementCurrency: CurrencySchema.nullable(),\n minimumQuantity: z.number().int().nonnegative().nullable(),\n usageLimit: z.number().int().nonnegative().nullable(),\n usageCount: z.number().int().nonnegative().nullable(),\n perCustomerLimit: z.number().int().nonnegative().nullable(),\n customerScope: z.enum([\"ALL\", \"RESTRICTED\", \"UNKNOWN\"]),\n excludesSaleItems: z.boolean().nullable(),\n individualUse: z.boolean().nullable(),\n combination: CommerceDiscountCombinationFactsSchema,\n unrepresentedConditions: z.array(z.string().min(1).max(128)).max(24),\n});\nexport type CommerceDiscountConditionFacts = z.infer<\n typeof CommerceDiscountConditionFactsSchema\n>;\nexport const CommerceDiscountDetailsSchema = z.strictObject({\n offer: CommerceOfferSchema,\n facts: CommerceDiscountConditionFactsSchema,\n providerDiscountId: z.string().min(1).max(191).nullable(),\n});\nexport type CommerceDiscountDetails = z.infer<\n typeof CommerceDiscountDetailsSchema\n>;\nconst condition = z.strictObject({\n code: z.string().min(1).max(64),\n description: z.string().max(256),\n});\nexport const CommerceEvidenceSchema = z\n .strictObject({\n evidenceId: HashSchema,\n turn: CommerceTurnIdentitySchema,\n grantId: ID,\n releaseId: ID,\n offerId: ID,\n proposal: CommerceProposalSchema.nullable(),\n basketFingerprint: HashSchema,\n ruleFingerprint: HashSchema,\n evaluatedAt: DateSchema,\n expiresAt: DateSchema,\n outcome: z.enum([\n \"QUALIFIES_FOR_KNOWN_RULES\",\n \"DOES_NOT_QUALIFY\",\n \"UNKNOWN\",\n \"UNSUPPORTED\",\n ]),\n currency: CurrencySchema.nullable(),\n savings: MoneySchema.nullable(),\n resultingTotal: MoneySchema.nullable(),\n evaluatedConditions: z.array(condition).max(32),\n unresolvedConditions: z.array(condition).max(32),\n })\n .superRefine((v, c) => {\n if (Date.parse(v.expiresAt) - Date.parse(v.evaluatedAt) > 60000)\n c.addIssue({\n code: \"custom\",\n message: \"Evidence lifetime exceeds ceiling\",\n });\n if (\n v.outcome === \"QUALIFIES_FOR_KNOWN_RULES\" &&\n (v.unresolvedConditions.length ||\n Date.parse(v.expiresAt) <= Date.parse(v.evaluatedAt) ||\n v.currency === null ||\n v.savings === null ||\n v.resultingTotal === null)\n )\n c.addIssue({ code: \"custom\", message: \"Unsupported qualifying claim\" });\n });\nexport type CommerceEvidence = z.infer<typeof CommerceEvidenceSchema>;\nexport const CommerceAlternativeSchema = z\n .strictObject({\n product: CommerceProductSchema,\n proposal: CommerceProposalSchema,\n extraSpend: MoneySchema.nullable(),\n resultingTotal: MoneySchema.nullable(),\n currency: CurrencySchema.nullable(),\n evidence: CommerceEvidenceSchema.nullable(),\n similarityReasons: z.array(z.string().max(256)).max(3),\n })\n .refine((v) => v.product.available === true);\nexport const CommerceErrorCodeSchema = z.enum([\n \"INVALID_INPUT\",\n \"DENIED\",\n \"STALE_TURN\",\n \"NOT_FOUND\",\n \"UNAVAILABLE\",\n \"THROTTLED\",\n \"DEADLINE\",\n \"INCOMPATIBLE_VERSION\",\n]);\nexport function commerceToolResultSchema<T extends z.ZodType>(data: T) {\n return z.union([\n z.strictObject({\n contractVersion: V,\n status: z.literal(\"OK\"),\n data,\n renderedText: z.string().max(4096),\n }),\n z.strictObject({\n contractVersion: V,\n status: z.literal(\"ERROR\"),\n code: CommerceErrorCodeSchema,\n retryable: z.boolean(),\n renderedText: z.string().max(4096).optional(),\n }),\n ]);\n}\nexport const CommerceToolResultSchema = commerceToolResultSchema(\n boundedJson(262144),\n);\nexport type CommerceToolResult = z.infer<typeof CommerceToolResultSchema>;\nconst wireId = z.string().min(1).max(128);\nconst taxonomySource = z.enum([\"SHOPIFY_STANDARD_PRODUCT_TAXONOMY\"]).meta({maxLength: 33});\nexport const CommerceCategoryCandidateSchema = z.strictObject({\n categoryId: wireId,\n name: z.string().min(1).max(512),\n fullName: z.string().min(1).max(4096),\n parentId: wireId.nullable(),\n level: z.number().int().min(0).max(32),\n ancestorIds: z.array(wireId).max(32),\n distance: z.number().min(0).max(2),\n});\nexport type CommerceCategoryCandidate = z.infer<typeof CommerceCategoryCandidateSchema>;\nexport const CommerceCategoryResolutionSchema = z.union([\n z.strictObject({\n outcome: z.enum([\"CANDIDATES\", \"NO_CANDIDATES\"]).meta({maxLength: 13}),\n generationId: wireId,\n source: taxonomySource,\n taxonomyVersion: z.string().min(1).max(64),\n languageTag: z.string().min(1).max(35),\n candidates: z.array(CommerceCategoryCandidateSchema).max(10),\n }),\n z.strictObject({\n outcome: z.enum([\"UNAVAILABLE\"]).meta({maxLength: 11}),\n reasonCode: z.enum([\"NOT_READY\", \"TEMPORARY_UNAVAILABLE\"]).meta({maxLength: 21}),\n }),\n]);\nexport type CommerceCategoryResolution = z.infer<typeof CommerceCategoryResolutionSchema>;\nexport const CommerceOptionalLookupUnavailableSchema = z.strictObject({\n outcome: z.enum([\"UNAVAILABLE\"]).meta({maxLength: 11}),\n reasonCode: z.enum([\"TEMPORARY_UNAVAILABLE\"]).meta({maxLength: 21}),\n});\nexport type CommerceOptionalLookupUnavailable = z.infer<typeof CommerceOptionalLookupUnavailableSchema>;\nexport const CommerceProductRecommendationSelectionSchema = z.strictObject({\n productRecommendationVersion: z.enum([\"1\"]).meta({maxLength: 1}).optional(),\n productRecommendations: z.array(z.strictObject({\n scope: z.enum([\"PRODUCT_ONLY\", \"ADD_TO_BASKET\", \"REPLACE_BASKET_LINE\"]).meta({maxLength: 19}),\n basketLineId: wireId.nullable(),\n productId: wireId,\n variantId: wireId.nullable(),\n quantity: z.number().int().min(1).max(99),\n promotionKind: z.enum([\"NONE\", \"NATIVE_SALE\", \"DISCOUNT\"]).meta({maxLength: 11}),\n offerIds: z.array(wireId).max(3),\n })).min(1).max(3).optional(),\n});\nexport type CommerceProductRecommendationSelection = z.infer<typeof CommerceProductRecommendationSelectionSchema>;\nexport const CommerceResponseDispositionSchema = z.enum([\n \"STANDARD\", \"OUT_OF_SCOPE_REDIRECT\", \"SHIPPING_INFORMATION_UNVERIFIED\",\n]).meta({maxLength: 31});\nexport type CommerceResponseDisposition = z.infer<typeof CommerceResponseDispositionSchema>;\nexport const CommerceAnswerPresentationSelectionSchema = z.strictObject({\n responseDisposition: CommerceResponseDispositionSchema.optional(),\n shippingInformationSelection: z.strictObject({\n productId: wireId.nullable(),\n variantId: wireId.nullable(),\n }).optional(),\n});\nexport type CommerceAnswerPresentationSelection = z.infer<typeof CommerceAnswerPresentationSelectionSchema>;\nexport const CommerceShippingInformationInputSchema = z.strictObject({\n productId: wireId.nullable().default(null),\n variantId: wireId.nullable().default(null),\n});\nexport type CommerceShippingInformationInput = z.infer<typeof CommerceShippingInformationInputSchema>;\n// Relationships, current-shop ownership and policy UTF-8 budgets belong to the adapter.\nexport const CommerceShippingInformationSchema = z.strictObject({\n provider: z.enum([\"SHOPIFY\", \"WOOCOMMERCE\"]).meta({maxLength: 11}),\n observedAt: DateSchema,\n product: z.strictObject({\n status: z.enum([\"NOT_REQUESTED\", \"VARIANT_REQUIRED\", \"AVAILABLE\"]).meta({maxLength: 16}),\n productId: wireId.nullable(),\n variantId: wireId.nullable(),\n requiresShipping: z.boolean().nullable(),\n virtual: z.boolean().nullable(),\n weight: z.strictObject({\n value: z.number().min(0),\n unit: z.enum([\"GRAMS\", \"KILOGRAMS\", \"OUNCES\", \"POUNDS\"]).meta({maxLength: 9}).nullable(),\n }).nullable(),\n dimensions: z.strictObject({\n length: z.number().min(0).nullable(),\n width: z.number().min(0).nullable(),\n height: z.number().min(0).nullable(),\n unit: z.string().min(1).max(16).nullable(),\n }).nullable(),\n shippingClassId: wireId.nullable(),\n shippingClassSlug: z.string().min(1).max(512).nullable(),\n }),\n policy: z.strictObject({\n status: z.enum([\"AVAILABLE\", \"NOT_CONFIGURED\", \"SCOPE_NOT_GRANTED\", \"UNSUPPORTED\"]).meta({maxLength: 17}),\n trust: z.enum([\"UNTRUSTED_REFERENCE\"]).meta({maxLength: 19}),\n title: z.string().min(1).max(512).nullable(),\n bodyStatus: z.enum([\"AVAILABLE\", \"EMPTY\", \"TOO_LARGE\", \"NOT_AVAILABLE\"]).meta({maxLength: 13}),\n bodyHtml: z.string().min(1).max(8000).nullable(),\n url: z.url({protocol: /^https$/}).min(1).max(2048).nullable(),\n updatedAt: DateSchema.nullable(),\n }),\n});\nexport type CommerceShippingInformation = z.infer<typeof CommerceShippingInformationSchema>;\nconst limit = z.number().int().min(1).max(3).default(3);\nexport const CommerceToolInputs = {\n commerce_resolve_product_categories: z.strictObject({\n query: z.string().min(1).max(200),\n limit: z.number().int().min(1).max(10).default(5),\n }),\n commerce_get_shipping_information: CommerceShippingInformationInputSchema,\n commerce_get_basket: z.strictObject({}),\n commerce_search_products: z.strictObject({\n query: z.string().min(1).max(200).nullable().default(null),\n category: z.strictObject({\n system: z.enum([\"SHOPIFY_STANDARD_PRODUCT_TAXONOMY\", \"WOOCOMMERCE_PRODUCT_CATEGORY\"]).meta({maxLength: 33}),\n id: wireId,\n taxonomyVersion: z.string().min(1).max(64).nullable(),\n }).optional(),\n browse: z.boolean().default(false),\n maximumPrice: MoneySchema.optional(),\n availableOnly: z.boolean().default(true),\n limit: z.number().int().min(1).max(20).default(10),\n cursor: z.string().max(2048).nullable().default(null),\n }),\n commerce_get_product: z.strictObject({\n productId: ID,\n variantId: ID.nullable(),\n }),\n commerce_get_discount_options: z.strictObject({\n limit: z.number().int().min(1).max(50).default(20),\n cursor: z.string().max(2048).nullable().default(null),\n }),\n commerce_get_discount_details: z.strictObject({ offerId: ID }),\n commerce_evaluate_discount: z.strictObject({\n offerId: ID,\n proposal: CommerceProposalSchema.nullable(),\n }),\n commerce_find_qualifying_products: z.strictObject({\n offerId: ID,\n query: z.string().min(1).max(200).nullable(),\n limit,\n }),\n commerce_find_similar_products: z.strictObject({\n variantId: ID,\n offerId: ID.nullable(),\n limit,\n }),\n};\nconst alternatives = z.strictObject({\n alternatives: z.array(CommerceAlternativeSchema).max(3),\n truncated: z.boolean(),\n});\nexport const CommerceToolOutputs = {\n commerce_resolve_product_categories: CommerceCategoryResolutionSchema,\n commerce_get_shipping_information: CommerceShippingInformationSchema,\n commerce_get_basket: CommerceBasketSchema,\n commerce_search_products: z.strictObject({\n products: z.array(CommerceProductSchema).max(20),\n cursor: z.string().max(2048).nullable(),\n truncated: z.boolean(),\n }),\n commerce_get_product: z.strictObject({\n product: CommerceProductSchema.nullable(),\n }),\n commerce_get_discount_options: z.union([CommerceOptionalLookupUnavailableSchema, z.strictObject({\n mode: z.enum([\"NONE\", \"FIXED\", \"AI_BEST_APPLICABLE\"]),\n offers: z.array(CommerceOfferSchema).max(50),\n truncated: z.boolean(),\n cursor: z.string().max(2048).nullable().optional(),\n })]),\n commerce_get_discount_details: z.union([CommerceOptionalLookupUnavailableSchema, z.strictObject({\n details: CommerceDiscountDetailsSchema.nullable(),\n })]),\n commerce_evaluate_discount: CommerceEvidenceSchema,\n commerce_find_qualifying_products: alternatives,\n commerce_find_similar_products: alternatives,\n};\nexport function productBelongsToDomain(\n product: z.infer<typeof CommerceProductSchema>,\n verifiedDomain: string,\n) {\n try {\n return (\n product.url === null || new URL(product.url).hostname === verifiedDomain\n );\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;AAoBX,IAAM,gBAAgB;AACtB,IAAM,WAAW,CAAC,SACvB,+BAA+B,KAAK,IAAI,KACxC,CAAC,CAAC,aAAa,aAAa,aAAa,EAAE,SAAS,IAAI;AACnD,IAAM,WAAW,CAAC,SACvB,KAAK,UAAU,OAAO,KAAK,MAAM,GAAG,EAAE,MAAM,QAAQ;AACtD,IAAM,WAAW;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACO,SAAS,eACd,OACA,MACuB;AACvB,MAAI,gBAAgB;AACpB,QAAM,WAAW,SAAS,UAAU,IAAI;AACxC,WAAS,KAAK,KAAc,OAAwB;AAClD,QACE,QAAQ,YACR,CAAC,OACD,OAAO,QAAQ,YACf,MAAM,QAAQ,GAAG;AAEjB,aAAO;AACT,UAAM,IAAI;AACV,QACE,OAAO,KAAK,CAAC,EAAE;AAAA,MACb,CAAC,MAAM,CAAC,SAAS,SAAS,CAAC,KAAK,EAAE,SAAS,WAAW,MAAM;AAAA,IAC9D;AAEA,aAAO;AACT,UAAM,WAAW,MAAM,QAAQ,EAAE,IAAI;AACrC,QACE,aACC,EAAE,KAAK,WAAW,KAAK,EAAE,KAAK,CAAC,MAAM,UACnC,SAAS,aAAa,CAAC,UAAU,OAAO,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;AAE/D,aAAO;AACT,UAAM,OAAO,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC;AAC3D,QACE,CAAC;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAI,SAAS,YAAY,CAAC,QAAQ,IAAI,CAAC;AAAA,I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BuiltInDescriptor,
8
8
  isTrustedCommerceBuiltInGrant
9
- } from "./chunk-HR7T3UEW.js";
9
+ } from "./chunk-6OBYUIQ3.js";
10
10
  import {
11
11
  IdSchema
12
12
  } from "./chunk-QVPEX7KY.js";
@@ -64,8 +64,7 @@ function deduplicateTools(capabilities, builtInTools = []) {
64
64
  ...builtInTools.map((tool) => ({
65
65
  kind: "BUILT_IN",
66
66
  toolName: tool.name,
67
- definitionVersion: tool.definitionVersion,
68
- contractHash: tool.contractHash
67
+ definitionVersion: tool.definitionVersion
69
68
  }))
70
69
  ]).sort((a, b) => a.toolName.localeCompare(b.toolName, "en"));
71
70
  }
@@ -84,7 +83,7 @@ function manifestMatchesGrant(manifest, grant) {
84
83
  var parseCommerceManifest = (raw) => CommerceManifestSchema.parse(raw);
85
84
  function currentlyGrantedTools(grant, eligibleCapabilityKeys, enabledToolIds, allowedBuiltInTools = []) {
86
85
  return grant.grantedTools.filter(
87
- (t) => isBuiltInTool(t) ? isTrustedCommerceBuiltInGrant(t) && allowedBuiltInTools.some((descriptor) => isTrustedCommerceBuiltInDescriptor(descriptor) && descriptor.name === t.toolName && descriptor.definitionVersion === t.definitionVersion && descriptor.contractHash === t.contractHash) : enabledToolIds.has(t.toolId) && t.capabilityKeys.some((k) => eligibleCapabilityKeys.has(k))
86
+ (t) => isBuiltInTool(t) ? isTrustedCommerceBuiltInGrant(t) && allowedBuiltInTools.some((descriptor) => isTrustedCommerceBuiltInDescriptor(descriptor) && descriptor.name === t.toolName && descriptor.definitionVersion === t.definitionVersion) : enabledToolIds.has(t.toolId) && t.capabilityKeys.some((k) => eligibleCapabilityKeys.has(k))
88
87
  );
89
88
  }
90
89
 
@@ -95,4 +94,4 @@ export {
95
94
  parseCommerceManifest,
96
95
  currentlyGrantedTools
97
96
  };
98
- //# sourceMappingURL=chunk-QG2M5FDO.js.map
97
+ //# sourceMappingURL=chunk-C2PCRWOW.js.map