spatial-views 0.0.0-stage → 0.2.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +245 -2
  3. package/dist/app/assets/abnfDiagram-S7VZAUFO-CFbb_Sz2.js +1 -0
  4. package/dist/app/assets/architecture-WOLXFQ4H-CsBD__5a.js +1 -0
  5. package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
  6. package/dist/app/assets/blockDiagram-APKKGZFW-BZDPbzAG.js +140 -0
  7. package/dist/app/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  8. package/dist/app/assets/c4Diagram-KJ2TOQU5-BilBWuq5.js +38 -0
  9. package/dist/app/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  10. package/dist/app/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  11. package/dist/app/assets/chunk-6MUBBAK2-BBl-4tQr.js +2 -0
  12. package/dist/app/assets/chunk-AXFCVDMN-BhsttQ-k.js +62 -0
  13. package/dist/app/assets/chunk-BG4553SI-mWcPcFZr.js +127 -0
  14. package/dist/app/assets/chunk-DQASFODM-7FKe2gLt.js +10 -0
  15. package/dist/app/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  16. package/dist/app/assets/chunk-HFQBQIA3-nXrQ08BL.js +1 -0
  17. package/dist/app/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  18. package/dist/app/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  19. package/dist/app/assets/chunk-KQLB2F66-swukhFmZ.js +2 -0
  20. package/dist/app/assets/chunk-KS47KZWR-DkDkwO82.js +1 -0
  21. package/dist/app/assets/chunk-LEVMRMFU-DXH6iXv3.js +1 -0
  22. package/dist/app/assets/chunk-M57EVK23-B-kEyOJF.js +1 -0
  23. package/dist/app/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  24. package/dist/app/assets/chunk-OY52VR5R-DweG7qYw.js +88 -0
  25. package/dist/app/assets/chunk-QB3YPZ4I-DyozK3lV.js +213 -0
  26. package/dist/app/assets/chunk-R3KSYZAL-BEXCUN6J.js +1 -0
  27. package/dist/app/assets/chunk-STOXU5M4-BaTlty4O.js +72 -0
  28. package/dist/app/assets/chunk-TU62E6Q5-_rcUP1Fh.js +1 -0
  29. package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
  30. package/dist/app/assets/chunk-X4PVCEUW-DGxTL3kB.js +1 -0
  31. package/dist/app/assets/chunk-XXDRQBXY-C02Gpej2.js +1 -0
  32. package/dist/app/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  33. package/dist/app/assets/classDiagram-v2-L25IHNXF-DLEBwpvk.js +217 -0
  34. package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
  35. package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
  36. package/dist/app/assets/cynefinDiagram-L36ESFBY-CLFstukD.js +62 -0
  37. package/dist/app/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  38. package/dist/app/assets/d3-scale-CaJQQYkF.js +1 -0
  39. package/dist/app/assets/dagre-SPEB5RXH-BaSAny1T.js +4 -0
  40. package/dist/app/assets/diagram-3B7GL73J-DJNlt5Sg.js +200 -0
  41. package/dist/app/assets/diagram-DNEMPZML-DEHeuILB.js +24 -0
  42. package/dist/app/assets/diagram-L3MUGCDN-ob5Ka2Xc.js +41 -0
  43. package/dist/app/assets/diagram-LA4NIPWU-DNESzFAc.js +24 -0
  44. package/dist/app/assets/diagram-MHCOC4E2-CVi9zKjG.js +3 -0
  45. package/dist/app/assets/diagram-XPFHEONP-DInT4C7e.js +30 -0
  46. package/dist/app/assets/dist-CjvHN74u.js +1 -0
  47. package/dist/app/assets/ebnfDiagram-UZSYDL2S-CRCZNsji.js +1 -0
  48. package/dist/app/assets/elk-XV6XMXQE-D4fsWI2l.js +2 -0
  49. package/dist/app/assets/erDiagram-EYBAPDEH-YQNM5StV.js +99 -0
  50. package/dist/app/assets/eventmodeling-K75KTNOO-Bev08J2F.js +1 -0
  51. package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
  52. package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
  53. package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
  54. package/dist/app/assets/gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js +106 -0
  55. package/dist/app/assets/graphlib-DS17s2tU.js +1 -0
  56. package/dist/app/assets/index-Bn6_wHEp.js +98 -0
  57. package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
  58. package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
  59. package/dist/app/assets/infoDiagram-KBXO4MBG-DT7LbBRQ.js +2 -0
  60. package/dist/app/assets/ishikawaDiagram-M35NCXHK-CF51lhjB.js +70 -0
  61. package/dist/app/assets/journeyDiagram-OPLOXDXO-_36FonKk.js +139 -0
  62. package/dist/app/assets/kanban-definition-BZKZHSQY-tLk_OlQ-.js +89 -0
  63. package/dist/app/assets/katex-MEuSR36T.js +257 -0
  64. package/dist/app/assets/mermaid-parser.core-_3Vo8x6b.js +7 -0
  65. package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
  66. package/dist/app/assets/mindmap-definition-I2QAS2VK-BCI4HRX3.js +98 -0
  67. package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
  68. package/dist/app/assets/pegDiagram-FD4XPPHP-BOzSoNji.js +1 -0
  69. package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
  70. package/dist/app/assets/pieDiagram-J4AKIIQI-PlHpwT_c.js +39 -0
  71. package/dist/app/assets/quadrantDiagram-XTYBLID2-CdxZ0ael.js +7 -0
  72. package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
  73. package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
  74. package/dist/app/assets/railroad-abnf-LNEFI6M7-C49jJE4Y.js +1 -0
  75. package/dist/app/assets/railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js +1 -0
  76. package/dist/app/assets/railroad-peg-JR7BVNR7-DjBPSCKV.js +1 -0
  77. package/dist/app/assets/railroadDiagram-MRQ6NCDL-wGcmIMqq.js +1 -0
  78. package/dist/app/assets/requirementDiagram-Y7LWUY3S-DprFI03z.js +84 -0
  79. package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  80. package/dist/app/assets/rough.esm-Dy-Kn_BL.js +1 -0
  81. package/dist/app/assets/sankeyDiagram-WGJFYUXA-DygYWLTR.js +40 -0
  82. package/dist/app/assets/sequenceDiagram-5NDRBG5M-BzIr2DBO.js +169 -0
  83. package/dist/app/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  84. package/dist/app/assets/stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js +291 -0
  85. package/dist/app/assets/swimlanes-UMQ2AFYF-CIEH82Zt.js +1 -0
  86. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
  87. package/dist/app/assets/timeline-definition-SEUHKTQE-BGYSqup2.js +120 -0
  88. package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
  89. package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
  90. package/dist/app/assets/usecaseDiagram-AFA6YXN4-dy6oVOke.js +328 -0
  91. package/dist/app/assets/vennDiagram-NNMJR3RB-CUyuhcAk.js +34 -0
  92. package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
  93. package/dist/app/assets/wardleyDiagram-S7YFUSEH-DYtxYUHe.js +78 -0
  94. package/dist/app/assets/xychartDiagram-GGNKY7IX-ClR06AlB.js +7 -0
  95. package/dist/app/index.html +14 -0
  96. package/dist/cli/index.js +338 -0
  97. package/dist/core/api.js +420 -0
  98. package/dist/core/approvals.js +426 -0
  99. package/dist/core/context.js +259 -0
  100. package/dist/core/diff.js +156 -0
  101. package/dist/core/docs.js +140 -0
  102. package/dist/core/doctor.js +152 -0
  103. package/dist/core/doctypes.js +79 -0
  104. package/dist/core/edit.js +130 -0
  105. package/dist/core/errors.js +3 -0
  106. package/dist/core/flags.js +13 -0
  107. package/dist/core/gaps.js +119 -0
  108. package/dist/core/heading.js +4 -0
  109. package/dist/core/history.js +50 -0
  110. package/dist/core/home.js +345 -0
  111. package/dist/core/lanes.js +134 -0
  112. package/dist/core/launch.js +34 -0
  113. package/dist/core/layout.js +362 -0
  114. package/dist/core/links.js +68 -0
  115. package/dist/core/mermaid.js +175 -0
  116. package/dist/core/newdoc.js +66 -0
  117. package/dist/core/open-folder.js +30 -0
  118. package/dist/core/openspec.js +120 -0
  119. package/dist/core/paths.js +90 -0
  120. package/dist/core/project.js +392 -0
  121. package/dist/core/resolve.js +35 -0
  122. package/dist/core/route.js +420 -0
  123. package/dist/core/scan.js +514 -0
  124. package/dist/core/schema.js +270 -0
  125. package/dist/core/scope.js +126 -0
  126. package/dist/core/setup.js +134 -0
  127. package/dist/core/skills.js +181 -0
  128. package/dist/core/storage/config.js +74 -0
  129. package/dist/core/storage/events.js +54 -0
  130. package/dist/core/storage/folder-watch.js +147 -0
  131. package/dist/core/storage/folder.js +469 -0
  132. package/dist/core/storage/index.js +8 -0
  133. package/dist/core/storage/local.js +22 -0
  134. package/dist/core/storage/migrate.js +48 -0
  135. package/dist/core/storage/postgres.js +290 -0
  136. package/dist/core/storage/types.js +101 -0
  137. package/dist/core/storage.js +589 -0
  138. package/dist/core/suggest.js +283 -0
  139. package/dist/core/tree.js +254 -0
  140. package/dist/core/types.js +583 -0
  141. package/dist/core/version.js +1 -0
  142. package/dist/core/versions.js +245 -0
  143. package/dist/core/watch.js +2 -0
  144. package/dist/core/xml.js +68 -0
  145. package/dist/demo/args.js +58 -0
  146. package/dist/demo/browser.js +301 -0
  147. package/dist/demo/platform.js +147 -0
  148. package/dist/demo/run.js +198 -0
  149. package/dist/demo/steps.js +328 -0
  150. package/dist/mcp/project-tools.js +193 -0
  151. package/dist/mcp/server.js +785 -0
  152. package/examples/platform/README.md +33 -0
  153. package/examples/platform/api/package.json +8 -0
  154. package/examples/platform/api/src/auth-middleware.js +16 -0
  155. package/examples/platform/api/src/proxy.js +7 -0
  156. package/examples/platform/api/src/rate-limit.js +13 -0
  157. package/examples/platform/api/src/server.js +40 -0
  158. package/examples/platform/auth/package.json +9 -0
  159. package/examples/platform/auth/src/server.js +24 -0
  160. package/examples/platform/auth/src/tokens.js +19 -0
  161. package/examples/platform/auth/src/users.js +16 -0
  162. package/examples/platform/docs/api/PRD.md +10 -0
  163. package/examples/platform/docs/api/SDD.md +15 -0
  164. package/examples/platform/docs/auth/PRD.md +10 -0
  165. package/examples/platform/docs/auth/SDD.md +8 -0
  166. package/examples/platform/docs/frontend/PRD.md +18 -0
  167. package/examples/platform/docs/frontend/SDD.md +13 -0
  168. package/examples/platform/docs/pricing/PRD.md +9 -0
  169. package/examples/platform/docs/pricing/SDD.md +8 -0
  170. package/examples/platform/docs/products/PRD.md +9 -0
  171. package/examples/platform/docs/products/SDD.md +8 -0
  172. package/examples/platform/frontend/package.json +8 -0
  173. package/examples/platform/frontend/src/api-client.js +21 -0
  174. package/examples/platform/frontend/src/main.js +21 -0
  175. package/examples/platform/frontend/src/pages/products.js +12 -0
  176. package/examples/platform/frontend/src/pages/sign-in.js +14 -0
  177. package/examples/platform/frontend/src/session.js +11 -0
  178. package/examples/platform/pricing/package.json +9 -0
  179. package/examples/platform/pricing/src/cache.js +19 -0
  180. package/examples/platform/pricing/src/product-events.js +17 -0
  181. package/examples/platform/pricing/src/rules.js +19 -0
  182. package/examples/platform/pricing/src/server.js +32 -0
  183. package/examples/platform/products/package.json +9 -0
  184. package/examples/platform/products/src/catalog.js +20 -0
  185. package/examples/platform/products/src/events.js +11 -0
  186. package/examples/platform/products/src/search.js +9 -0
  187. package/examples/platform/products/src/server.js +31 -0
  188. package/migrations/postgres/001_init.sql +55 -0
  189. package/migrations/postgres/002_view_versions.sql +18 -0
  190. package/package.json +69 -4
  191. package/schema/approval.schema.json +173 -0
  192. package/schema/gap.schema.json +56 -0
  193. package/schema/pins.schema.json +122 -0
  194. package/schema/project.schema.json +93 -0
  195. package/schema/settings.schema.json +86 -0
  196. package/schema/toolbox.schema.json +206 -0
  197. package/schema/type.schema.json +121 -0
  198. package/schema/view.schema.json +240 -0
  199. package/skills/claude/build-gap/SKILL.md +28 -0
  200. package/skills/claude/check-ui/SKILL.md +40 -0
  201. package/skills/claude/draw-system/SKILL.md +38 -0
  202. package/skills/claude/gap-from-view/SKILL.md +29 -0
  203. package/skills/claude/post-audit/SKILL.md +58 -0
  204. package/skills/claude/pre-audit/SKILL.md +82 -0
  205. package/skills/claude/update-state/SKILL.md +56 -0
  206. package/skills/cursor/check-ui.mdc +40 -0
  207. package/skills/cursor/draw-system.mdc +38 -0
  208. package/skills/cursor/post-audit.mdc +44 -0
  209. package/skills/cursor/pre-audit.mdc +49 -0
  210. package/skills/cursor/update-state.mdc +45 -0
  211. package/skills/windsurf/spatial-views.md +212 -0
  212. package/toolboxes/aws.yaml +43 -0
  213. package/toolboxes/azure.yaml +41 -0
  214. package/toolboxes/cloud.yaml +95 -0
  215. package/toolboxes/docs.yaml +111 -0
  216. package/toolboxes/software.yaml +114 -0
  217. package/toolboxes/types/docs/gap.yaml +15 -0
  218. package/toolboxes/types/docs/mdd.yaml +19 -0
  219. package/toolboxes/types/docs/plain.yaml +7 -0
  220. package/toolboxes/types/docs/prd.yaml +17 -0
