@relyon/kit 0.0.0-stage → 1.0.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 (225) hide show
  1. package/AGENTS.md +75 -0
  2. package/CHANGELOG.md +1053 -0
  3. package/LICENSE +21 -0
  4. package/QUICKSTART.md +239 -0
  5. package/README.md +117 -2
  6. package/dist/adapters/express.d.ts +39 -0
  7. package/dist/adapters/express.js +106 -0
  8. package/dist/adapters/hono.d.ts +16 -0
  9. package/dist/adapters/hono.js +15 -0
  10. package/dist/adapters/next.d.ts +29 -0
  11. package/dist/adapters/next.js +38 -0
  12. package/dist/agent-card.d.ts +14 -0
  13. package/dist/agent-card.js +58 -0
  14. package/dist/agent-docs.d.ts +36 -0
  15. package/dist/agent-docs.js +78 -0
  16. package/dist/agent-hooks.d.ts +66 -0
  17. package/dist/agent-hooks.js +280 -0
  18. package/dist/agents.d.ts +24 -0
  19. package/dist/agents.js +120 -0
  20. package/dist/api-key.d.ts +6 -0
  21. package/dist/api-key.js +33 -0
  22. package/dist/cache.d.ts +46 -0
  23. package/dist/cache.js +86 -0
  24. package/dist/cart-tokens.d.ts +31 -0
  25. package/dist/cart-tokens.js +58 -0
  26. package/dist/cart-transfer.d.ts +95 -0
  27. package/dist/cart-transfer.js +387 -0
  28. package/dist/catalog-enrichment.d.ts +6 -0
  29. package/dist/catalog-enrichment.js +71 -0
  30. package/dist/catalog-reads.d.ts +126 -0
  31. package/dist/catalog-reads.js +104 -0
  32. package/dist/catalog.d.ts +78 -0
  33. package/dist/catalog.js +288 -0
  34. package/dist/charge-claims.d.ts +11 -0
  35. package/dist/charge-claims.js +47 -0
  36. package/dist/check.d.ts +44 -0
  37. package/dist/check.js +152 -0
  38. package/dist/checklist-manifest.d.ts +72 -0
  39. package/dist/checklist-manifest.js +341 -0
  40. package/dist/checkout.d.ts +222 -0
  41. package/dist/checkout.js +353 -0
  42. package/dist/cli.d.ts +2 -0
  43. package/dist/cli.js +727 -0
  44. package/dist/confirmation.d.ts +78 -0
  45. package/dist/confirmation.js +124 -0
  46. package/dist/context.d.ts +81 -0
  47. package/dist/context.js +10 -0
  48. package/dist/discovery.d.ts +151 -0
  49. package/dist/discovery.js +346 -0
  50. package/dist/doctor-cart-transfer.d.ts +33 -0
  51. package/dist/doctor-cart-transfer.js +186 -0
  52. package/dist/doctor-catalog.d.ts +8 -0
  53. package/dist/doctor-catalog.js +47 -0
  54. package/dist/doctor-evidence.d.ts +22 -0
  55. package/dist/doctor-evidence.js +57 -0
  56. package/dist/doctor-merchant.d.ts +48 -0
  57. package/dist/doctor-merchant.js +74 -0
  58. package/dist/doctor-source.d.ts +5 -0
  59. package/dist/doctor-source.js +142 -0
  60. package/dist/doctor-variants.d.ts +70 -0
  61. package/dist/doctor-variants.js +102 -0
  62. package/dist/doctor.d.ts +215 -0
  63. package/dist/doctor.js +1689 -0
  64. package/dist/events.d.ts +95 -0
  65. package/dist/events.js +200 -0
  66. package/dist/feed-mapping.d.ts +114 -0
  67. package/dist/feed-mapping.js +152 -0
  68. package/dist/feed-values.d.ts +13 -0
  69. package/dist/feed-values.js +40 -0
  70. package/dist/feeds.d.ts +104 -0
  71. package/dist/feeds.js +366 -0
  72. package/dist/identify.d.ts +102 -0
  73. package/dist/identify.js +124 -0
  74. package/dist/identity.d.ts +37 -0
  75. package/dist/identity.js +54 -0
  76. package/dist/index.d.ts +42 -0
  77. package/dist/index.js +41 -0
  78. package/dist/init.d.ts +157 -0
  79. package/dist/init.js +912 -0
  80. package/dist/kit-config.d.ts +19 -0
  81. package/dist/kit-config.js +43 -0
  82. package/dist/kit-environment.d.ts +20 -0
  83. package/dist/kit-environment.js +32 -0
  84. package/dist/kit-updates.d.ts +47 -0
  85. package/dist/kit-updates.js +77 -0
  86. package/dist/kit-version-project.d.ts +18 -0
  87. package/dist/kit-version-project.js +214 -0
  88. package/dist/kit-version.d.ts +37 -0
  89. package/dist/kit-version.js +162 -0
  90. package/dist/kit.d.ts +516 -0
  91. package/dist/kit.js +1309 -0
  92. package/dist/layers/pages.d.ts +3 -0
  93. package/dist/layers/pages.js +5 -0
  94. package/dist/layers/payments.d.ts +7 -0
  95. package/dist/layers/payments.js +9 -0
  96. package/dist/layers/products.d.ts +10 -0
  97. package/dist/layers/products.js +13 -0
  98. package/dist/live.d.ts +13 -0
  99. package/dist/live.js +52 -0
  100. package/dist/mcp.d.ts +270 -0
  101. package/dist/mcp.js +312 -0
  102. package/dist/next-steps.d.ts +101 -0
  103. package/dist/next-steps.js +257 -0
  104. package/dist/order-pending.d.ts +57 -0
  105. package/dist/order-pending.js +127 -0
  106. package/dist/orders.d.ts +12 -0
  107. package/dist/orders.js +21 -0
  108. package/dist/payments-init.d.ts +19 -0
  109. package/dist/payments-init.js +70 -0
  110. package/dist/payments-routes.d.ts +54 -0
  111. package/dist/payments-routes.js +123 -0
  112. package/dist/payments.d.ts +165 -0
  113. package/dist/payments.js +192 -0
  114. package/dist/pnpm-workspace.d.ts +58 -0
  115. package/dist/pnpm-workspace.js +250 -0
  116. package/dist/policies.d.ts +111 -0
  117. package/dist/policies.js +317 -0
  118. package/dist/preview-hosts.d.ts +64 -0
  119. package/dist/preview-hosts.js +175 -0
  120. package/dist/private-config.d.ts +169 -0
  121. package/dist/private-config.js +820 -0
  122. package/dist/progress.d.ts +54 -0
  123. package/dist/progress.js +153 -0
  124. package/dist/protocol-inputs.d.ts +22 -0
  125. package/dist/protocol-inputs.js +151 -0
  126. package/dist/public-origin.d.ts +50 -0
  127. package/dist/public-origin.js +180 -0
  128. package/dist/refusals.d.ts +86 -0
  129. package/dist/refusals.js +157 -0
  130. package/dist/relay.d.ts +107 -0
  131. package/dist/relay.js +655 -0
  132. package/dist/release-notes.d.ts +2 -0
  133. package/dist/release-notes.js +290 -0
  134. package/dist/relyon-cart-tokens.d.ts +101 -0
  135. package/dist/relyon-cart-tokens.js +521 -0
  136. package/dist/relyon.d.ts +141 -0
  137. package/dist/relyon.js +238 -0
  138. package/dist/robots.d.ts +27 -0
  139. package/dist/robots.js +127 -0
  140. package/dist/rules.d.ts +144 -0
  141. package/dist/rules.js +347 -0
  142. package/dist/sdk/generated/public-api.d.ts +4816 -0
  143. package/dist/sdk/generated/public-api.js +1 -0
  144. package/dist/sdk/index.d.ts +24 -0
  145. package/dist/sdk/index.js +34 -0
  146. package/dist/sdk/signatures.d.ts +17 -0
  147. package/dist/sdk/signatures.js +33 -0
  148. package/dist/setup.d.ts +37 -0
  149. package/dist/setup.js +94 -0
  150. package/dist/signatures.d.ts +112 -0
  151. package/dist/signatures.js +443 -0
  152. package/dist/state.d.ts +185 -0
  153. package/dist/state.js +96 -0
  154. package/dist/store-payments.d.ts +48 -0
  155. package/dist/store-payments.js +143 -0
  156. package/dist/structured-fields.d.ts +26 -0
  157. package/dist/structured-fields.js +200 -0
  158. package/dist/templates.d.ts +19 -0
  159. package/dist/templates.js +193 -0
  160. package/dist/test-checkout-command.d.ts +32 -0
  161. package/dist/test-checkout-command.js +161 -0
  162. package/dist/test-checkout.d.ts +88 -0
  163. package/dist/test-checkout.js +292 -0
  164. package/dist/types.d.ts +103 -0
  165. package/dist/types.js +18 -0
  166. package/dist/ucp-versions.d.ts +57 -0
  167. package/dist/ucp-versions.js +129 -0
  168. package/dist/util.d.ts +23 -0
  169. package/dist/util.js +68 -0
  170. package/dist/variants.d.ts +67 -0
  171. package/dist/variants.js +146 -0
  172. package/dist/version.d.ts +9 -0
  173. package/dist/version.js +10 -0
  174. package/dist/waiting.d.ts +43 -0
  175. package/dist/waiting.js +57 -0
  176. package/dist/webhook-command.d.ts +48 -0
  177. package/dist/webhook-command.js +367 -0
  178. package/dist/webhook-registration.d.ts +47 -0
  179. package/dist/webhook-registration.js +69 -0
  180. package/dist/webmcp-schema.d.ts +14 -0
  181. package/dist/webmcp-schema.js +140 -0
  182. package/dist/webmcp-script.d.ts +3 -0
  183. package/dist/webmcp-script.js +176 -0
  184. package/dist/webmcp-store.d.ts +102 -0
  185. package/dist/webmcp-store.js +116 -0
  186. package/dist/webmcp.d.ts +242 -0
  187. package/dist/webmcp.js +866 -0
  188. package/dist/wire-names.d.ts +85 -0
  189. package/dist/wire-names.js +109 -0
  190. package/package.json +118 -4
  191. package/release-notes.json +290 -0
  192. package/scripts/install-notice.cjs +7 -0
  193. package/skills/relyon-agents/SKILL.md +327 -0
  194. package/skills/relyon-catalog/SKILL.md +499 -0
  195. package/skills/relyon-catalog/references/example-store.md +218 -0
  196. package/skills/relyon-checkout/SKILL.md +603 -0
  197. package/skills/relyon-checkout/references/checkout-flow.md +257 -0
  198. package/skills/relyon-checkout/references/checkout-page.md +315 -0
  199. package/skills/relyon-go-live/SKILL.md +344 -0
  200. package/skills/relyon-orders/SKILL.md +191 -0
  201. package/skills/relyon-orders/references/webhook-receiver.md +113 -0
  202. package/skills/relyon-payments/SKILL.md +117 -0
  203. package/skills/relyon-setup/SKILL.md +1061 -0
  204. package/skills/relyon-setup/references/QUICKSTART.md +239 -0
  205. package/skills/relyon-setup/references/durable-state.md +209 -0
  206. package/skills/relyon-setup/references/express-server.md +388 -0
  207. package/skills/relyon-setup/references/next-app-router.md +251 -0
  208. package/templates/common/STORE-README.md +67 -0
  209. package/templates/common/gitignore +8 -0
  210. package/templates/common/scripts/check-pricing.ts +22 -0
  211. package/templates/common/scripts/serve.mjs +13 -0
  212. package/templates/common/server/catalog.ts +79 -0
  213. package/templates/common/server/checkout-flow.d.ts +34 -0
  214. package/templates/common/server/pages.ts +184 -0
  215. package/templates/common/server/storage.ts +114 -0
  216. package/templates/common/server/store.ts +67 -0
  217. package/templates/express/server/express.ts +20 -0
  218. package/templates/express/tsconfig.build.json +6 -0
  219. package/templates/express/tsconfig.json +9 -0
  220. package/templates/next/app/[[...path]]/route.ts +24 -0
  221. package/templates/next/next.config.mjs +19 -0
  222. package/templates/next/tsconfig.json +12 -0
  223. package/templates/payments/express.ts +39 -0
  224. package/templates/payments/next.ts +38 -0
  225. package/templates/payments/node.ts +39 -0
