@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
package/dist/cli.js ADDED
@@ -0,0 +1,727 @@
1
+ #!/usr/bin/env node
2
+ import { publicUrlFromEnv } from "./kit-environment.js";
3
+ import { DEFAULT_RELYON_BASE_URL, redactSecrets } from "./doctor.js";
4
+ import { doctorExitCode, doctorJson, formatDoctorReport, runDoctorReport } from "./next-steps.js";
5
+ import { isAgentHookTool, readHookStdin, runAgentHook } from "./agent-hooks.js";
6
+ import { STORE_FEED_PATHS } from "./feeds.js";
7
+ import { STORE_BRIEF_FILE, STORE_IDEA_MAX, runInit } from "./init.js";
8
+ import { KIT_VERSION } from "./version.js";
9
+ import { AUTO_TEST_KEY_ENV, loadTestConfig } from "./private-config.js";
10
+ import { usableApiKey } from "./api-key.js";
11
+ import { runTestCheckoutCommand } from "./test-checkout-command.js";
12
+ import { runWebhookCommand } from "./webhook-command.js";
13
+ import { CART_TRANSFER_KEY_ENV } from "./cart-transfer.js";
14
+ import path from "node:path";
15
+ import { runCheck } from "./check.js";
16
+ import { PROJECT_SPACE_ENV } from "./wire-names.js";
17
+ import { STORE_KIT_PACKAGE, forKitPackage, kitCommand, kitIdentity } from "./identity.js";
18
+ import { KIT_LAYERS, KIT_LAYER_LABELS, isKitLayer, readKitConfig } from "./kit-config.js";
19
+ // `npx @relyon/store-kit init` and `npx @relyon/store-kit doctor`. Keys come
20
+ // from the environment (RELYON_API_KEY), verified private server storage or init --key-from-stdin
21
+ // (stdin or a hidden prompt), never from flags, so they stay out of shell history. Nothing prints one.
22
+ // Doctor exit codes: 0 DONE, 1 at least one FAIL, 2 NOT DONE without a FAIL, or a usage error.
23
+ // Init exit codes: 0 done, 1 a conflict or failed install (conflicts write nothing), 2 refused.
24
+ // test-checkout exit codes: 0 purchase done (and confirmed when Relyon could be asked), 1 failed or
25
+ // not confirmed, 2 refused to run (usage, Live, or no Test key).
26
+ // webhook exit codes: 0 the endpoint is registered, 1 the registration or the .env write failed,
27
+ // 2 refused to run (usage, Live, a non-https URL, or no Test key). The signing secret is never printed.
28
+ const USAGE_LAYERS = `Usage: npx @relyon/store-kit init --payments|--products|--pages [--store "<store idea>"] [--force] [--skip-install] [--key-from-stdin] [--auto-test-key] [--agent-hooks] [--yes]
29
+ npx @relyon/store-kit init --payments [--framework express|next|node] [--force] [--skip-install] [--key-from-stdin]
30
+ npx @relyon/store-kit check [--base-url <url>] [--allow-saved-key-to-base-url]
31
+ `;
32
+ /** The store kit keeps its own first line: init without a layer is its store setup. */
33
+ const USAGE_STORE_KIT = `Usage: npx @relyon/store-kit init [--store "<store idea>"] [--force] [--skip-install] [--key-from-stdin] [--auto-test-key] [--agent-hooks] [--yes]
34
+ npx @relyon/store-kit init --products|--pages [--store "<store idea>"] [--force] [--skip-install] [--key-from-stdin] [--agent-hooks]
35
+ npx @relyon/store-kit check [--base-url <url>] [--allow-saved-key-to-base-url]
36
+ `;
37
+ const USAGE_TEXT = ` npx @relyon/store-kit init [--pages] --template next|express [--dir <new-or-empty-directory>] [--store "<store idea>"] [--skip-install] [--auto-test-key]
38
+ npx @relyon/store-kit doctor [--url <origin>] [--feeds <formats>] [--strict] [--live] [--base-url <url>] [--webhook-path <path>] [--checkout-path <path>] [--allow-saved-key-to-base-url] [--json]
39
+ npx @relyon/store-kit test-checkout --url <origin> [--product <id>] [--idempotency-key <id>] [--base-url <url>] [--allow-saved-key-to-base-url]
40
+ npx @relyon/store-kit webhook [--url <origin>] [--webhook-path <path>] [--rotate] [--base-url <url>] [--allow-saved-key-to-base-url]
41
+
42
+ init: sets up the app in the current directory for a coding agent. Run it in the app's directory.
43
+ First choose a layer (init asks on a terminal; a script must pass one flag, or init refuses):
44
+ --payments Accept card payments in your own app: payment session, card fields, charge,
45
+ refund and webhook verification helpers (relyon/payments.ts for Express, Next.js
46
+ or a plain Node server), the relyon-payments skill and an agent-instructions
47
+ block. No product catalog, feeds, /cart page or store hostnames.
48
+ Then run check. --framework picks the helper's style (default: from package.json).
49
+ --products Also list products so AI shopping agents can find and buy them. The doctor
50
+ is the gate; no /cart page is required.
51
+ --pages Also have Relyon's kit build the shopping pages (--template implies it).
52
+ The doctor is the gate and requires a real /cart page.
53
+ The layer is recorded in relyon/kit.json for the doctor and check.
54
+ Adds @relyon/store-kit@${KIT_VERSION} (exact version) with the app's package manager, picked from its
55
+ lockfile (pnpm, yarn, bun, else npm), unless that version is already installed; creates a minimal
56
+ private package.json if there is none. Copies the six Relyon skills to .agents/skills (Codex,
57
+ Replit Agent, OpenCode), .claude/skills (Claude Code) and .cursor/skills (Cursor), and adds a
58
+ pointer in AGENTS.md and CLAUDE.md, and a marked "definition of done" block (relyon-done) in
59
+ AGENTS.md, CLAUDE.md and replit.md. Read the copied relyon/QUICKSTART.md first.
60
+ Open a skill only when a numbered step names its section. Build before requesting a key.
61
+ Non-interactive; never prints secrets.
62
+ Init never creates sandboxes: open https://core.getrelyon.com/get-sandbox-key (signed in) to
63
+ create one and copy its Test key, then run init --key-from-stdin. A key is saved privately:
64
+ in RELYON_PRIVATE_DIR when set, else the first usable of $XDG_CONFIG_HOME/relyon/<project>
65
+ and ~/.config/relyon/<project>. Each must be an owner-only folder outside the app and every
66
+ git tree. Init also sets RELYON_API_KEY in .env (0600, listed in .gitignore;
67
+ never when .env is tracked by git). RELYON_LIVE=true keeps init off the saved Test key.
68
+ The .env key is readable by coding agents working in the app, and remixes, forks and exports
69
+ of the project copy .env with it. An existing .dockerignore gets .env added.
70
+ If RELYON_API_KEY is in the environment, use it and write no key file.
71
+ Before publishing, add RELYON_API_KEY in the host's environment settings.
72
+ Get your Test key from the Relyon dashboard; never paste keys in chat.
73
+ Placeholder or malformed keys (empty, your_key_here, changeme) count as no key.
74
+ --key-from-stdin Read a Test key from stdin, or a hidden prompt, and save it the same way.
75
+ Never pass a key as an argument.
76
+ --store "<idea>" Write the merchant's store idea word for word to ${STORE_BRIEF_FILE}
77
+ (at most ${STORE_IDEA_MAX} characters; an idea containing a key is refused).
78
+ --force Replace differing Relyon skill files, quick start and store brief, and only the marked
79
+ Relyon block in AGENTS.md and CLAUDE.md. An AGENTS.md or CLAUDE.md without the
80
+ block gets it appended (no --force needed); its other lines stay as they are.
81
+ --skip-install Don't add the package.
82
+ --auto-test-key Accepted for scripts; init no longer creates sandboxes, so it changes
83
+ nothing (same for ${AUTO_TEST_KEY_ENV}=true).
84
+ --yes Accepted for scripts; init never asks questions.
85
+ --agent-hooks Also add a stop hook for Claude Code (.claude/settings.json), Cursor
86
+ (.cursor/hooks.json) and Copilot (.github/hooks/relyon.json): while doctor says
87
+ NOT DONE, the agent is asked to continue with the next steps, at most 3 times
88
+ per session. Merged into existing hook files; other hooks are kept. Off by default.
89
+ Identical files are skipped, so running init again changes nothing.
90
+ --template Write a pinned working Test store in a completely empty or new directory.
91
+ Hidden entries and links are refused; --force never bypasses this.
92
+ --dir Template target (default current directory); parent must already exist.
93
+ A template written with --dir is a scratch copy; add a Test key to it with
94
+ init --key-from-stdin.
95
+ The server loads the key with loadTestConfig() from @relyon/store-kit/server-config (or dotenv).
96
+ Never cat or print .env, and never paste the key into a command.
97
+
98
+ check:
99
+
100
+ The short check for a payments-only app (init --payments). Four steps, each needing the one
101
+ before: a Test key is present; Relyon creates a payment session; a mock Test charge succeeds;
102
+ a webhook signature verifies. The first line is "DONE: payments verified in Test." or
103
+ "NOT DONE: <n> of 4 steps remain."; every failing step says what to fix. When the workspace's
104
+ Test processor isn't Relyon's mock, the charge step is NOT RUN (never passed). It sends
105
+ RELYON_PROJECT_SPACE, when set, to name the project space. Test only; keys are never printed. Exit codes: 0 DONE; 1 a step failed or was not run; 2 refused (Live, usage).
106
+
107
+ doctor:
108
+
109
+ Checks what agents and Relyon see on the store's public URL, then runs Relyon's
110
+ integration doctor and reads whether Relyon confirmed a completed Test checkout. The first line
111
+ is "DONE: Test integration verified by Relyon." or "NOT DONE: <n> of <m> required steps remain."
112
+ followed by a numbered "Do this next" list; then PASS, FAIL, WARN, PENDING merchant, PENDING,
113
+ N/A or UNVERIFIED per item (PENDING merchant carries an owner to-do; plain PENDING is an
114
+ agent's own next step, such as running the webhook command after publish). DONE needs a Test key,
115
+ no FAIL, the store's checkout page and a sample of
116
+ its product pages answering 200 on its origin, Relyon's confirmation of one completed
117
+ Test checkout and every selected feed live. It changes nothing in the store and never submits
118
+ a payment; Relyon's diagnostic may create and clean up one temporary system checkout.
119
+ In Test, missing merchant facts can be PENDING merchant; DONE is not Live readiness.
120
+ Agent checkout remains off until merchant confirmation and policy setup.
121
+ Exit codes: 0 DONE; 2 NOT DONE without any FAIL (the work is incomplete); 1 any FAIL;
122
+ usage errors 2.
123
+ --strict Treat Test merchant-pending items as FAIL (exit 1). Live is always strict.
124
+ --json Print one JSON object on stdout and nothing else: status ("done" or
125
+ "not_done"), version, checks, next_steps, confirmed and kit_version.
126
+ Version evidence is advisory; unavailable fields are null. Same exit codes.
127
+ --webhook-path <path> The kit's webhook path when paths.webhook isn't the default /relyon/webhooks.
128
+ --checkout-path <path> The store's checkout page for shoppers when paths.checkout isn't the default /checkout.
129
+ --allow-saved-key-to-base-url
130
+ Send the saved Test key (private folder or .env) to a custom or plain-http
131
+ Relyon base URL. Without it the saved key goes only to ${DEFAULT_RELYON_BASE_URL}.
132
+
133
+ test-checkout:
134
+
135
+ Completes ONE Test purchase on the store, so Relyon confirms a completed Test checkout (the doctor's
136
+ "Test checkout confirmed by Relyon" step). It posts to the store kit's own Test-only route
137
+ (/relyon/test-checkout) with a short-lived proof signed by the store's Test key; the key itself is
138
+ never sent to the store or printed. The kit prices one agent-purchasable product with the store's
139
+ priceCart, pays it with Relyon's Test mock processor token (no card number exists anywhere) and
140
+ runs the store's createOrder. Retries resend the same request, so one run never pays twice.
141
+ It refuses Live keys and RELYON_LIVE=true. Then it reads Relyon's confirmation and names the next step.
142
+ Exit codes: 0 purchase done; 1 failed or not confirmed; 2 refused to run (usage, Live or no Test key).
143
+ --product <id> Buy this product or variant feed ID (default: a product without options,
144
+ else the first listed variant, else the first value of each option).
145
+ --idempotency-key <id> Resend an earlier run's request (printed when one may need resending).
146
+
147
+ webhook:
148
+
149
+ Registers the store's webhook endpoint (<origin>/relyon/webhooks, event: agent_rules.updated) with
150
+ Relyon. With RELYON_API_KEY from the environment it writes no file: the receiver resolves
151
+ the signing secret at runtime, in Test and Live. Only a local file key saves RELYON_WEBHOOK_SECRET in the project's
152
+ .env (0600, git-ignored, never when .env is tracked by git).
153
+ The secret is never printed. Run it after publish, and re-run it whenever the store's public URL
154
+ changes. There is one endpoint per URL: when an active endpoint already exists (the dashboard's or
155
+ an older registration's), the command adopts it and saves its current secret instead of registering
156
+ a duplicate, and a Test registration replays without expiry to recover the secret — a replacement
157
+ Test key in the same store recovers it too. RELYON_WEBHOOK_SECRET in the environment remains
158
+ an optional explicit override. With an environment API key, --rotate rotates without saving
159
+ anything; runtime resolution picks up the new secret (unset or update an explicit override).
160
+ It needs a public https store URL and refuses preview, loopback, IP-literal and single-label hosts.
161
+ Live works the same way once Relyon staff approved it: the store's Live key in RELYON_API_KEY
162
+ (with or without RELYON_LIVE=true), no file, runtime resolution.
163
+ Exit codes: 0 registered (or already registered); 1 the registration or the .env write failed;
164
+ 2 refused to run (usage, a non-https URL, or no usable key for the mode).
165
+ --webhook-path <path> When the kit's paths.webhook isn't the default /relyon/webhooks.
166
+ --rotate Rotate the endpoint's signing secret in place (same endpoint, fresh
167
+ secret) — only when the saved secret was lost or must be replaced.
168
+
169
+ Environment:
170
+ PUBLIC_URL The app's public origin, such as https://shop.example.com (or --url).
171
+ STORE_PUBLIC_URL is still read when PUBLIC_URL isn't an absolute URL.
172
+ RELYON_PROJECT_SPACE The project space's ID; optional in a single-space workspace.
173
+ RELYON_API_KEY The store's secret key. Without it Relyon's doctor is UNVERIFIED. Never printed.
174
+ RELYON_PRIVATE_DIR Optional verified private POSIX directory for init and the server-config loader
175
+ (default: $XDG_CONFIG_HOME/relyon/<project>, else ~/.config/relyon/<project>).
176
+ RELYON_LIVE "true" to check in Live mode (or --live); needs a Live key.
177
+ RELYON_CART_TRANSFER_KEY The store's cart-transfer caller key, when it requires one: Test doctor sends it
178
+ only to the store's own /ucp/carts to transfer a real item. Never printed.
179
+ RELYON_BASE_URL Relyon's API base URL (or --base-url). Default ${DEFAULT_RELYON_BASE_URL}.
180
+ RELYON_FEEDS The store's selected feeds (or --feeds), comma separated:
181
+ ${Object.keys(STORE_FEED_PATHS).join(", ")}. Default: those llms.txt advertises.
182
+ `;
183
+ /** The help text, naming the package that is running. */
184
+ const usage = () => kitIdentity().name === STORE_KIT_PACKAGE
185
+ ? USAGE_STORE_KIT + USAGE_TEXT.replace("First choose a layer (init asks on a terminal; a script must pass one flag, or init refuses):", "Optionally choose a layer (without one, the store kit sets up a store as before):")
186
+ .replace(/\n --payments [\s\S]*?Then run check\. --framework picks the helper's style \(default: from package\.json\)\.\n/, "\n --payments Payments only is in the new package: npx @relyon/kit init --payments.\n")
187
+ : forKitPackage(USAGE_LAYERS + USAGE_TEXT);
188
+ class UsageError extends Error {
189
+ }
190
+ /**
191
+ * Reads one key for `init --key-from-stdin`: piped stdin, or a prompt on the
192
+ * terminal that echoes nothing. The key is never printed.
193
+ */
194
+ async function readKeyFromStdin() {
195
+ const input = process.stdin;
196
+ if (!input.isTTY) {
197
+ let text = "";
198
+ for await (const chunk of input) {
199
+ text += String(chunk);
200
+ if (text.length > 4096)
201
+ throw new UsageError("The key input is too long. Nothing was saved.");
202
+ }
203
+ return text.split(/\r?\n/).find((line) => line.trim()) ?? "";
204
+ }
205
+ process.stderr.write("Paste the Relyon Test key from the get-key page, then press Enter. Nothing is shown while you type: ");
206
+ return new Promise((resolve, reject) => {
207
+ let value = "";
208
+ input.setRawMode(true);
209
+ input.resume();
210
+ input.setEncoding("utf8");
211
+ const finish = (error) => {
212
+ input.setRawMode(false);
213
+ input.pause();
214
+ input.removeListener("data", onData);
215
+ process.stderr.write("\n");
216
+ if (error)
217
+ reject(error);
218
+ else
219
+ resolve(value);
220
+ };
221
+ const onData = (chunk) => {
222
+ for (const char of chunk) {
223
+ if (char === "\r" || char === "\n")
224
+ return finish();
225
+ if (char === "\u0003" || char === "\u0004")
226
+ return finish(new UsageError("Cancelled. Nothing was saved."));
227
+ if (char === "\u007f" || char === "\b")
228
+ value = value.slice(0, -1);
229
+ else if (char >= " ")
230
+ value += char;
231
+ if (value.length > 4096)
232
+ return finish(new UsageError("The key input is too long. Nothing was saved."));
233
+ }
234
+ };
235
+ input.on("data", onData);
236
+ });
237
+ }
238
+ function parse(argv, env) {
239
+ const [command, ...rest] = argv;
240
+ if (command === undefined || command === "help" || command === "--help" || command === "-h")
241
+ return { help: true };
242
+ if (command === "init")
243
+ return parseInit(rest);
244
+ if (command === "test-checkout")
245
+ return parseTestCheckout(rest, env);
246
+ if (command === "webhook")
247
+ return parseWebhook(rest, env);
248
+ if (command === "check")
249
+ return parseCheck(rest, env);
250
+ if (command !== "doctor")
251
+ throw new UsageError(`Unknown command "${command}".`);
252
+ const flags = {};
253
+ for (let i = 0; i < rest.length; i++) {
254
+ const arg = rest[i];
255
+ if (arg === "--help" || arg === "-h")
256
+ return { help: true };
257
+ if (arg === "--live") {
258
+ flags.live = true;
259
+ continue;
260
+ }
261
+ if (arg === "--strict") {
262
+ flags.strict = true;
263
+ continue;
264
+ }
265
+ if (arg === "--allow-saved-key-to-base-url") {
266
+ flags.allowSavedKey = true;
267
+ continue;
268
+ }
269
+ if (arg === "--json") {
270
+ flags.json = true;
271
+ continue;
272
+ }
273
+ const match = /^--(url|feeds|base-url|webhook-path|checkout-path)(?:=(.*))?$/.exec(arg);
274
+ if (!match)
275
+ throw new UsageError(`Unknown option "${arg.split("=")[0]}". Keys are read from RELYON_API_KEY only.`);
276
+ const value = match[2] ?? rest[++i];
277
+ if (value === undefined || value === "")
278
+ throw new UsageError(`--${match[1]} needs a value.`);
279
+ flags[match[1]] = value;
280
+ }
281
+ const storeUrl = flags.url ?? publicUrlFromEnv(env);
282
+ if (!storeUrl)
283
+ throw new UsageError("Set STORE_PUBLIC_URL (or pass --url) to the store's public origin.");
284
+ const liveEnv = env.RELYON_LIVE?.trim().toLowerCase();
285
+ if (liveEnv !== undefined && liveEnv !== "" && liveEnv !== "true" && liveEnv !== "false")
286
+ throw new UsageError('RELYON_LIVE must be "true" or "false".');
287
+ const feedList = flags.feeds ?? env.RELYON_FEEDS;
288
+ let feeds;
289
+ if (feedList !== undefined && feedList.trim() !== "") {
290
+ feeds = feedList.split(",").map((value) => value.trim()).filter(Boolean);
291
+ const unknown = feeds.filter((format) => !(format in STORE_FEED_PATHS));
292
+ if (unknown.length)
293
+ throw new UsageError(`Unknown feed format ${unknown.join(", ")}. Use ${Object.keys(STORE_FEED_PATHS).join(", ")}.`);
294
+ }
295
+ return {
296
+ help: false, command: "doctor", storeUrl, feeds,
297
+ apiKey: env.RELYON_API_KEY?.trim() || undefined,
298
+ live: flags.live === true || liveEnv === "true",
299
+ strict: flags.strict === true,
300
+ allowSavedKey: flags.allowSavedKey === true,
301
+ webhookPath: flags["webhook-path"],
302
+ checkoutPath: flags["checkout-path"],
303
+ json: flags.json === true,
304
+ baseUrl: flags["base-url"] ?? (env.RELYON_BASE_URL?.trim() || DEFAULT_RELYON_BASE_URL),
305
+ };
306
+ }
307
+ function parseInit(rest) {
308
+ let layer;
309
+ let framework;
310
+ let store;
311
+ let template;
312
+ let directory;
313
+ let force = false;
314
+ let skipInstall = false;
315
+ let keyFromStdin = false;
316
+ let agentHooks = false;
317
+ let autoTestKey = false;
318
+ for (let i = 0; i < rest.length; i++) {
319
+ const arg = rest[i];
320
+ if (arg === "--help" || arg === "-h")
321
+ return { help: true };
322
+ if (arg === "--force") {
323
+ force = true;
324
+ continue;
325
+ }
326
+ if (arg === "--skip-install") {
327
+ skipInstall = true;
328
+ continue;
329
+ }
330
+ if (arg === "--key-from-stdin") {
331
+ keyFromStdin = true;
332
+ continue;
333
+ }
334
+ if (arg === "--auto-test-key") {
335
+ autoTestKey = true;
336
+ continue;
337
+ }
338
+ if (arg === "--agent-hooks") {
339
+ agentHooks = true;
340
+ continue;
341
+ }
342
+ if (arg === "--payments" || arg === "--products" || arg === "--pages") {
343
+ const chosen = arg.slice(2);
344
+ if (layer !== undefined && layer !== chosen)
345
+ throw new UsageError("Pass one layer: --payments, --products or --pages.");
346
+ layer = chosen;
347
+ continue;
348
+ }
349
+ if (arg === "--framework" || arg.startsWith("--framework=")) {
350
+ if (framework !== undefined)
351
+ throw new UsageError("Pass --framework once.");
352
+ const value = arg === "--framework" ? rest[++i] : arg.slice("--framework=".length);
353
+ if (value !== "express" && value !== "next" && value !== "node")
354
+ throw new UsageError("--framework needs express, next or node.");
355
+ framework = value;
356
+ continue;
357
+ }
358
+ // Init is non-interactive; --yes is accepted so scripts that pass it don't fail.
359
+ if (arg === "--yes" || arg === "-y")
360
+ continue;
361
+ if (arg === "--template" || arg.startsWith("--template=")) {
362
+ if (template !== undefined)
363
+ throw new UsageError("Pass --template once.");
364
+ const value = arg === "--template" ? rest[++i] : arg.slice("--template=".length);
365
+ if (value !== "next" && value !== "express")
366
+ throw new UsageError("--template needs next or express.");
367
+ template = value;
368
+ continue;
369
+ }
370
+ if (arg === "--dir" || arg.startsWith("--dir=")) {
371
+ if (directory !== undefined)
372
+ throw new UsageError("Pass --dir once.");
373
+ const value = arg === "--dir" ? rest[++i] : arg.slice("--dir=".length);
374
+ if (!value || value.startsWith("--"))
375
+ throw new UsageError("--dir needs a target directory.");
376
+ directory = value;
377
+ continue;
378
+ }
379
+ if (arg === "--store" || arg.startsWith("--store=")) {
380
+ if (store !== undefined)
381
+ throw new UsageError("Pass --store once.");
382
+ const value = arg === "--store" ? rest[++i] : arg.slice("--store=".length);
383
+ if (value === undefined)
384
+ throw new UsageError("--store needs the store idea, in quotes.");
385
+ store = value;
386
+ continue;
387
+ }
388
+ // Never echo the argument: it may be a mistyped key.
389
+ throw new UsageError(arg.startsWith("-") ? "Unknown init option. Init takes --payments, --products, --pages, --framework, --template, --dir, --store, --force, --skip-install, --key-from-stdin, --auto-test-key, --agent-hooks and --yes. Keys are never taken as arguments." : "Unexpected init argument. Put the store idea in quotes after --store.");
390
+ }
391
+ if (directory !== undefined && !template)
392
+ throw new UsageError("--dir is available only with --template.");
393
+ if (template && layer && layer !== "pages")
394
+ throw new UsageError("--template writes Relyon's shopping pages, which is the pages layer: use --template with --pages (or alone).");
395
+ // Run as @relyon/kit, a template is the pages layer; the store kit keeps its own init.
396
+ if (template && kitIdentity().name !== STORE_KIT_PACKAGE)
397
+ layer = "pages";
398
+ if (layer === "payments" && kitIdentity().name === STORE_KIT_PACKAGE) {
399
+ throw new UsageError("Payments-only setup is in the new package: run npx @relyon/kit init --payments (the store kit is for stores).");
400
+ }
401
+ if (layer === "payments" && store !== undefined)
402
+ throw new UsageError("--store describes a store's products and pages; payments-only init (--payments) takes no store idea.");
403
+ if (layer === "payments" && agentHooks)
404
+ throw new UsageError("--agent-hooks runs the doctor, which is for --products and --pages; payments-only apps use check.");
405
+ if (framework !== undefined && layer !== "payments")
406
+ throw new UsageError("--framework is available only with --payments.");
407
+ return { help: false, command: "init", layer, framework, store, force, skipInstall, template, directory, keyFromStdin, autoTestKey, agentHooks };
408
+ }
409
+ function parseTestCheckout(rest, env) {
410
+ const flags = {};
411
+ for (let i = 0; i < rest.length; i++) {
412
+ const arg = rest[i];
413
+ if (arg === "--help" || arg === "-h")
414
+ return { help: true };
415
+ if (arg === "--allow-saved-key-to-base-url") {
416
+ flags.allowSavedKey = true;
417
+ continue;
418
+ }
419
+ const match = /^--(url|base-url|product|idempotency-key)(?:=(.*))?$/.exec(arg);
420
+ // Never echo the argument: it may be a mistyped key.
421
+ if (!match)
422
+ throw new UsageError("Unknown test-checkout option. It takes --url, --product, --idempotency-key, --base-url and --allow-saved-key-to-base-url. Keys are never taken as arguments.");
423
+ if (flags[match[1]] !== undefined)
424
+ throw new UsageError(`Pass --${match[1]} once.`);
425
+ const value = match[2] ?? rest[++i];
426
+ if (value === undefined || value === "" || value.startsWith("--"))
427
+ throw new UsageError(`--${match[1]} needs a value.`);
428
+ flags[match[1]] = value;
429
+ }
430
+ const storeUrl = flags.url ?? publicUrlFromEnv(env);
431
+ if (!storeUrl)
432
+ throw new UsageError("Pass --url (or set STORE_PUBLIC_URL) to the store's origin.");
433
+ const liveEnv = env.RELYON_LIVE?.trim().toLowerCase();
434
+ if (liveEnv !== undefined && liveEnv !== "" && liveEnv !== "true" && liveEnv !== "false")
435
+ throw new UsageError('RELYON_LIVE must be "true" or "false".');
436
+ return {
437
+ help: false, command: "test-checkout", storeUrl, live: liveEnv === "true",
438
+ apiKey: env.RELYON_API_KEY?.trim() || undefined,
439
+ productId: flags.product, idempotencyKey: flags["idempotency-key"],
440
+ allowSavedKey: flags.allowSavedKey === true,
441
+ baseUrl: flags["base-url"] ?? (env.RELYON_BASE_URL?.trim() || DEFAULT_RELYON_BASE_URL),
442
+ };
443
+ }
444
+ function parseWebhook(rest, env) {
445
+ const flags = {};
446
+ for (let i = 0; i < rest.length; i++) {
447
+ const arg = rest[i];
448
+ if (arg === "--help" || arg === "-h")
449
+ return { help: true };
450
+ if (arg === "--rotate") {
451
+ if (flags.rotate)
452
+ throw new UsageError("Pass --rotate once.");
453
+ flags.rotate = true;
454
+ continue;
455
+ }
456
+ if (arg === "--allow-saved-key-to-base-url") {
457
+ flags.allowSavedKey = true;
458
+ continue;
459
+ }
460
+ const match = /^--(url|webhook-path|base-url)(?:=(.*))?$/.exec(arg);
461
+ // Never echo the argument: it may be a mistyped key.
462
+ if (!match)
463
+ throw new UsageError("Unknown webhook option. It takes --url, --webhook-path, --rotate, --base-url and --allow-saved-key-to-base-url. Keys are never taken as arguments.");
464
+ if (flags[match[1]] !== undefined)
465
+ throw new UsageError(`Pass --${match[1]} once.`);
466
+ const value = match[2] ?? rest[++i];
467
+ if (value === undefined || value === "" || value.startsWith("--"))
468
+ throw new UsageError(`--${match[1]} needs a value.`);
469
+ flags[match[1]] = value;
470
+ }
471
+ const storeUrl = flags.url ?? publicUrlFromEnv(env);
472
+ if (!storeUrl)
473
+ throw new UsageError("Pass --url (or set STORE_PUBLIC_URL) to the store's public origin.");
474
+ const liveEnv = env.RELYON_LIVE?.trim().toLowerCase();
475
+ if (liveEnv !== undefined && liveEnv !== "" && liveEnv !== "true" && liveEnv !== "false")
476
+ throw new UsageError('RELYON_LIVE must be "true" or "false".');
477
+ return {
478
+ help: false, command: "webhook", storeUrl, live: liveEnv === "true",
479
+ apiKey: env.RELYON_API_KEY?.trim() || undefined,
480
+ webhookPath: flags["webhook-path"],
481
+ rotate: flags.rotate === true,
482
+ allowSavedKey: flags.allowSavedKey === true,
483
+ baseUrl: flags["base-url"] ?? (env.RELYON_BASE_URL?.trim() || DEFAULT_RELYON_BASE_URL),
484
+ };
485
+ }
486
+ function parseCheck(rest, env) {
487
+ const flags = {};
488
+ for (let i = 0; i < rest.length; i++) {
489
+ const arg = rest[i];
490
+ if (arg === "--help" || arg === "-h")
491
+ return { help: true };
492
+ if (arg === "--allow-saved-key-to-base-url") {
493
+ flags.allowSavedKey = true;
494
+ continue;
495
+ }
496
+ const match = /^--(base-url)(?:=(.*))?$/.exec(arg);
497
+ // Never echo the argument: it may be a mistyped key.
498
+ if (!match)
499
+ throw new UsageError("Unknown check option. It takes --base-url and --allow-saved-key-to-base-url. Keys are never taken as arguments.");
500
+ if (flags[match[1]] !== undefined)
501
+ throw new UsageError(`Pass --${match[1]} once.`);
502
+ const value = match[2] ?? rest[++i];
503
+ if (value === undefined || value === "" || value.startsWith("--"))
504
+ throw new UsageError(`--${match[1]} needs a value.`);
505
+ flags[match[1]] = value;
506
+ }
507
+ const liveEnv = env.RELYON_LIVE?.trim().toLowerCase();
508
+ if (liveEnv !== undefined && liveEnv !== "" && liveEnv !== "true" && liveEnv !== "false")
509
+ throw new UsageError('RELYON_LIVE must be "true" or "false".');
510
+ return {
511
+ help: false, command: "check", live: liveEnv === "true",
512
+ apiKey: env.RELYON_API_KEY?.trim() || undefined,
513
+ projectSpace: env[PROJECT_SPACE_ENV]?.trim() || undefined,
514
+ allowSavedKey: flags.allowSavedKey === true,
515
+ baseUrl: flags["base-url"] ?? (env.RELYON_BASE_URL?.trim() || DEFAULT_RELYON_BASE_URL),
516
+ };
517
+ }
518
+ /** `check`: the payments-only app's four steps, ending with DONE. */
519
+ async function checkCommand(parsed, secrets) {
520
+ // Test only: nothing saved is read in Live; nor when RELYON_API_KEY is usable.
521
+ const saved = parsed.live || usableApiKey(parsed.apiKey) ? {} : await loadTestConfig({ project: process.cwd() }).catch(() => ({}));
522
+ if (saved.apiKey)
523
+ secrets.push(saved.apiKey);
524
+ const webhookSecret = process.env.RELYON_WEBHOOK_SECRET?.trim() || saved.webhookSecret;
525
+ if (webhookSecret)
526
+ secrets.push(webhookSecret);
527
+ const result = await runCheck({
528
+ envKey: parsed.apiKey, savedKey: saved.apiKey, live: parsed.live, baseUrl: parsed.baseUrl,
529
+ allowSavedKeyToBaseUrl: parsed.allowSavedKey, ...(webhookSecret ? { webhookSecret } : {}),
530
+ ...(parsed.projectSpace ? { projectSpace: parsed.projectSpace } : {}),
531
+ });
532
+ // A products or pages app is judged by the doctor; check covers only its payments.
533
+ const recorded = (await readKitConfig(process.cwd()))?.layer;
534
+ const gate = recorded && recorded !== "payments"
535
+ ? [`This app recorded the ${recorded} layer in relyon/kit.json: check covers only its payments; ${kitCommand()} doctor is its full check.`]
536
+ : [];
537
+ const text = redactSecrets(`${[...result.lines, ...gate].join("\n")}\n`, secrets);
538
+ if (result.exitCode === 0)
539
+ process.stdout.write(text);
540
+ else
541
+ process.stderr.write(text);
542
+ return result.exitCode;
543
+ }
544
+ /**
545
+ * The layer for `init`: the flag, else (run as @relyon/kit) the answer to
546
+ * one question on a terminal. A script without a flag is refused: init
547
+ * never guesses. Run as @relyon/store-kit, no flag keeps the store kit's
548
+ * own init (no layer recorded).
549
+ */
550
+ async function chooseLayer(given) {
551
+ if (given)
552
+ return given;
553
+ if (kitIdentity().name === STORE_KIT_PACKAGE)
554
+ return undefined;
555
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
556
+ return null;
557
+ const { createInterface } = await import("node:readline/promises");
558
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
559
+ try {
560
+ process.stdout.write("Which do you want?\n");
561
+ KIT_LAYERS.forEach((layer, index) => process.stdout.write(` ${index + 1}) ${KIT_LAYER_LABELS[layer]}\n`));
562
+ for (let tries = 0; tries < 3; tries++) {
563
+ const answer = (await rl.question("Choose 1, 2 or 3: ")).trim().toLowerCase();
564
+ const index = ["1", "2", "3"].indexOf(answer);
565
+ if (index !== -1)
566
+ return KIT_LAYERS[index];
567
+ if (isKitLayer(answer))
568
+ return answer;
569
+ }
570
+ return null;
571
+ }
572
+ finally {
573
+ rl.close();
574
+ }
575
+ }
576
+ /** Printed when init has no layer and can't ask. */
577
+ const LAYER_REQUIRED = () => [
578
+ "init needs a layer and won't guess. Ask the user which they want, then pass one flag:",
579
+ ...KIT_LAYERS.map((layer) => ` --${layer.padEnd(9)} ${KIT_LAYER_LABELS[layer]}`),
580
+ `For example: ${kitCommand()} init --payments`,
581
+ "Nothing was written.",
582
+ ].join("\n");
583
+ /** `webhook`: register the endpoint, saving a secret only for local file-key development. */
584
+ async function webhookCommand(parsed, secrets) {
585
+ // Test-only: nothing saved is read in Live; nor when RELYON_API_KEY is usable.
586
+ const saved = parsed.live || usableApiKey(parsed.apiKey) ? {} : await loadTestConfig({ project: process.cwd() }).catch(() => ({}));
587
+ if (saved.apiKey)
588
+ secrets.push(saved.apiKey);
589
+ const result = await runWebhookCommand({
590
+ storeUrl: parsed.storeUrl, envKey: parsed.apiKey, savedKey: saved.apiKey, live: parsed.live, baseUrl: parsed.baseUrl,
591
+ ...(parsed.webhookPath ? { webhookPath: parsed.webhookPath } : {}),
592
+ rotate: parsed.rotate, allowSavedKeyToBaseUrl: parsed.allowSavedKey,
593
+ });
594
+ const text = redactSecrets(`${result.lines.join("\n")}\n`, secrets);
595
+ if (result.exitCode === 0)
596
+ process.stdout.write(text);
597
+ else
598
+ process.stderr.write(text);
599
+ return result.exitCode;
600
+ }
601
+ /** `test-checkout`: one Test purchase through the store's kit route, then Relyon's confirmation. */
602
+ async function testCheckoutCommand(parsed, secrets) {
603
+ // L3: in Live nothing saved is read; nor when RELYON_API_KEY is usable.
604
+ const saved = parsed.live || usableApiKey(parsed.apiKey) ? {} : await loadTestConfig({ project: process.cwd() }).catch(() => ({}));
605
+ if (saved.apiKey)
606
+ secrets.push(saved.apiKey);
607
+ const result = await runTestCheckoutCommand({
608
+ storeUrl: parsed.storeUrl, envKey: parsed.apiKey, savedKey: saved.apiKey, live: parsed.live, baseUrl: parsed.baseUrl,
609
+ productId: parsed.productId, idempotencyKey: parsed.idempotencyKey, allowSavedKeyToBaseUrl: parsed.allowSavedKey,
610
+ });
611
+ const text = redactSecrets(`${result.lines.join("\n")}\n`, secrets);
612
+ if (result.exitCode === 0)
613
+ process.stdout.write(text);
614
+ else
615
+ process.stderr.write(text);
616
+ return result.exitCode;
617
+ }
618
+ /**
619
+ * Hidden: `doctor --agent-hook claude|cursor|copilot`, run by a coding agent's
620
+ * stop hook. Reads the event on stdin, answers in the tool's format, always exits 0.
621
+ */
622
+ async function agentHookCommand(argv) {
623
+ const tool = argv[argv.indexOf("--agent-hook") + 1];
624
+ if (!isAgentHookTool(tool))
625
+ return 0;
626
+ const answer = await runAgentHook(tool, { stdin: await readHookStdin().catch(() => ""), env: process.env, cwd: process.cwd() });
627
+ if (answer.stdout)
628
+ process.stdout.write(answer.stdout);
629
+ if (answer.stderr)
630
+ process.stderr.write(redactSecrets(answer.stderr, [process.env.RELYON_API_KEY]));
631
+ // Fail open on time: a doctor run that lost the deadline race may still hold sockets or
632
+ // timers, so flush the answer and exit now instead of waiting for them.
633
+ await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve()))));
634
+ process.exit(answer.exitCode);
635
+ }
636
+ /** `doctor` (and `doctor --json`): the verdict, the next steps and every item. */
637
+ async function doctorCommand(parsed, secrets) {
638
+ // L3: in Live (--live or RELYON_LIVE=true) the saved Test key is never read; nor when RELYON_API_KEY is usable.
639
+ const saved = parsed.live || usableApiKey(parsed.apiKey) ? {} : await loadTestConfig({ project: process.cwd() }).catch(() => ({}));
640
+ if (saved.apiKey)
641
+ secrets.push(saved.apiKey);
642
+ secrets.push(process.env[CART_TRANSFER_KEY_ENV]);
643
+ // The webhook signing secret, environment first (loadTestConfig resolves
644
+ // env, then the project's private files), so the doctor can prove the
645
+ // running store accepts it. Never printed.
646
+ const webhookSecret = process.env.RELYON_WEBHOOK_SECRET?.trim() || saved.webhookSecret;
647
+ if (webhookSecret)
648
+ secrets.push(webhookSecret);
649
+ // A placeholder RELYON_API_KEY counts as no key; the saved private key is used then.
650
+ const envKey = usableApiKey(parsed.apiKey);
651
+ const report = await runDoctorReport({
652
+ storeUrl: parsed.storeUrl, apiKey: envKey ?? saved.apiKey ?? parsed.apiKey, baseUrl: parsed.baseUrl, feeds: parsed.feeds,
653
+ strict: parsed.strict, projectDir: process.cwd(),
654
+ // A saved key goes only to Relyon's official https API unless --allow-saved-key-to-base-url says otherwise.
655
+ keySource: envKey ? "env" : saved.apiKey ? "saved" : undefined,
656
+ allowSavedKeyToBaseUrl: parsed.allowSavedKey,
657
+ ...(parsed.live ? { live: true } : {}),
658
+ ...(parsed.webhookPath ? { webhookPath: parsed.webhookPath } : {}),
659
+ ...(parsed.checkoutPath ? { checkoutPath: parsed.checkoutPath } : {}),
660
+ // Test: the store's cart-transfer caller key, sent only to its own /ucp/carts. Never printed.
661
+ ...(process.env[CART_TRANSFER_KEY_ENV] ? { cartTransferKey: process.env[CART_TRANSFER_KEY_ENV] } : {}),
662
+ ...(webhookSecret ? { webhookSecret } : {}),
663
+ });
664
+ if (parsed.json)
665
+ process.stdout.write(`${JSON.stringify(doctorJson(report, secrets))}\n`);
666
+ else
667
+ process.stdout.write(formatDoctorReport(report, secrets));
668
+ return doctorExitCode(report);
669
+ }
670
+ /**
671
+ * Run as `@relyon/kit`, every command the kit prints names `@relyon/kit`
672
+ * (the kit's shared text names the store kit, which the wrapper keeps).
673
+ */
674
+ function nameThisPackageInOutput() {
675
+ if (kitIdentity().name === STORE_KIT_PACKAGE)
676
+ return;
677
+ for (const stream of [process.stdout, process.stderr]) {
678
+ const write = stream.write.bind(stream);
679
+ stream.write = ((chunk, ...rest) => write(typeof chunk === "string" ? forKitPackage(chunk) : chunk, ...rest));
680
+ }
681
+ }
682
+ async function main() {
683
+ nameThisPackageInOutput();
684
+ const secrets = [process.env.RELYON_API_KEY];
685
+ try {
686
+ const argv = process.argv.slice(2);
687
+ if (argv[0] === "doctor" && argv.includes("--agent-hook"))
688
+ return await agentHookCommand(argv);
689
+ if (argv[0] === "doctor" && !argv.some((arg) => arg === "--help" || arg === "-h") && (await readKitConfig(process.cwd()))?.layer === "payments") {
690
+ process.stderr.write(`This app uses payments only (relyon/kit.json records layer 1), so the doctor doesn't apply: run ${kitCommand()} check instead. The doctor is for --products and --pages apps.\n`);
691
+ return 2;
692
+ }
693
+ const parsed = parse(argv, process.env);
694
+ if (parsed.help) {
695
+ process.stdout.write(usage());
696
+ return 0;
697
+ }
698
+ if (parsed.command === "init") {
699
+ const layer = await chooseLayer(parsed.layer);
700
+ if (layer === null) {
701
+ process.stderr.write(`${LAYER_REQUIRED()}\n`);
702
+ return 2;
703
+ }
704
+ const result = await runInit({ ...(layer ? { layer } : {}), ...(parsed.framework ? { framework: parsed.framework } : {}), cwd: parsed.directory ? path.resolve(parsed.directory) : process.cwd(), store: parsed.store,
705
+ force: parsed.force, skipInstall: parsed.skipInstall, template: parsed.template, agentHooks: parsed.agentHooks,
706
+ ...(parsed.template && parsed.directory ? { scratchTemplate: true } : {}),
707
+ ...(parsed.keyFromStdin ? { readKey: readKeyFromStdin } : {}), ...(parsed.autoTestKey ? { autoTestKey: true } : {}) });
708
+ return result.exitCode;
709
+ }
710
+ if (parsed.command === "test-checkout")
711
+ return await testCheckoutCommand(parsed, secrets);
712
+ if (parsed.command === "webhook")
713
+ return await webhookCommand(parsed, secrets);
714
+ if (parsed.command === "check")
715
+ return await checkCommand(parsed, secrets);
716
+ return await doctorCommand(parsed, secrets);
717
+ }
718
+ catch (error) {
719
+ if (error instanceof UsageError) {
720
+ process.stderr.write(redactSecrets(`${error.message}\n\n${usage()}`, secrets));
721
+ return 2;
722
+ }
723
+ process.stderr.write(redactSecrets(`Doctor could not run: ${error?.message ?? String(error)}\n`, secrets));
724
+ return 1;
725
+ }
726
+ }
727
+ process.exitCode = await main();