@@ -0,0 +1,33 @@
1
+ # Example: platform
2
+
3
+ A small, invented commerce platform for trying Spatial Views: five repos and a folder of docs.
4
+
5
+ | Folder | What it is |
6
+ |---|---|
7
+ | `frontend/` | The storefront (browser): browse, search, a product's price, sign in. |
8
+ | `api/` | The API gateway: one front door; checks tokens, limits rates, forwards. |
9
+ | `auth/` | Sign-in and short-lived tokens (Postgres users, JWKS). |
10
+ | `products/` | The catalogue (Postgres), search, and `products.changed` events. |
11
+ | `pricing/` | Prices and quotes, a Redis cache, and it follows `products.changed`. |
12
+ | `docs/<area>/` | A short PRD and an SDD for each of the five areas. |
13
+
14
+ ## Try it
15
+
16
+ ```bash
17
+ cp -r examples/platform /tmp/platform
18
+ for r in frontend api auth products pricing; do (cd /tmp/platform/$r && git init -q && git add . && git commit -qm "initial"); done
19
+ npx spatial-views setup # once
20
+ npx spatial-views # the canvas, in another terminal
21
+ ```
22
+
23
+ Then, in Cursor, Claude Code or Windsurf:
24
+
25
+ ```
26
+ pre-audit platform /tmp/platform/frontend /tmp/platform/api /tmp/platform/auth /tmp/platform/products /tmp/platform/pricing /tmp/platform/docs
27
+ ```
28
+
29
+ pre-audit draws the **System Overview** (Frontend, API, Auth, Products, Pricing), creates a **Sub View** for each (3 to 6 modules, with their files), and pins each area's PRD and SDD to its module. Nothing else. Double-click a module to drill down.
30
+
31
+ On Windows, copy to `c:\platform` and pass `c:\platform\frontend` and so on.
32
+
33
+ The decoy folders `examples/other-billing` and `examples/other-notes` sit next to it on disk and are never added. Nothing in them is ever read; the end-to-end test (`test/demo-platform.test.ts`) checks that.
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "platform-api",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "src/server.js",
7
+ "scripts": { "start": "node src/server.js" }
8
+ }
@@ -0,0 +1,16 @@
1
+ // Checks the bearer token against Auth's public keys (JWKS) before a request goes on.
2
+ const AUTH_URL = process.env.AUTH_URL ?? "http://auth:4001";
3
+ let keys = null;
4
+
5
+ async function jwks() {
6
+ keys ??= await fetch(`${AUTH_URL}/.well-known/jwks.json`).then((r) => r.json());
7
+ return keys;
8
+ }
9
+
10
+ export const requireToken = (handler) => async (req, params) => {
11
+ const token = (req.headers.authorization ?? "").replace(/^Bearer /, "");
12
+ if (!token) return [401, { error: "sign in first" }];
13
+ const { keys: list } = await jwks();
14
+ if (!list.some((k) => token.includes(k.kid))) return [401, { error: "bad token" }];
15
+ return handler(req, params);
16
+ };
@@ -0,0 +1,7 @@
1
+ // Forwards a request to a service and hands its answer back.
2
+ export async function forward(req, base, path) {
3
+ let body = "";
4
+ for await (const chunk of req) body += chunk;
5
+ const res = await fetch(`${base}${path}`, { method: req.method, headers: { "content-type": "application/json" }, body: body || undefined });
6
+ return [res.status, await res.json()];
7
+ }
@@ -0,0 +1,13 @@
1
+ // A token bucket per client address: 60 requests a minute.
2
+ const buckets = new Map();
3
+ export function allow(req) {
4
+ const key = req.socket.remoteAddress;
5
+ const now = Date.now();
6
+ const b = buckets.get(key) ?? { tokens: 60, at: now };
7
+ b.tokens = Math.min(60, b.tokens + ((now - b.at) / 60000) * 60);
8
+ b.at = now;
9
+ buckets.set(key, b);
10
+ if (b.tokens < 1) return false;
11
+ b.tokens -= 1;
12
+ return true;
13
+ }
@@ -0,0 +1,40 @@
1
+ // The API gateway: one front door for the frontend. It checks tokens, limits
2
+ // rates, and forwards each request to the service that owns it.
3
+ import { createServer } from "node:http";
4
+ import { requireToken } from "./auth-middleware.js";
5
+ import { forward } from "./proxy.js";
6
+ import { allow } from "./rate-limit.js";
7
+
8
+ const FRONTEND_URL = process.env.FRONTEND_URL ?? "http://frontend:8080";
9
+ const AUTH_URL = process.env.AUTH_URL ?? "http://auth:4001";
10
+ const PRODUCTS_URL = process.env.PRODUCTS_URL ?? "http://products:4002";
11
+ const PRICING_URL = process.env.PRICING_URL ?? "http://pricing:4003";
12
+
13
+ const routes = [];
14
+ const route = (method, pattern, handler) => {
15
+ const re = new RegExp(`^${pattern.replace(/:(\w+)/g, "(?<$1>[^/]+)")}$`);
16
+ routes.push({ method, re, handler });
17
+ };
18
+
19
+ route("GET", "/health", async () => [200, { ok: true }]);
20
+ route("POST", "/auth/login", (req) => forward(req, AUTH_URL, "/login"));
21
+ route("GET", "/products", (req) => forward(req, PRODUCTS_URL, "/products"));
22
+ route("GET", "/products/:id", (req, { id }) => forward(req, PRODUCTS_URL, `/products/${id}`));
23
+ route("GET", "/prices/:productId", (req, { productId }) => forward(req, PRICING_URL, `/prices/${productId}`));
24
+ route("POST", "/quotes", requireToken((req) => forward(req, PRICING_URL, "/quotes")));
25
+
26
+ createServer(async (req, res) => {
27
+ const path = new URL(req.url, "http://localhost").pathname;
28
+ let [status, body] = [404, { error: "not found" }];
29
+ if (!allow(req)) [status, body] = [429, { error: "slow down" }];
30
+ else
31
+ for (const r of routes) {
32
+ const m = r.method === req.method && r.re.exec(path);
33
+ if (m) {
34
+ [status, body] = await r.handler(req, m.groups ?? {});
35
+ break;
36
+ }
37
+ }
38
+ res.writeHead(status, { "content-type": "application/json", "access-control-allow-origin": FRONTEND_URL });
39
+ res.end(JSON.stringify(body));
40
+ }).listen(Number(process.env.PORT ?? 3000));
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "platform-auth",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "src/server.js",
7
+ "scripts": { "start": "node src/server.js" },
8
+ "dependencies": { "pg": "^8.13.0" }
9
+ }
@@ -0,0 +1,24 @@
1
+ // Auth: signs users in and issues short-lived access tokens.
2
+ import { createServer } from "node:http";
3
+ import { findUser, checkPassword } from "./users.js";
4
+ import { issue, publicKeys, refresh } from "./tokens.js";
5
+
6
+ const routes = [];
7
+ const route = (method, pattern, handler) => routes.push({ method, pattern, handler });
8
+
9
+ route("POST", "/login", async (body) => {
10
+ const user = await findUser(body.email);
11
+ if (!user || !(await checkPassword(user, body.password))) return [401, { error: "wrong email or password" }];
12
+ return [200, issue(user)];
13
+ });
14
+ route("POST", "/token/refresh", async (body) => [200, refresh(body.refresh_token)]);
15
+ route("GET", "/.well-known/jwks.json", async () => [200, publicKeys()]);
16
+
17
+ createServer(async (req, res) => {
18
+ let raw = "";
19
+ for await (const chunk of req) raw += chunk;
20
+ const r = routes.find((x) => x.method === req.method && x.pattern === new URL(req.url, "http://localhost").pathname);
21
+ const [status, body] = r ? await r.handler(raw ? JSON.parse(raw) : {}) : [404, { error: "not found" }];
22
+ res.writeHead(status, { "content-type": "application/json" });
23
+ res.end(JSON.stringify(body));
24
+ }).listen(Number(process.env.PORT ?? 4001));
@@ -0,0 +1,19 @@
1
+ // Access tokens (15 minutes) and refresh tokens (30 days), signed with the current key.
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ const KEY = { kid: "k1", alg: "RS256" };
5
+ const refreshTokens = new Map();
6
+
7
+ export function issue(user) {
8
+ const refresh_token = randomUUID();
9
+ refreshTokens.set(refresh_token, user.id);
10
+ return { access_token: `${KEY.kid}.${user.id}.${Date.now() + 15 * 60_000}`, refresh_token, expires_in: 900 };
11
+ }
12
+
13
+ export function refresh(token) {
14
+ const id = refreshTokens.get(token);
15
+ if (!id) return { error: "expired" };
16
+ return issue({ id });
17
+ }
18
+
19
+ export const publicKeys = () => ({ keys: [KEY] });
@@ -0,0 +1,16 @@
1
+ // Users live in Postgres; passwords are stored as scrypt hashes.
2
+ import { scrypt, timingSafeEqual } from "node:crypto";
3
+ import pg from "pg";
4
+
5
+ const db = new pg.Pool({ connectionString: process.env.DATABASE_URL ?? "postgres://auth@auth-db/auth" });
6
+
7
+ export async function findUser(email) {
8
+ const { rows } = await db.query("SELECT id, email, password_hash, salt FROM users WHERE email = $1", [email]);
9
+ return rows[0] ?? null;
10
+ }
11
+
12
+ export function checkPassword(user, password) {
13
+ return new Promise((ok) =>
14
+ scrypt(password, user.salt, 64, (err, key) => ok(!err && timingSafeEqual(key, Buffer.from(user.password_hash, "hex")))),
15
+ );
16
+ }
@@ -0,0 +1,10 @@
1
+ # API gateway: PRD
2
+
3
+ ## Problem
4
+ The frontend should see one API, not three services, and no service should be open to the internet.
5
+
6
+ ## Requirements
7
+ 1. One base URL for every call the frontend makes.
8
+ 2. Requests that change data need a valid access token.
9
+ 3. At most 60 requests a minute per client; more get `429`.
10
+ 4. Only the frontend's origin may call it from a browser.
@@ -0,0 +1,15 @@
1
+ # API gateway: SDD
2
+
3
+ Node, no framework. Each route forwards to the service that owns it.
4
+
5
+ | Route | Goes to |
6
+ |---|---|
7
+ | `POST /auth/login` | Auth `POST /login` |
8
+ | `GET /products`, `GET /products/:id` | Products |
9
+ | `GET /prices/:productId` | Pricing |
10
+ | `POST /quotes` (token needed) | Pricing |
11
+
12
+ - **Router** (`src/server.js`): the route table.
13
+ - **Auth middleware** (`src/auth-middleware.js`): checks the bearer token against Auth's JWKS.
14
+ - **Rate limiter** (`src/rate-limit.js`): a token bucket per client address.
15
+ - **Proxy** (`src/proxy.js`): forwards the request and returns the answer.
@@ -0,0 +1,10 @@
1
+ # Auth: PRD
2
+
3
+ ## Problem
4
+ Shoppers sign in once and the platform trusts them for a while, without each service checking passwords.
5
+
6
+ ## Requirements
7
+ 1. Sign in with email and password.
8
+ 2. Access tokens last 15 minutes; refresh tokens last 30 days.
9
+ 3. Services check tokens with Auth's public keys, without calling Auth each time.
10
+ 4. Passwords are never stored in plain text.
@@ -0,0 +1,8 @@
1
+ # Auth: SDD
2
+
3
+ | Part | File | Does |
4
+ |---|---|---|
5
+ | Login handler | `src/server.js` | `POST /login`, `POST /token/refresh` |
6
+ | Token service | `src/tokens.js` | issues and refreshes tokens, signed with the current key |
7
+ | JWKS endpoint | `src/server.js` | `GET /.well-known/jwks.json`: the public keys |
8
+ | Users store | `src/users.js` | Postgres `users` table; scrypt password hashes |
@@ -0,0 +1,18 @@
1
+ # Frontend: PRD
2
+
3
+ ## Problem
4
+ Shoppers need to find a product, see its price and sign in, in a browser, fast.
5
+
6
+ ## Goals
7
+ - Browse and search the catalogue.
8
+ - See a product's page with its current price.
9
+ - Sign in with email and password.
10
+
11
+ ## Requirements
12
+ 1. The product list loads in under 1 second on a 4G phone.
13
+ 2. Search matches product names and descriptions.
14
+ 3. A product page always shows the price Pricing gives today.
15
+ 4. A signed-in shopper stays signed in for the browser tab's lifetime.
16
+
17
+ ## Out of scope
18
+ Checkout and payments (a later release).
@@ -0,0 +1,13 @@
1
+ # Frontend: SDD
2
+
3
+ A single-page app. It only talks to the API gateway (`API_URL`).
4
+
5
+ | Part | File | Does |
6
+ |---|---|---|
7
+ | Shell and routing | `src/main.js` | maps the URL to a page |
8
+ | Product pages | `src/pages/products.js` | the list, search and one product with its price |
9
+ | Sign-in | `src/pages/sign-in.js` | the form; saves the access token |
10
+ | Session | `src/session.js` | the token, in `sessionStorage` |
11
+ | API client | `src/api-client.js` | every HTTP call, with the bearer token |
12
+
13
+ Calls: `GET /products`, `GET /products/:id`, `GET /prices/:id`, `POST /auth/login`.
@@ -0,0 +1,9 @@
1
+ # Pricing: PRD
2
+
3
+ ## Problem
4
+ A shopper must see the right price for a product, and a quote for a basket, every time.
5
+
6
+ ## Requirements
7
+ 1. The price of one product, in GBP.
8
+ 2. A quote for a basket, with discounts applied (10% off 10 or more; 5% off music).
9
+ 3. A price is never more than 5 minutes stale, and never stale after the product changes.
@@ -0,0 +1,8 @@
1
+ # Pricing: SDD
2
+
3
+ | Part | File | Does |
4
+ |---|---|---|
5
+ | Price API | `src/server.js` | `GET /prices/:productId`, `POST /quotes` |
6
+ | Rules engine | `src/rules.js` | list prices by category, then the first matching discount |
7
+ | Price cache | `src/cache.js` | Redis, 5 minutes |
8
+ | Product events | `src/product-events.js` | follows `products.changed`; drops that product's cached price |
@@ -0,0 +1,9 @@
1
+ # Products: PRD
2
+
3
+ ## Problem
4
+ Everyone needs the same, current catalogue: the shop shows it and Pricing prices it.
5
+
6
+ ## Requirements
7
+ 1. List products by name, and get one by id.
8
+ 2. Search names and descriptions.
9
+ 3. When a product changes, everyone that cares hears about it within seconds.
@@ -0,0 +1,8 @@
1
+ # Products: SDD
2
+
3
+ | Part | File | Does |
4
+ |---|---|---|
5
+ | Catalogue API | `src/server.js` | `GET /products`, `GET /products/:id` |
6
+ | Search | `src/search.js` | Postgres full-text search |
7
+ | Catalogue store | `src/catalog.js` | the `products` table |
8
+ | Change events | `src/events.js` | publishes each change on the `products.changed` exchange (fanout) |
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "platform-frontend",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "src/main.js",
7
+ "scripts": { "start": "node src/main.js" }
8
+ }
@@ -0,0 +1,21 @@
1
+ // Every call from the browser goes through the API gateway.
2
+ import { session } from "./session.js";
3
+
4
+ const API_URL = process.env.API_URL ?? "http://api:3000";
5
+
6
+ async function call(method, path, body) {
7
+ const res = await fetch(`${API_URL}${path}`, {
8
+ method,
9
+ headers: { "content-type": "application/json", ...(session.token ? { authorization: `Bearer ${session.token}` } : {}) },
10
+ body: body ? JSON.stringify(body) : undefined,
11
+ });
12
+ if (!res.ok) throw new Error(`${method} ${path}: ${res.status}`);
13
+ return res.json();
14
+ }
15
+
16
+ export const api = {
17
+ products: (q) => call("GET", `/products${q ? `?q=${encodeURIComponent(q)}` : ""}`),
18
+ product: (id) => call("GET", `/products/${id}`),
19
+ price: (id) => call("GET", `/prices/${id}`),
20
+ login: (email, password) => call("POST", "/auth/login", { email, password }),
21
+ };
@@ -0,0 +1,21 @@
1
+ // The storefront shell: routes the URL to a page and keeps the signed-in user.
2
+ import { renderProductList, renderProductPage } from "./pages/products.js";
3
+ import { renderSignIn } from "./pages/sign-in.js";
4
+ import { session } from "./session.js";
5
+
6
+ const routes = [
7
+ [/^\/$/, () => renderProductList()],
8
+ [/^\/products\/(\d+)$/, (id) => renderProductPage(Number(id))],
9
+ [/^\/sign-in$/, () => renderSignIn()],
10
+ ];
11
+
12
+ export function navigate(path) {
13
+ for (const [re, page] of routes) {
14
+ const m = re.exec(path);
15
+ if (m) return page(...m.slice(1));
16
+ }
17
+ return renderProductList();
18
+ }
19
+
20
+ session.restore();
21
+ navigate(location.pathname);
@@ -0,0 +1,12 @@
1
+ // The product list (with search) and one product's page, with its price.
2
+ import { api } from "../api-client.js";
3
+
4
+ export async function renderProductList(q) {
5
+ const products = await api.products(q);
6
+ document.body.innerHTML = products.map((p) => `<a href="/products/${p.id}">${p.name}</a>`).join("");
7
+ }
8
+
9
+ export async function renderProductPage(id) {
10
+ const [product, price] = await Promise.all([api.product(id), api.price(id)]);
11
+ document.body.innerHTML = `<h1>${product.name}</h1><p>${price.amount} ${price.currency}</p>`;
12
+ }
@@ -0,0 +1,14 @@
1
+ // Sign in with email and password; the API hands back an access token.
2
+ import { api } from "../api-client.js";
3
+ import { session } from "../session.js";
4
+
5
+ export function renderSignIn() {
6
+ document.body.innerHTML = `<form><input name="email"><input name="password" type="password"><button>Sign in</button></form>`;
7
+ document.querySelector("form").addEventListener("submit", async (e) => {
8
+ e.preventDefault();
9
+ const f = new FormData(e.target);
10
+ const { access_token } = await api.login(f.get("email"), f.get("password"));
11
+ session.save(access_token);
12
+ location.assign("/");
13
+ });
14
+ }
@@ -0,0 +1,11 @@
1
+ // The signed-in user's access token, kept for the tab's lifetime.
2
+ export const session = {
3
+ token: null,
4
+ restore() {
5
+ this.token = sessionStorage.getItem("token");
6
+ },
7
+ save(token) {
8
+ this.token = token;
9
+ sessionStorage.setItem("token", token);
10
+ },
11
+ };
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "platform-pricing",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "src/server.js",
7
+ "scripts": { "start": "node src/server.js" },
8
+ "dependencies": { "amqplib": "^0.10.4", "redis": "^4.7.0" }
9
+ }
@@ -0,0 +1,19 @@
1
+ // Prices are cached in Redis for 5 minutes, and dropped when a product changes.
2
+ import { createClient } from "redis";
3
+
4
+ const redis = createClient({ url: process.env.REDIS_URL ?? "redis://pricing-cache:6379" });
5
+ const ready = redis.connect();
6
+
7
+ export async function cached(key, make) {
8
+ await ready;
9
+ const hit = await redis.get(key);
10
+ if (hit) return JSON.parse(hit);
11
+ const value = await make();
12
+ await redis.set(key, JSON.stringify(value), { EX: 300 });
13
+ return value;
14
+ }
15
+
16
+ export async function forget(key) {
17
+ await ready;
18
+ await redis.del(key);
19
+ }
@@ -0,0 +1,17 @@
1
+ // Follows products.changed, so a stale price is never served.
2
+ import amqp from "amqplib";
3
+ import { forget } from "./cache.js";
4
+
5
+ const BROKER_URL = process.env.BROKER_URL ?? "amqp://broker";
6
+
7
+ export async function followProducts() {
8
+ const channel = await (await amqp.connect(BROKER_URL)).createChannel();
9
+ await channel.assertExchange("products.changed", "fanout");
10
+ const { queue } = await channel.assertQueue("pricing.products");
11
+ await channel.bindQueue(queue, "products.changed", "");
12
+ channel.consume(queue, async (msg) => {
13
+ const product = JSON.parse(msg.content.toString());
14
+ await forget(`price:${product.id}`);
15
+ channel.ack(msg);
16
+ });
17
+ }
@@ -0,0 +1,19 @@
1
+ // Price rules: a list price per category, then the first matching discount.
2
+ const LIST = { books: 12, games: 40, music: 9 };
3
+ const DISCOUNTS = [
4
+ { when: (item) => item.quantity >= 10, percent: 10 },
5
+ { when: (item) => item.category === "music", percent: 5 },
6
+ ];
7
+
8
+ export function priceFor(productId, category = "books") {
9
+ return { productId, amount: LIST[category] ?? 20, currency: "GBP" };
10
+ }
11
+
12
+ export function quote(items) {
13
+ const lines = items.map((item) => {
14
+ const { amount } = priceFor(item.productId, item.category);
15
+ const d = DISCOUNTS.find((x) => x.when(item));
16
+ return { ...item, amount: amount * item.quantity * (1 - (d?.percent ?? 0) / 100) };
17
+ });
18
+ return { lines, total: lines.reduce((n, l) => n + l.amount, 0), currency: "GBP" };
19
+ }
@@ -0,0 +1,32 @@
1
+ // Pricing: the price of a product for a customer, and quotes for a basket.
2
+ import { createServer } from "node:http";
3
+ import { cached } from "./cache.js";
4
+ import { followProducts } from "./product-events.js";
5
+ import { priceFor, quote } from "./rules.js";
6
+
7
+ const routes = [];
8
+ const route = (method, pattern, handler) => {
9
+ const re = new RegExp(`^${pattern.replace(/:(\w+)/g, "(?<$1>[^/]+)")}$`);
10
+ routes.push({ method, re, handler });
11
+ };
12
+
13
+ route("GET", "/prices/:productId", async ({ productId }) => [200, await cached(`price:${productId}`, () => priceFor(Number(productId)))]);
14
+ route("POST", "/quotes", async (_p, body) => [200, await quote(body.items ?? [])]);
15
+
16
+ createServer(async (req, res) => {
17
+ let raw = "";
18
+ for await (const chunk of req) raw += chunk;
19
+ const path = new URL(req.url, "http://localhost").pathname;
20
+ let [status, body] = [404, { error: "not found" }];
21
+ for (const r of routes) {
22
+ const m = r.method === req.method && r.re.exec(path);
23
+ if (m) {
24
+ [status, body] = await r.handler(m.groups ?? {}, raw ? JSON.parse(raw) : {});
25
+ break;
26
+ }
27
+ }
28
+ res.writeHead(status, { "content-type": "application/json" });
29
+ res.end(JSON.stringify(body));
30
+ }).listen(Number(process.env.PORT ?? 4003));
31
+
32
+ followProducts();
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "platform-products",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "src/server.js",
7
+ "scripts": { "start": "node src/server.js" },
8
+ "dependencies": { "pg": "^8.13.0", "amqplib": "^0.10.4" }
9
+ }
@@ -0,0 +1,20 @@
1
+ // The catalogue in Postgres. Every change is announced on products.changed.
2
+ import pg from "pg";
3
+ import { productChanged } from "./events.js";
4
+
5
+ const db = new pg.Pool({ connectionString: process.env.DATABASE_URL ?? "postgres://products@products-db/products" });
6
+
7
+ export async function listProducts() {
8
+ const { rows } = await db.query("SELECT id, name, category FROM products ORDER BY name");
9
+ return rows;
10
+ }
11
+
12
+ export async function getProduct(id) {
13
+ const { rows } = await db.query("SELECT id, name, category, description FROM products WHERE id = $1", [id]);
14
+ return rows[0] ?? null;
15
+ }
16
+
17
+ export async function updateProduct(id, patch) {
18
+ await db.query("UPDATE products SET name = $2, category = $3 WHERE id = $1", [id, patch.name, patch.category]);
19
+ await productChanged({ id, ...patch });
20
+ }
@@ -0,0 +1,11 @@
1
+ // Publishes product changes for Pricing (and anyone else) to follow.
2
+ import amqp from "amqplib";
3
+
4
+ const BROKER_URL = process.env.BROKER_URL ?? "amqp://broker";
5
+ let channel = null;
6
+
7
+ export async function productChanged(product) {
8
+ channel ??= await (await amqp.connect(BROKER_URL)).createChannel();
9
+ await channel.assertExchange("products.changed", "fanout");
10
+ channel.publish("products.changed", "", Buffer.from(JSON.stringify(product)));
11
+ }
@@ -0,0 +1,9 @@
1
+ // Full-text search over names and descriptions.
2
+ import pg from "pg";
3
+
4
+ const db = new pg.Pool({ connectionString: process.env.DATABASE_URL ?? "postgres://products@products-db/products" });
5
+
6
+ export async function search(q) {
7
+ const { rows } = await db.query("SELECT id, name, category FROM products WHERE to_tsvector(name || ' ' || description) @@ plainto_tsquery($1)", [q]);
8
+ return rows;
9
+ }
@@ -0,0 +1,31 @@
1
+ // Products: the catalogue. Lists, searches and serves products, and tells
2
+ // others when one changes.
3
+ import { createServer } from "node:http";
4
+ import { getProduct, listProducts } from "./catalog.js";
5
+ import { search } from "./search.js";
6
+
7
+ const routes = [];
8
+ const route = (method, pattern, handler) => {
9
+ const re = new RegExp(`^${pattern.replace(/:(\w+)/g, "(?<$1>[^/]+)")}$`);
10
+ routes.push({ method, re, handler });
11
+ };
12
+
13
+ route("GET", "/products", async (_p, url) => [200, url.searchParams.get("q") ? await search(url.searchParams.get("q")) : await listProducts()]);
14
+ route("GET", "/products/:id", async ({ id }) => {
15
+ const p = await getProduct(Number(id));
16
+ return p ? [200, p] : [404, { error: "no such product" }];
17
+ });
18
+
19
+ createServer(async (req, res) => {
20
+ const url = new URL(req.url, "http://localhost");
21
+ let [status, body] = [404, { error: "not found" }];
22
+ for (const r of routes) {
23
+ const m = r.method === req.method && r.re.exec(url.pathname);
24
+ if (m) {
25
+ [status, body] = await r.handler(m.groups ?? {}, url);
26
+ break;
27
+ }
28
+ }
29
+ res.writeHead(status, { "content-type": "application/json" });
30
+ res.end(JSON.stringify(body));
31
+ }).listen(Number(process.env.PORT ?? 4002));