@@ -0,0 +1,95 @@
1
+ import type { AgentEventInput, Logger, RequestInfo } from "./types.js";
2
+ import { type RelyonGateway } from "./relyon.js";
3
+ /**
4
+ * Where queued agent events wait until Relyon has them. The default keeps
5
+ * them in memory; a store that wants them to survive restarts plugs in its
6
+ * own (a table, Redis, a file). Events come back from `peek` oldest first.
7
+ */
8
+ export interface AgentEventStore {
9
+ append(event: AgentEventInput): Promise<void> | void;
10
+ peek(limit: number): Promise<AgentEventInput[]> | AgentEventInput[];
11
+ remove(ids: readonly string[]): Promise<void> | void;
12
+ size(): Promise<number> | number;
13
+ }
14
+ export declare class MemoryAgentEventStore implements AgentEventStore {
15
+ private events;
16
+ append(event: AgentEventInput): void;
17
+ peek(limit: number): AgentEventInput[];
18
+ remove(ids: readonly string[]): void;
19
+ size(): number;
20
+ }
21
+ export interface AgentEventQueueOptions {
22
+ store?: AgentEventStore;
23
+ /** Events per `recordAgentEvents` call. At most 500 (the contract's limit). Default 500. */
24
+ maxBatch?: number;
25
+ /** Events held at most; more are counted in `stats.dropped` and never block a request. Default 10000. */
26
+ maxQueued?: number;
27
+ /** How often queued events are sent, in milliseconds. Default 5000. */
28
+ flushIntervalMs?: number;
29
+ /** First retry delay after a failed batch, doubled per failure. Default 1000. */
30
+ retryInitialMs?: number;
31
+ /** Longest retry delay. Default 300000 (5 minutes). */
32
+ retryMaxMs?: number;
33
+ }
34
+ export interface AgentEventStats {
35
+ queued: number;
36
+ sent: number;
37
+ /** Events Relyon already had (same ID sent before). */
38
+ duplicates: number;
39
+ /** Events refused because the queue was full. */
40
+ dropped: number;
41
+ /** Events in batches Relyon refused as invalid; never retried. */
42
+ rejected: number;
43
+ /** Failed send attempts (each is retried with backoff). */
44
+ failedAttempts: number;
45
+ }
46
+ export type NewAgentEvent = Omit<AgentEventInput, "id" | "occurred_at"> & {
47
+ id?: string;
48
+ occurred_at?: number;
49
+ };
50
+ /**
51
+ * Batches agent events to `recordAgentEvents`. Every event gets a stable ID
52
+ * when it's queued, so a batch can be resent as often as needed: Relyon
53
+ * de-duplicates on the ID. Failed batches stay queued and are retried with
54
+ * exponential backoff.
55
+ */
56
+ export declare class AgentEventQueue {
57
+ private readonly gateway;
58
+ private readonly now;
59
+ private readonly logger;
60
+ private readonly store;
61
+ private readonly maxBatch;
62
+ private readonly maxQueued;
63
+ private readonly flushIntervalMs;
64
+ private readonly retryInitialMs;
65
+ private readonly retryMaxMs;
66
+ private timer;
67
+ private flushing;
68
+ private pendingAppends;
69
+ private queued;
70
+ private failures;
71
+ private nextAttemptAt;
72
+ readonly stats: AgentEventStats;
73
+ constructor(gateway: RelyonGateway, options: AgentEventQueueOptions, now: () => number, logger: Logger);
74
+ /** Starts the flush timer and counts events a persistent store already holds. */
75
+ start(): Promise<void>;
76
+ stop(): void;
77
+ /**
78
+ * Queues one event and returns its ID, or null when the queue is full.
79
+ * Never throws and never waits for Relyon.
80
+ */
81
+ record(event: NewAgentEvent): string | null;
82
+ /**
83
+ * Sends queued events in batches until the queue is empty or a batch fails.
84
+ * While a retry is backing off this does nothing unless `force` is set.
85
+ */
86
+ flush(options?: {
87
+ force?: boolean;
88
+ }): Promise<void>;
89
+ private drain;
90
+ private done;
91
+ /** When the next retry may run (epoch ms); 0 when not backing off. */
92
+ get retryAt(): number;
93
+ }
94
+ /** The request facts an agent event carries, trimmed to the contract's limits, never with a hand-off token. */
95
+ export declare function requestFacts(request: Request, publicUrl: string, info?: RequestInfo): AgentEventInput["request"] | null;
package/dist/events.js ADDED
@@ -0,0 +1,200 @@
1
+ import { AGENT_EVENTS_PATH, AGENT_EVENT_BATCH_OBJECT } from "./wire-names.js";
2
+ import { RelyonProblemError, RelyonUnavailableError } from "./relyon.js";
3
+ import { isRecord, randomId, sha256 } from "./util.js";
4
+ import { redactCartTokens } from "./relyon-cart-tokens.js";
5
+ import { describeError } from "./relyon-cart-tokens.js";
6
+ export class MemoryAgentEventStore {
7
+ events = [];
8
+ append(event) { this.events.push(event); }
9
+ peek(limit) { return this.events.slice(0, limit); }
10
+ remove(ids) {
11
+ const gone = new Set(ids);
12
+ this.events = this.events.filter((event) => !gone.has(event.id));
13
+ }
14
+ size() { return this.events.length; }
15
+ }
16
+ /** A Relyon refusal that retrying the same batch can never fix. */
17
+ const PERMANENT = new Set([400, 413, 422]);
18
+ /**
19
+ * Batches agent events to `recordAgentEvents`. Every event gets a stable ID
20
+ * when it's queued, so a batch can be resent as often as needed: Relyon
21
+ * de-duplicates on the ID. Failed batches stay queued and are retried with
22
+ * exponential backoff.
23
+ */
24
+ export class AgentEventQueue {
25
+ gateway;
26
+ now;
27
+ logger;
28
+ store;
29
+ maxBatch;
30
+ maxQueued;
31
+ flushIntervalMs;
32
+ retryInitialMs;
33
+ retryMaxMs;
34
+ timer;
35
+ flushing;
36
+ pendingAppends = new Set();
37
+ queued = 0;
38
+ failures = 0;
39
+ nextAttemptAt = 0;
40
+ stats = { queued: 0, sent: 0, duplicates: 0, dropped: 0, rejected: 0, failedAttempts: 0 };
41
+ constructor(gateway, options, now, logger) {
42
+ this.gateway = gateway;
43
+ this.now = now;
44
+ this.logger = logger;
45
+ this.store = options.store ?? new MemoryAgentEventStore();
46
+ this.maxBatch = Math.min(500, Math.max(1, options.maxBatch ?? 500));
47
+ this.maxQueued = Math.max(1, options.maxQueued ?? 10_000);
48
+ this.flushIntervalMs = options.flushIntervalMs ?? 5_000;
49
+ this.retryInitialMs = options.retryInitialMs ?? 1_000;
50
+ this.retryMaxMs = options.retryMaxMs ?? 300_000;
51
+ }
52
+ /** Starts the flush timer and counts events a persistent store already holds. */
53
+ async start() {
54
+ this.queued = await this.store.size();
55
+ this.stats.queued = this.queued;
56
+ if (!this.timer && this.flushIntervalMs > 0) {
57
+ this.timer = setInterval(() => { void this.flush(); }, this.flushIntervalMs);
58
+ this.timer.unref?.();
59
+ }
60
+ }
61
+ stop() {
62
+ if (this.timer)
63
+ clearInterval(this.timer);
64
+ this.timer = undefined;
65
+ }
66
+ /**
67
+ * Queues one event and returns its ID, or null when the queue is full.
68
+ * Never throws and never waits for Relyon.
69
+ */
70
+ record(event) {
71
+ if (this.queued >= this.maxQueued) {
72
+ this.stats.dropped += 1;
73
+ return null;
74
+ }
75
+ const full = { ...event, id: event.id ?? randomId("sk-evt-"), occurred_at: event.occurred_at ?? Math.floor(this.now() / 1000) };
76
+ this.queued += 1;
77
+ this.stats.queued = this.queued;
78
+ const appended = Promise.resolve()
79
+ .then(() => this.store.append(full))
80
+ .catch((error) => {
81
+ this.queued -= 1;
82
+ this.stats.queued = this.queued;
83
+ this.stats.dropped += 1;
84
+ this.logger.error("could not queue an agent event", { error: describeError(error) });
85
+ })
86
+ .finally(() => this.pendingAppends.delete(appended));
87
+ this.pendingAppends.add(appended);
88
+ if (this.queued >= this.maxBatch)
89
+ void appended.then(() => this.flush());
90
+ return full.id;
91
+ }
92
+ /**
93
+ * Sends queued events in batches until the queue is empty or a batch fails.
94
+ * While a retry is backing off this does nothing unless `force` is set.
95
+ */
96
+ flush(options = {}) {
97
+ if (this.flushing)
98
+ return this.flushing;
99
+ if (!options.force && this.now() < this.nextAttemptAt)
100
+ return Promise.resolve();
101
+ this.flushing = this.drain().finally(() => { this.flushing = undefined; });
102
+ return this.flushing;
103
+ }
104
+ async drain() {
105
+ await Promise.all([...this.pendingAppends]);
106
+ for (;;) {
107
+ const batch = await this.store.peek(this.maxBatch);
108
+ if (batch.length === 0)
109
+ return;
110
+ const ids = batch.map((event) => event.id);
111
+ try {
112
+ const { data } = await this.gateway.call((client) => client.POST(AGENT_EVENTS_PATH, {
113
+ params: { header: { "Idempotency-Key": `sk-evt-batch-${sha256(ids.join(","))}` } },
114
+ body: { events: batch },
115
+ }), isBatchResult);
116
+ this.stats.sent += data.stored;
117
+ this.stats.duplicates += data.duplicates;
118
+ await this.done(ids);
119
+ this.failures = 0;
120
+ this.nextAttemptAt = 0;
121
+ }
122
+ catch (error) {
123
+ if (error instanceof RelyonProblemError && PERMANENT.has(error.status)) {
124
+ this.logger.error("Relyon refused a batch of agent events; it is dropped", { code: error.code, message: redactCartTokens(error.message), events: ids.length });
125
+ this.stats.rejected += ids.length;
126
+ await this.done(ids);
127
+ continue;
128
+ }
129
+ this.failures += 1;
130
+ this.stats.failedAttempts += 1;
131
+ const delay = Math.min(this.retryMaxMs, this.retryInitialMs * 2 ** (this.failures - 1));
132
+ this.nextAttemptAt = this.now() + delay;
133
+ if (!(error instanceof RelyonUnavailableError) && !(error instanceof RelyonProblemError)) {
134
+ this.logger.error("sending agent events failed", { error: describeError(error) });
135
+ }
136
+ return;
137
+ }
138
+ }
139
+ }
140
+ async done(ids) {
141
+ await this.store.remove(ids);
142
+ this.queued = Math.max(0, this.queued - ids.length);
143
+ this.stats.queued = this.queued;
144
+ }
145
+ /** When the next retry may run (epoch ms); 0 when not backing off. */
146
+ get retryAt() {
147
+ return this.nextAttemptAt;
148
+ }
149
+ }
150
+ function isBatchResult(data) {
151
+ return isRecord(data) && data.object === AGENT_EVENT_BATCH_OBJECT && Number.isInteger(data.stored) && Number.isInteger(data.duplicates);
152
+ }
153
+ const IDENTIFYING_HEADERS = ["signature", "signature-input", "signature-agent", "ucp-agent", "x-openai-agent", "openai-agent"];
154
+ const METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
155
+ /**
156
+ * The URL without its `relyon_cart` hand-off token (a bearer of attribution
157
+ * that never leaves the store) or `relyon_transfer` cart-transfer token.
158
+ */
159
+ function withoutCartToken(publicUrl) {
160
+ // Always parsed: a percent-encoded parameter name (`%72elyon_cart`) is still the hand-off token.
161
+ if (!publicUrl.includes("?"))
162
+ return publicUrl;
163
+ try {
164
+ const url = new URL(publicUrl);
165
+ const names = [...url.searchParams.keys()].filter((name) => name.toLowerCase() === "relyon_cart" || name.toLowerCase() === "relyon_transfer");
166
+ if (!names.length)
167
+ return publicUrl;
168
+ for (const name of names)
169
+ url.searchParams.delete(name);
170
+ if ([...url.searchParams.keys()].length === 0)
171
+ url.search = "";
172
+ return url.toString();
173
+ }
174
+ catch {
175
+ return publicUrl.split("?")[0];
176
+ }
177
+ }
178
+ /** The request facts an agent event carries, trimmed to the contract's limits, never with a hand-off token. */
179
+ export function requestFacts(request, publicUrl, info = {}) {
180
+ const method = request.method.toUpperCase();
181
+ if (!METHODS.has(method))
182
+ return null;
183
+ let url = withoutCartToken(publicUrl);
184
+ if (url.length > 4096)
185
+ url = url.split("?")[0].slice(0, 4096);
186
+ const headers = {};
187
+ for (const name of IDENTIFYING_HEADERS) {
188
+ const value = request.headers.get(name);
189
+ if (value !== null)
190
+ headers[name] = value.slice(0, 16384);
191
+ }
192
+ const userAgent = request.headers.get("user-agent");
193
+ return {
194
+ method: method,
195
+ url,
196
+ ...(userAgent ? { user_agent: userAgent.slice(0, 1000) } : {}),
197
+ ...(info.ip ? { ip: info.ip.slice(0, 64) } : {}),
198
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
199
+ };
200
+ }
@@ -0,0 +1,114 @@
1
+ import { type FeedText } from "./feed-values.js";
2
+ export type FeedMappingFormat = "acp" | "google" | "jsonld";
3
+ export type FeedDiagnostic = {
4
+ productId: string;
5
+ format: FeedMappingFormat;
6
+ code: string;
7
+ };
8
+ export type FeedGeneration = {
9
+ bodies: Record<FeedMappingFormat, string>;
10
+ diagnostics: readonly FeedDiagnostic[];
11
+ };
12
+ export type FeedRow = {
13
+ organizationId: string;
14
+ environment: "test" | "live";
15
+ id: string;
16
+ status: string;
17
+ agentVisible: boolean;
18
+ document: Record<string, unknown>;
19
+ checkout?: {
20
+ checkout_eligible: {
21
+ google: boolean;
22
+ chatgpt: boolean;
23
+ };
24
+ checkout_ineligible_reasons: {
25
+ google: readonly string[];
26
+ chatgpt: readonly string[];
27
+ };
28
+ };
29
+ };
30
+ export type FeedMerchant = {
31
+ organizationId: string;
32
+ environment: "test" | "live";
33
+ merchantId: string;
34
+ sellerName: string;
35
+ storeUrl: string;
36
+ exactPriceProductIds: readonly string[];
37
+ conditions: Readonly<Record<string, "new" | "used" | "refurbished">>;
38
+ };
39
+ export type GoogleItem = {
40
+ productId: string;
41
+ id: string;
42
+ title: string;
43
+ description: string;
44
+ link: string;
45
+ imageLink: string;
46
+ price: {
47
+ decimal: string;
48
+ currency: string;
49
+ };
50
+ availability: "in_stock" | "out_of_stock";
51
+ condition: "new" | "used" | "refurbished";
52
+ brand?: string;
53
+ gtin?: string;
54
+ mpn?: string;
55
+ /** Only `false`, and only for an explicit custom-goods attestation (store profile). */
56
+ identifierExists?: false;
57
+ };
58
+ export type SerializeHooks = {
59
+ onGoogleItem?: (item: GoogleItem) => void;
60
+ };
61
+ /** Shared Merchant Center checkout eligibility mapping; no visibility-based inference. */
62
+ export declare function googleNativeCommerce(eligible: boolean | undefined, condition: string, channelStatus: string): boolean;
63
+ /** Store-only extensions. The legacy API adapter never enables them. */
64
+ export type StoreMappingProfile = {
65
+ stable: true;
66
+ variants: Readonly<Record<string, {
67
+ groupId: string;
68
+ options: Readonly<Record<string, string>>;
69
+ }>>;
70
+ /** Only Google XML, never the Microsoft-compatible file. Explicit channel eligibility AND new/in-stock/USD. */
71
+ googleCheckout: Readonly<Record<string, {
72
+ eligible: boolean;
73
+ channelStatus: string;
74
+ }>>;
75
+ microsoft?: boolean;
76
+ /**
77
+ * Explicit per-product identifier attestations from the store (never
78
+ * inferred). `own_brand`: the store is the brand owner and its MPN is the
79
+ * store's own SKU; brand+MPN is emitted only when both are given.
80
+ * `custom_goods`: made-to-order goods with no assigned GTIN or MPN, the only
81
+ * case `identifier_exists=false` is emitted. `conflict`: contradictory
82
+ * attestations; the item is omitted from RSS.
83
+ */
84
+ identifiers?: Readonly<Record<string, IdentifierAttestation>>;
85
+ /**
86
+ * Resolved per-product age group and gender (already validated or
87
+ * defaulted by the store adapter), emitted as `age_group` and `gender` in
88
+ * Google and Microsoft RSS, with the per-field diagnostics reported for each
89
+ * emitted item.
90
+ */
91
+ demographics?: Readonly<Record<string, ProductDemographics>>;
92
+ /**
93
+ * ChatGPT feed only: products the store adapter found eligible for ChatGPT
94
+ * checkout (the channel connected, the item buyable), with the store's
95
+ * privacy and terms pages that a checkout-eligible item must carry. Any
96
+ * other product keeps `is_eligible_checkout: false`.
97
+ */
98
+ chatgptCheckout?: Readonly<Record<string, {
99
+ privacyUrl: string;
100
+ termsUrl: string;
101
+ }>>;
102
+ };
103
+ export type ProductDemographics = {
104
+ ageGroup?: string;
105
+ gender?: string;
106
+ diagnostics: readonly string[];
107
+ };
108
+ export type IdentifierAttestation = "own_brand" | "custom_goods" | "conflict";
109
+ /**
110
+ * Shared flat-file mapping extracted from the API serializer. Authorization and
111
+ * sanitization belong to the adapter; this function has no server dependencies.
112
+ * Without a store profile its output, diagnostics and hook order are unchanged.
113
+ */
114
+ export declare function mapFeedRows(merchant: FeedMerchant, rows: readonly FeedRow[], text: FeedText, hooks?: SerializeHooks, profile?: StoreMappingProfile): FeedGeneration;
@@ -0,0 +1,152 @@
1
+ import { decimalMoney, publicUrl, validGtin, feedXml as xml, feedTag as tag, scriptSafeJson } from "./feed-values.js";
2
+ /** Shared Merchant Center checkout eligibility mapping; no visibility-based inference. */
3
+ export function googleNativeCommerce(eligible, condition, channelStatus) {
4
+ return eligible === true && condition === "new" && channelStatus === "connected";
5
+ }
6
+ const availability = {
7
+ in_stock: "InStock", out_of_stock: "OutOfStock", pre_order: "PreOrder", backorder: "BackOrder",
8
+ };
9
+ /**
10
+ * Shared flat-file mapping extracted from the API serializer. Authorization and
11
+ * sanitization belong to the adapter; this function has no server dependencies.
12
+ * Without a store profile its output, diagnostics and hook order are unchanged.
13
+ */
14
+ export function mapFeedRows(merchant, rows, text, hooks = {}, profile) {
15
+ const diagnostics = [];
16
+ const acp = [], google = [], jsonld = [];
17
+ const omit = (productId, format, code) => diagnostics.push({ productId, format, code });
18
+ const scoped = rows.filter(row => row.organizationId === merchant.organizationId && row.environment === merchant.environment
19
+ && row.status === "published" && row.agentVisible && row.document.agent?.visible !== false)
20
+ .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
21
+ const googleIds = new Set();
22
+ for (const row of scoped) {
23
+ const doc = row.document;
24
+ const title = text(doc.title, 150), description = text(doc.description, 5000);
25
+ const url = publicUrl(doc.url), brand = text(doc.brand, 70);
26
+ const images = Array.isArray(doc.images) ? doc.images.map(v => publicUrl(v)).filter((v) => Boolean(v)).slice(0, 20) : [];
27
+ const money = decimalMoney(doc.from_price);
28
+ const stock = typeof doc.availability === "string" && Object.hasOwn(availability, doc.availability)
29
+ ? doc.availability : undefined;
30
+ if (!/^[A-Za-z0-9._:-]{1,128}$/.test(row.id) || !title || !description || !url || !images.length || !money || !stock) {
31
+ for (const format of ["acp", "google", "jsonld"])
32
+ omit(row.id, format, "missing_or_invalid_discovery_field");
33
+ continue;
34
+ }
35
+ for (const reason of row.checkout?.checkout_ineligible_reasons.chatgpt ?? [])
36
+ omit(row.id, "acp", `checkout_ineligible:${reason}`);
37
+ for (const reason of row.checkout?.checkout_ineligible_reasons.google ?? [])
38
+ omit(row.id, "google", `checkout_ineligible:${reason}`);
39
+ const exact = doc.configurable !== true && merchant.exactPriceProductIds.includes(row.id);
40
+ const positive = Number(money.decimal) > 0;
41
+ const gtin = validGtin(doc.gtin) ? doc.gtin : undefined;
42
+ const mpn = text(doc.mpn, 70);
43
+ const identity = { ...(gtin ? { gtin } : {}), ...(mpn && brand ? { mpn } : {}) };
44
+ jsonld.push({
45
+ "@type": "Product", "@id": `urn:relyon:feed:${encodeURIComponent(merchant.merchantId)}:${row.id}`,
46
+ sku: row.id, name: title, description, url, image: images,
47
+ ...(brand ? { brand: { "@type": "Brand", name: brand } } : {}), ...identity,
48
+ offers: {
49
+ "@type": exact ? "Offer" : "AggregateOffer",
50
+ ...(exact ? { price: money.decimal } : { lowPrice: money.decimal }),
51
+ priceCurrency: money.currency, availability: `https://schema.org/${availability[stock]}`,
52
+ url, seller: { "@type": "Organization", name: merchant.sellerName, url: merchant.storeUrl },
53
+ },
54
+ });
55
+ if (!exact) {
56
+ omit(row.id, "acp", "exact_item_price_required");
57
+ omit(row.id, "google", "exact_item_price_required");
58
+ continue;
59
+ }
60
+ if (!positive) {
61
+ omit(row.id, "acp", "positive_price_required");
62
+ omit(row.id, "google", "positive_price_required");
63
+ continue;
64
+ }
65
+ const agent = doc.agent;
66
+ // An item agents may not buy is still listed for discovery; only its
67
+ // checkout eligibility flags stay off (is_eligible_checkout / native_commerce).
68
+ const buyable = !(agent?.purchasable === false || agent?.restrictions || (Array.isArray(agent?.must_ask) && agent.must_ask.length > 0));
69
+ const chatgptEligible = Boolean(brand && (gtin || mpn))
70
+ && profile?.chatgptCheckout !== undefined && Object.hasOwn(profile.chatgptCheckout, row.id);
71
+ if (!brand)
72
+ omit(row.id, "acp", "brand_required");
73
+ else
74
+ acp.push({
75
+ item_id: row.id, title, description, url, brand, seller_name: merchant.sellerName,
76
+ seller_url: merchant.storeUrl, image_url: images[0], price: `${money.decimal} ${money.currency}`,
77
+ availability: stock, is_eligible_search: true, is_eligible_checkout: chatgptEligible, ...identity,
78
+ ...(chatgptEligible ? {
79
+ seller_privacy_policy: profile.chatgptCheckout[row.id].privacyUrl, seller_tos: profile.chatgptCheckout[row.id].termsUrl,
80
+ } : {}),
81
+ ...(profile ? {
82
+ condition: merchant.conditions[row.id],
83
+ ...(profile.variants[row.id] ? {
84
+ group_id: profile.variants[row.id].groupId, listing_has_variations: true,
85
+ variant_dict: profile.variants[row.id].options,
86
+ } : {}),
87
+ } : {}),
88
+ });
89
+ const condition = merchant.conditions[row.id];
90
+ const googleDecimal = /\.\d{3}$/.test(money.decimal) && money.decimal.endsWith("0")
91
+ ? money.decimal.slice(0, -1) : money.decimal;
92
+ const merchantItemId = typeof doc.merchant_product_id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(doc.merchant_product_id)
93
+ ? doc.merchant_product_id : row.id;
94
+ const googleReason = merchantItemId.length > 50 ? "id_too_long"
95
+ : googleIds.has(merchantItemId) ? "duplicate_merchant_item_id" : !condition ? "condition_unknown"
96
+ : /\.\d{3}$/.test(googleDecimal) ? "google_price_precision_unsupported"
97
+ : stock === "pre_order" || stock === "backorder" ? "availability_date_missing"
98
+ : profile?.identifiers?.[row.id] === "conflict" ? "identifier_attestation_conflict"
99
+ : profile?.identifiers?.[row.id] === "custom_goods" && (gtin || mpn) ? "identifier_attestation_conflict"
100
+ : profile?.identifiers?.[row.id] === "own_brand" && !mpn ? "own_brand_mpn_missing"
101
+ : !gtin && !(brand && mpn) && profile?.identifiers?.[row.id] !== "custom_goods" ? "assigned_identifier_missing"
102
+ : profile?.microsoft && (brand.split(/\s+/).length > 10 || Number(googleDecimal) > 10_000_000) ? "microsoft_attribute_limit"
103
+ : undefined;
104
+ if (googleReason) {
105
+ omit(row.id, "google", googleReason);
106
+ continue;
107
+ }
108
+ googleIds.add(merchantItemId);
109
+ // An option key the XML channels don't support (their variant attributes
110
+ // are only color/size/material/pattern) loses just that attribute, never
111
+ // the whole item. The ChatGPT feed still carries the full variant_dict.
112
+ for (const key of Object.keys(profile?.variants[row.id]?.options ?? {})) {
113
+ if (!["color", "size", "material", "pattern"].includes(key))
114
+ omit(row.id, "google", `xml_variant_attribute_omitted:${key}`);
115
+ }
116
+ const customGoods = profile?.identifiers?.[row.id] === "custom_goods";
117
+ const demographics = profile?.demographics?.[row.id];
118
+ for (const code of demographics?.diagnostics ?? [])
119
+ omit(row.id, "google", code);
120
+ hooks.onGoogleItem?.({
121
+ productId: row.id, id: merchantItemId, title, description, link: url, imageLink: images[0],
122
+ price: { decimal: googleDecimal, currency: money.currency }, availability: stock,
123
+ condition: condition, ...(brand ? { brand } : {}), ...(gtin ? { gtin } : {}), ...(mpn && brand ? { mpn } : {}),
124
+ ...(customGoods ? { identifierExists: false } : {}),
125
+ });
126
+ google.push(`<item>${[
127
+ tag("id", merchantItemId), tag("title", title), tag("description", description), tag("link", url),
128
+ tag("image_link", images[0]), tag("price", `${profile?.microsoft && !googleDecimal.includes(".") ? `${googleDecimal}.00` : googleDecimal} ${money.currency}`),
129
+ tag("availability", profile?.microsoft ? stock.replace(/_/g, " ") : stock), tag("condition", condition),
130
+ ...(brand ? [tag("brand", brand)] : []), ...(gtin ? [tag("gtin", gtin)] : []),
131
+ ...(mpn && brand ? [tag("mpn", mpn)] : []),
132
+ ...(customGoods ? [tag("identifier_exists", "false")] : []),
133
+ ...(demographics?.ageGroup ? [tag("age_group", demographics.ageGroup)] : []),
134
+ ...(demographics?.gender ? [tag("gender", demographics.gender)] : []),
135
+ ...(profile?.variants[row.id] ? [
136
+ tag("item_group_id", profile.variants[row.id].groupId),
137
+ ...Object.entries(profile.variants[row.id].options).filter(([key]) => ["color", "size", "material", "pattern"].includes(key)).map(([key, value]) => tag(key, value)),
138
+ ] : []),
139
+ ...(profile && Object.hasOwn(profile.googleCheckout, row.id) ? [
140
+ `<g:native_commerce>${tag("checkout_eligibility", String(buyable && googleNativeCommerce(profile.googleCheckout[row.id]?.eligible, condition, profile.googleCheckout[row.id]?.channelStatus ?? "") && stock === "in_stock" && money.currency === "USD"))}</g:native_commerce>`,
141
+ ] : []),
142
+ ].join("")}</item>`);
143
+ }
144
+ return {
145
+ bodies: {
146
+ acp: acp.map(p => JSON.stringify(p)).join("\n") + (acp.length ? "\n" : ""),
147
+ google: `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:g="http://base.google.com/ns/1.0"><channel><title>${xml(merchant.sellerName)}</title><link>${xml(merchant.storeUrl)}</link><description>${xml(merchant.sellerName)} product discovery feed</description>${google.join("")}</channel></rss>`,
148
+ jsonld: scriptSafeJson({ "@context": "https://schema.org", "@graph": jsonld }),
149
+ },
150
+ diagnostics,
151
+ };
152
+ }
@@ -0,0 +1,13 @@
1
+ /** Dependency-neutral feed values. Callers supply their own text sanitizer. */
2
+ export type FeedText = (value: unknown, max: number) => string;
3
+ export declare function publicUrl(value: unknown, max?: number): string | undefined;
4
+ /** Finite supported ISO 4217 subset; never guess an unknown currency's precision. */
5
+ export declare const currencyPrecision: Readonly<Record<string, number>>;
6
+ export declare function decimalMoney(value: unknown): {
7
+ decimal: string;
8
+ currency: string;
9
+ } | undefined;
10
+ export declare function validGtin(value: unknown): value is string;
11
+ export declare const feedXml: (value: string) => string;
12
+ export declare const feedTag: (key: string, value: string) => string;
13
+ export declare const scriptSafeJson: (value: unknown) => string;
@@ -0,0 +1,40 @@
1
+ export function publicUrl(value, max = 2000) {
2
+ if (typeof value !== "string" || value.length > max || /[\s<>"'\\\u0000-\u001f]/u.test(value))
3
+ return;
4
+ try {
5
+ const url = new URL(value);
6
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password)
7
+ return;
8
+ return url.href;
9
+ }
10
+ catch {
11
+ return;
12
+ }
13
+ }
14
+ /** Finite supported ISO 4217 subset; never guess an unknown currency's precision. */
15
+ export const currencyPrecision = Object.freeze({
16
+ USD: 2, EUR: 2, GBP: 2, CAD: 2, AUD: 2, NZD: 2, CHF: 2, CNY: 2, HKD: 2,
17
+ SGD: 2, INR: 2, BRL: 2, MXN: 2, ZAR: 2, SEK: 2, NOK: 2, DKK: 2, PLN: 2,
18
+ AED: 2, SAR: 2, ILS: 2, KRW: 0, JPY: 0, CLP: 0, VND: 0,
19
+ BHD: 3, KWD: 3, OMR: 3, JOD: 3, TND: 3,
20
+ });
21
+ export function decimalMoney(value) {
22
+ if (!value || typeof value !== "object")
23
+ return;
24
+ const { amount, currency } = value;
25
+ if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount < 0
26
+ || typeof currency !== "string" || !Object.hasOwn(currencyPrecision, currency))
27
+ return;
28
+ const precision = currencyPrecision[currency];
29
+ const digits = BigInt(amount).toString().padStart(precision + 1, "0");
30
+ return { decimal: precision ? `${digits.slice(0, -precision)}.${digits.slice(-precision)}` : digits, currency };
31
+ }
32
+ export function validGtin(value) {
33
+ if (typeof value !== "string" || !/^(?:\d{8}|\d{12}|\d{13}|\d{14})$/.test(value) || /^0+$/.test(value))
34
+ return false;
35
+ const digits = [...value].reverse().map(Number);
36
+ return digits.reduce((sum, digit, i) => sum + digit * (i % 2 ? 3 : 1), 0) % 10 === 0;
37
+ }
38
+ export const feedXml = (value) => value.replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[c]);
39
+ export const feedTag = (key, value) => `<g:${key}>${feedXml(value)}</g:${key}>`;
40
+ export const scriptSafeJson = (value) => JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, c => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);