@40rty/ams-cli 0.5.9 → 0.5.11

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.
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { cwd, fail, option, readConfig, storeBinding } from '../lib/context.mjs';
4
4
  import { call, request } from '../lib/credentials.mjs';
5
+ import { resolveStorePage } from '../lib/store-page.mjs';
5
6
  import { displayName, titleCase } from './init.mjs';
6
7
 
7
8
  /** The Storefront API version the store is asked through. */
@@ -73,8 +74,13 @@ export const ZERO_RESULTS_HINT = 'unpublished/dev stores are not in Shopify\'s g
73
74
  /** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
74
75
  export async function connect() {
75
76
  const config = await readConfig();
76
- // `--domain` / `--token` / `--shop-id` win over `.env`.
77
- const env = await storeBinding();
77
+ // `--from <storefront url>` reads the store's domain and its public Storefront
78
+ // token off the page every visitor's browser already gets (./store-page.mjs).
79
+ const from = option('from');
80
+ const page = from === undefined ? undefined : await resolveStorePage(from);
81
+ if (page !== undefined && 'error' in page) fail(`--from: ${page.error}`);
82
+ // `--domain` / `--token` / `--shop-id` win over `--from`, which wins over `.env`.
83
+ const env = page === undefined ? await storeBinding() : { ...(await storeBinding()), domain: page.domain, token: page.token };
78
84
  const pick = (flagName, fromEnv) => (option(flagName) !== undefined ? option(flagName) : fromEnv);
79
85
  const binding = { domain: pick('domain', env.domain), token: pick('token', env.token), shopId: pick('shop-id', env.shopId) };
80
86
  // An empty `.env` value is absence: `PUBLIC_STOREFRONT_API_TOKEN=` once
@@ -82,7 +88,7 @@ export async function connect() {
82
88
  const present = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
83
89
  const domain = present(binding.domain);
84
90
  const token = present(binding.token);
85
- if (domain === undefined || token === undefined) fail('no store: set PUBLIC_STORE_DOMAIN and PUBLIC_STOREFRONT_API_TOKEN (or SHOPIFY_STORE_DOMAIN and SHOPIFY_STOREFRONT_ACCESS_TOKEN) in .env, or pass --domain and --token');
91
+ if (domain === undefined || token === undefined) fail('no store: pass --from <the store\'s live URL> (reads its public Storefront token), or set PUBLIC_STORE_DOMAIN and PUBLIC_STOREFRONT_API_TOKEN (or SHOPIFY_STORE_DOMAIN and SHOPIFY_STOREFRONT_ACCESS_TOKEN) in .env, or pass --domain and --token');
86
92
  const host = domain.replace(/^https?:\/\//, '').replace(/\/+$/, '');
87
93
  // Catalog search runs ONLY through Shopify's Global catalog, scoped by the
88
94
  // store's id — and mock.shop is not in it, so a spacefront on it could never
@@ -1,7 +1,9 @@
1
1
  // `forty create <dir>` — start a spacefront package from nothing.
2
2
  //
3
- // Copies the starter (templates/package) into a new directory: a catalog with
4
- // the types a store needs, a component for each, a shell and a Tailwind build.
3
+ // Copies the starter (templates/package) into a new directory: a conversational
4
+ // UI spacefront — a catalog with the types a store needs plus the conversation
5
+ // blocks, a component for each, the conversation-page shell, the composition
6
+ // prompt and a Tailwind build.
5
7
  // It writes no forty.config.json: the first `forty dev` signs in, asks which
6
8
  // space this is for and writes it (`forty init`).
7
9
  import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
@@ -44,7 +46,7 @@ export async function create() {
44
46
  const { version } = JSON.parse(await readFile(CLI_MANIFEST, 'utf8'));
45
47
 
46
48
  await copy(TEMPLATE, target, (text) =>
47
- text.replaceAll('__PACKAGE__', `@${slug}/spacefront`).replaceAll('__LABEL__', label).replaceAll('__VERSION__', `^${version}`),
49
+ text.replaceAll('__PACKAGE__', `@${slug}/spacefront`).replaceAll('__SLUG__', slug).replaceAll('__LABEL__', label).replaceAll('__VERSION__', `^${version}`),
48
50
  );
49
51
 
50
52
  console.log(`created ${dir} — @${slug}/spacefront\n`);
@@ -1,4 +1,6 @@
1
- // `forty doctor [dev-server-url] [--ask "<question>" | --no-ask]` — the integration's definition of done.
1
+ // `forty doctor [dev-server-url | preview-link] [--ask "<question>" | --no-ask]` — the integration's definition of done.
2
+ // A preview link (`…/?preview=<token>`, what `forty dev` prints) lends its
3
+ // token to the test turn, so a locked space answers it.
2
4
  // When 40rty hosts the app (`forty deploy`), the space's own address is
3
5
  // checked too: its own site, `https://<space>.40rty.app<route>`.
4
6
  //
@@ -182,7 +184,7 @@ export async function doctor() {
182
184
  for (const [what, fix] of problems) check(false, what, fix);
183
185
  }
184
186
  if (devOrigin !== undefined) {
185
- await routeChecks(check, config, `${devOrigin}/`);
187
+ await routeChecks(check, config, `${new URL(devOrigin).origin}/`);
186
188
  } else {
187
189
  console.log('- skipped the page and CSP checks: start the dev server with FORTY_AGENTIC=1 and pass its url, e.g. `forty doctor http://localhost:3000`');
188
190
  }
@@ -195,7 +197,7 @@ export async function doctor() {
195
197
  }
196
198
  }
197
199
 
198
- if (!flag('no-ask')) await askCheck(config, check);
200
+ if (!flag('no-ask')) await askCheck(config, check, devOrigin === undefined ? null : new URL(devOrigin).searchParams.get('preview'));
199
201
 
200
202
  if (failures.length > 0) {
201
203
  console.error(`\n${failures.length} check(s) failed.`);
@@ -212,13 +214,15 @@ const DEFAULT_QUESTION = 'what do you sell?';
212
214
  * spacefront uses. Passes when the agent composed a catalog element carrying
213
215
  * at least one entity. Skipped with `--no-ask`.
214
216
  */
215
- async function askCheck(config, check) {
217
+ async function askCheck(config, check, linkToken) {
216
218
  const asked = option('ask');
217
219
  const question = asked === undefined ? DEFAULT_QUESTION : asked;
218
220
  const env = await readDotenv(path.join(cwd, '.env'));
219
- // The preview credential `forty dev` wrote opens a locked space, and its draft.
220
- const token = typeof env.FORTY_DEV_TOKEN === 'string' && env.FORTY_DEV_TOKEN !== '' ? env.FORTY_DEV_TOKEN : undefined;
221
- console.log(`\n- asking "${question}"${token === undefined ? '' : ' (with FORTY_DEV_TOKEN)'}…`);
221
+ // The preview credential opens a locked space, and its draft: the link's, else the one `forty dev` wrote.
222
+ const fromEnv = typeof env.FORTY_DEV_TOKEN === 'string' && env.FORTY_DEV_TOKEN !== '' ? env.FORTY_DEV_TOKEN : undefined;
223
+ const token = linkToken !== null && linkToken !== '' ? linkToken : fromEnv;
224
+ const source = token === undefined ? '' : token === fromEnv ? ' (with FORTY_DEV_TOKEN)' : ' (with the preview link\'s token)';
225
+ console.log(`\n- asking "${question}"${source}…`);
222
226
  // The organization key fetches the socket ticket a deployment asks a script for.
223
227
  const credential = await findCredential(config.apiUrl);
224
228
  const turn = await askSpace({ apiUrl: config.apiUrl, slug: config.spaceSlug, token, apiKey: credential === null ? undefined : credential.key, question });
@@ -1,17 +1,23 @@
1
1
  import { fail, positionals, readConfig } from '../lib/context.mjs';
2
2
  import { call } from '../lib/credentials.mjs';
3
3
 
4
- /** The DNS records a domain still needs, one line each — or why there are none to show. */
4
+ /** Where the domain stands, one line, then the DNS records to create while it is not live. */
5
5
  function describe(status) {
6
6
  const { hostname } = status.domain;
7
- const lines = [];
8
- if (status.vercel.state !== 'ok') return [` ${hostname}: status unavailable (${status.vercel.state})`];
9
- const vercel = status.vercel.status;
10
- if (vercel.verified && !vercel.misconfigured) return [` ${hostname}: live`];
11
- lines.push(` ${hostname}: waiting for DNS — create:`);
12
- for (const r of vercel.records) lines.push(` ${r.type.padEnd(5)} ${r.name.padEnd(24)} ${r.value}`);
13
- if (vercel.aliasTarget !== null) lines.push(` (or, at the apex, ALIAS/ANAME → ${vercel.aliasTarget})`);
14
- for (const c of vercel.challenges) lines.push(` ${c.type.padEnd(5)} ${c.domain.padEnd(24)} ${c.value}`);
7
+ const { edge, routing } = status;
8
+ if (edge.state !== 'ok') return [` ${hostname}: status unavailable (${edge.state === 'error' ? edge.message : edge.reason})`];
9
+ const cert = edge.status.certificate;
10
+ if (cert === 'active' && routing.state === 'pointed') return [` ${hostname}: live`];
11
+ const where =
12
+ !edge.status.attached ? 'provisioning the certificate — run `forty domain` again in a minute'
13
+ : cert === 'failed' ? `certificate failed${edge.status.certificateDetail === null ? '' : ` (${edge.status.certificateDetail})`}`
14
+ : cert !== 'active' ? 'issuing the certificate — waiting on the _acme-challenge record'
15
+ : routing.state === 'elsewhere' ? `certificate ready — DNS still points at ${routing.found.join(', ')}; switch the routing record to cut over`
16
+ : 'certificate ready — waiting for DNS';
17
+ const lines = [` ${hostname}: ${where}. Create:`];
18
+ for (const r of status.records) lines.push(` ${r.type.padEnd(5)} ${r.name.padEnd(40)} ${r.value}`);
19
+ const alt = status.routingAlternative;
20
+ if (alt !== null) lines.push(` (or, instead of the CNAME: ${alt.type} ${alt.name} → ${alt.value})`);
15
21
  return lines;
16
22
  }
17
23
 
@@ -19,7 +25,8 @@ function describe(status) {
19
25
  * `forty domain add <host>` — serve this repo's space on the customer's own
20
26
  * domain (its hosted app or package, as on `<console>/<space>`), and print the
21
27
  * DNS records to create. `forty domain` lists the space's domains and what each
22
- * still needs. Serving starts once DNS resolves to us; certificates are automatic.
28
+ * still needs. Publish the `_acme-challenge` record first: the certificate issues while the
29
+ * domain still serves from its old host, then the routing record moves with no gap.
23
30
  */
24
31
  export async function domain() {
25
32
  const [action, host] = positionals();
@@ -34,9 +41,9 @@ export async function domain() {
34
41
  if (action !== 'add' || host === undefined) fail('usage: forty domain add <shop.example.com> | forty domain');
35
42
  const result = await call(config.apiUrl, 'POST', route, { hostname: host });
36
43
  console.log(`${result.domain.hostname} now serves "${config.spaceSlug}"`);
37
- if (result.attach.state !== 'attached') {
44
+ if (result.attach.state === 'error' || result.attach.state === 'unconfigured') {
38
45
  const why = result.attach.state === 'error' ? result.attach.message : result.attach.reason;
39
- console.log(` not attached yet (${result.attach.state}: ${why}) — tell the 40rty team`);
46
+ console.log(` certificate not provisioned (${result.attach.state}: ${why}) — tell the 40rty team`);
40
47
  }
41
48
  for (const line of describe(result)) console.log(line);
42
49
  }
@@ -13,12 +13,14 @@
13
13
  // An organization with no space yet gets one, named after the app. A question
14
14
  // that would need a terminal when there is none fails naming the flag that
15
15
  // answers it, rather than waiting on input that will never come.
16
+ import { existsSync } from 'node:fs';
16
17
  import { readFile, writeFile } from 'node:fs/promises';
17
18
  import path from 'node:path';
18
19
  import { createInterface } from 'node:readline';
19
20
  import { appKind, CONFIG_FILE, cwd, deployment, fail, option, readConfigIfPresent } from '../lib/context.mjs';
20
21
  import { call, findCredential } from '../lib/credentials.mjs';
21
22
  import { login } from './login.mjs';
23
+ import { STAFF_NOTICE } from './whoami.mjs';
22
24
 
23
25
  /** Sources the platform owns; a space still on one has not been given the organization's own yet. */
24
26
  const RESERVED = /^@(fourty|forty)\//;
@@ -111,6 +113,16 @@ async function pickSpace(spaces, appName) {
111
113
  return space;
112
114
  }
113
115
 
116
+ /** The conversation blocks' descriptions ship in the kit; a starter with a brand file and prompts sends those too. */
117
+ function packageExtras() {
118
+ const has = (file) => existsSync(path.join(cwd, file));
119
+ return {
120
+ manifests: has('node_modules/@40rty/ams-ui/dist/conversation/manifests') || has('src/brand.ts') ? ['src/catalogs', 'node_modules/@40rty/ams-ui/dist/conversation/manifests'] : 'src/catalogs',
121
+ ...(has('src/brand.ts') ? { brand: 'src/brand.ts' } : {}),
122
+ ...(has('prompts') ? { prompts: 'prompts' } : {}),
123
+ };
124
+ }
125
+
114
126
  export async function init() {
115
127
  try {
116
128
  await run();
@@ -142,10 +154,11 @@ async function run() {
142
154
 
143
155
  const config = selfHosted
144
156
  ? { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'app/forty/catalog.ts', manifests: 'app/forty/catalogs' }
145
- : { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'src/catalog.ts', manifests: 'src/catalogs', bundle: { entry: 'src/index.ts', css: 'dist/package.css' } };
157
+ : { apiUrl, spaceSlug: space.slug, sourceId, label: space.name, catalog: 'src/catalog.ts', ...packageExtras(), bundle: { entry: 'src/index.ts', css: 'dist/package.css' } };
146
158
  await writeFile(path.join(cwd, CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`);
147
159
 
148
160
  const kind = selfHosted ? `this app hosts the spacefront${framework === undefined ? '' : ` (${framework})`}` : 'the platform hosts the spacefront from this package';
149
161
  console.log(`wrote ${CONFIG_FILE} for space "${space.slug}" — ${kind}; \`--self-hosted\` / \`--package\` override`);
150
162
  console.log(selfHosted ? 'next: forty connect, then forty dev' : 'next: forty dev');
163
+ if (me.staff) console.log(`\n${STAFF_NOTICE}`);
151
164
  }
@@ -0,0 +1,17 @@
1
+ // `forty whoami` — which organization this machine acts for, and whether it is
2
+ // one of 40rty's own. A coding agent runs it first: a 40rty organization's
3
+ // spaces are our demos, built in the brands repo, not in a folder of their own.
4
+ import { deployment } from '../lib/context.mjs';
5
+ import { call } from '../lib/credentials.mjs';
6
+
7
+ /** What a 40rty organization does differently — shared with `forty init`. */
8
+ export const STAFF_NOTICE = '40rty organization: its spaces are 40rty demos. Build the package in the 40RTY-ai/brands repo (packages/<space>, on the shape of packages/ryleeandcru-conversational, which passes the brands lint), open a PR there, and release it by merging (the brands CI publishes) — never from this machine.';
9
+
10
+ export async function whoami() {
11
+ const { apiUrl } = deployment(null);
12
+ const me = await call(apiUrl, 'GET', '/org/me');
13
+ console.log(`organization: ${me.organizationId} (key "${me.keyName}")`);
14
+ console.log(`staff: ${me.staff === undefined ? 'unknown (this API predates the flag)' : me.staff ? 'yes' : 'no'}`);
15
+ console.log(`spaces: ${me.spaces.length === 0 ? 'none' : me.spaces.map((space) => space.slug).join(', ')}`);
16
+ if (me.staff) console.log(`\n${STAFF_NOTICE}`);
17
+ }
package/bin/forty.mjs CHANGED
@@ -3,6 +3,8 @@
3
3
  //
4
4
  // forty create start a new spacefront package from the starter
5
5
  // forty login sign in through the browser (once per machine)
6
+ // forty whoami the organization this machine acts for, and whether it is
7
+ // 40rty's own (its spaces are demos, built in the brands repo)
6
8
  // forty init write forty.config.json for one of the organization's spaces,
7
9
  // creating one when asked (--create <slug>) or when there is none
8
10
  // forty dev work on the project: every save becomes your draft on the
@@ -14,7 +16,8 @@
14
16
  // `--message "…"` (required, one line) says what the release changed
15
17
  // forty releases the package's release history, and which one is live
16
18
  // forty rollback make an earlier release live again (`forty rollback 3`)
17
- // forty connect attach this app's store to the space
19
+ // forty connect attach this app's store to the space (`--from <store url>`
20
+ // reads its public Storefront token off the live page)
18
21
  // forty origin add let a deployed site's origin call the api (CORS)
19
22
  // forty domain add serve the space on your own domain; prints the DNS records
20
23
  // forty feedback report a problem to the 40rty team
@@ -33,6 +36,7 @@ import { recordFailure } from './lib/last-failure.mjs';
33
36
  const commands = {
34
37
  create: () => import('./commands/create.mjs').then((m) => m.create()),
35
38
  login: () => import('./commands/login.mjs').then((m) => m.login()),
39
+ whoami: () => import('./commands/whoami.mjs').then((m) => m.whoami()),
36
40
  init: () => import('./commands/init.mjs').then((m) => m.init()),
37
41
  publish: () => import('./commands/publish.mjs').then((m) => m.publish()),
38
42
  releases: () => import('./commands/releases.mjs').then((m) => m.releases()),
@@ -0,0 +1,26 @@
1
+ // Where a storefront ships its public Storefront token — what `forty connect --from` reads.
2
+ import { describe, expect, it } from 'vitest';
3
+ import { findShopDomains, findTokenCandidates } from '../store-page.mjs';
4
+
5
+ describe('findTokenCandidates', () => {
6
+ it('reads the token Hydrogen serializes into its consent config (acme.example shape)', () => {
7
+ const html = String.raw`\"checkoutDomain\",\"checkout.acme.example\",\"storefrontAccessToken\",\"2efed5e20dc72ac998fdbbc55ae0649e\",\"withPrivacyBanner\"`;
8
+ expect(findTokenCandidates(html)).toEqual(['2efed5e20dc72ac998fdbbc55ae0649e']);
9
+ });
10
+
11
+ it('reads it from JSON and from an Online Store theme meta tag', () => {
12
+ expect(findTokenCandidates('{"storefrontAccessToken":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}')).toEqual(['a'.repeat(32)]);
13
+ expect(findTokenCandidates('<meta name="shopify-checkout-api-token" content="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">')).toEqual(['b'.repeat(32)]);
14
+ expect(findTokenCandidates('<script id="shopify-features" type="application/json">{"accessToken":"cccccccccccccccccccccccccccccccc","betas":[]}</script>')).toEqual(['c'.repeat(32)]);
15
+ });
16
+
17
+ it('finds nothing on a page that ships no token', () => {
18
+ expect(findTokenCandidates('<html>469e4518231869be4ba940a1dcefec4b</html>')).toEqual([]);
19
+ });
20
+ });
21
+
22
+ describe('findShopDomains', () => {
23
+ it('ranks the store domain the page mentions most', () => {
24
+ expect(findShopDomains('x.myshopify.com acmebody.myshopify.com acmebody.myshopify.com')).toEqual(['acmebody.myshopify.com', 'x.myshopify.com']);
25
+ });
26
+ });
@@ -7,7 +7,7 @@ export const cwd = process.cwd();
7
7
  export const CONFIG_FILE = 'forty.config.json';
8
8
 
9
9
  /** The production deployment, used when neither the config nor the environment names another. */
10
- const PRODUCTION = { apiUrl: 'https://40rty-ams-production.up.railway.app', consoleUrl: 'https://app.40rty.ai' };
10
+ const PRODUCTION = { apiUrl: 'https://api.40rty.ai', consoleUrl: 'https://app.40rty.ai' };
11
11
 
12
12
  /** A problem the person can act on — printed without a stack. */
13
13
  export class FortyError extends Error {}
@@ -0,0 +1,14 @@
1
+ /** Types for `store-page.mjs`, for the TypeScript tooling that reads a storefront the way `forty connect --from` does (scripts/create-space/resolve.ts). */
2
+ export const STOREFRONT_API_VERSION: string;
3
+
4
+ /** Every myshopify domain the page names, most-mentioned first. */
5
+ export function findShopDomains(html: string): string[];
6
+
7
+ /** Public Storefront token candidates the page ships, most trusted first. */
8
+ export function findTokenCandidates(html: string): string[];
9
+
10
+ /** Does the Storefront API at `domain` accept `token`? */
11
+ export function acceptsToken(domain: string, token: string): Promise<boolean>;
12
+
13
+ /** The store behind a storefront URL (or its page saved from a browser), or why there is none. */
14
+ export function resolveStorePage(source: string): Promise<{ domain: string; token: string } | { error: string }>;
@@ -0,0 +1,82 @@
1
+ // Which Shopify store is behind a storefront URL, and a Storefront token that
2
+ // answers for it — read from the page every visitor's browser already gets.
3
+ //
4
+ // A storefront's Storefront token is PUBLIC by design: it ships to every
5
+ // browser so the page can query products. Where it ships depends on the stack:
6
+ // - Hydrogen renders it into its consent config (`storefrontAccessToken`
7
+ // beside `checkoutDomain`);
8
+ // - Online Store themes publish it as `<meta name="shopify-checkout-api-token">`
9
+ // or as the `shopify-features` script's `accessToken`.
10
+ // A candidate only counts once the Storefront API accepts it for the store's
11
+ // own domain. `forty connect --from <url>` and create-space's resolve stage
12
+ // both read the page through this module.
13
+
14
+ import { readFile } from 'node:fs/promises';
15
+
16
+ export const STOREFRONT_API_VERSION = '2025-07';
17
+
18
+ /** Every myshopify domain the page names, most-mentioned first. */
19
+ export function findShopDomains(html) {
20
+ const counts = new Map();
21
+ for (const m of html.matchAll(/\b([a-z0-9][a-z0-9-]*)\.myshopify\.com\b/g)) {
22
+ const domain = `${m[1]}.myshopify.com`;
23
+ counts.set(domain, (counts.has(domain) ? counts.get(domain) : 0) + 1);
24
+ }
25
+ return [...counts].sort((a, b) => b[1] - a[1]).map(([d]) => d);
26
+ }
27
+
28
+ /** Token candidates in the order the places above are trusted. */
29
+ export function findTokenCandidates(html) {
30
+ const found = [];
31
+ const patterns = [
32
+ // Hydrogen, serialized either as JSON or as a flat turbo-stream array (\"key\",\"value\").
33
+ /storefrontAccessToken\\?"\s*[:,]\s*\\?"([a-f0-9]{32})/g,
34
+ /<meta[^>]+name="shopify-checkout-api-token"[^>]+content="([a-f0-9]{32})"/g,
35
+ /<meta[^>]+content="([a-f0-9]{32})"[^>]+name="shopify-checkout-api-token"/g,
36
+ /<script[^>]+id="shopify-features"[^>]*>\s*\{"accessToken":"([a-f0-9]{32})"/g,
37
+ ];
38
+ for (const pattern of patterns) for (const m of html.matchAll(pattern)) if (!found.includes(m[1])) found.push(m[1]);
39
+ return found;
40
+ }
41
+
42
+ /** Does the Storefront API at `domain` accept `token`? */
43
+ export async function acceptsToken(domain, token) {
44
+ const res = await fetch(`https://${domain}/api/${STOREFRONT_API_VERSION}/graphql.json`, {
45
+ method: 'POST',
46
+ headers: { 'content-type': 'application/json', 'x-shopify-storefront-access-token': token },
47
+ body: JSON.stringify({ query: '{ shop { id } }' }),
48
+ });
49
+ if (!res.ok) return false;
50
+ const body = await res.json().catch((err) => {
51
+ console.warn(`${domain} answered ${res.status} with no JSON (${err.message}) — treating the token as refused`);
52
+ return null;
53
+ });
54
+ return body !== null && body.data !== undefined && body.data !== null && body.data.shop !== null;
55
+ }
56
+
57
+ /** The page's HTML: fetched for a URL, read from disk for a page a real browser saved (a bot wall lets only browsers through). */
58
+ async function pageHtml(source) {
59
+ if (!/^https?:\/\//.test(source)) {
60
+ return readFile(source, 'utf8').then((html) => ({ html }), (err) => ({ error: `cannot read ${source} (${err.message}) — pass the store's URL, or a page saved from it` }));
61
+ }
62
+ const res = await fetch(source, { headers: { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130 Safari/537.36' } });
63
+ if (!res.ok) return { error: `${source} answered ${res.status} — a bot wall lets only a real browser through: open the store there, save the page (or copy its HTML into a file) and pass that file to --from` };
64
+ return { html: await res.text() };
65
+ }
66
+
67
+ /**
68
+ * `{ domain, token }` for the store behind `source` — a storefront URL, or its
69
+ * page saved from a browser — or `{ error }` saying why there is none.
70
+ */
71
+ export async function resolveStorePage(source) {
72
+ const page = await pageHtml(source);
73
+ if ('error' in page) return page;
74
+ const domains = findShopDomains(page.html);
75
+ if (domains.length === 0) return { error: `${source} names no *.myshopify.com domain — not a Shopify storefront page` };
76
+ const tokens = findTokenCandidates(page.html);
77
+ if (tokens.length === 0) return { error: `${source} ships no public Storefront token in its page` };
78
+ for (const domain of domains) {
79
+ for (const token of tokens) if (await acceptsToken(domain, token)) return { domain, token };
80
+ }
81
+ return { error: `none of the ${tokens.length} token(s) on ${source} is accepted by ${domains.join(', ')}` };
82
+ }
package/package.json CHANGED
@@ -16,7 +16,7 @@
16
16
  "peerDependencies": {
17
17
  "zod": "^3.25.0"
18
18
  },
19
- "version": "0.5.9",
19
+ "version": "0.5.11",
20
20
  "homepage": "https://docs.40rty.ai",
21
21
  "license": "UNLICENSED",
22
22
  "engines": {
@@ -1,10 +1,14 @@
1
1
  # __LABEL__ — spacefront
2
2
 
3
- Your components, rendered by 40rty: the agent composes `src/catalog.ts`'s types onto
4
- the canvas in `src/shell.tsx`, drawn by `src/blocks.tsx`.
3
+ A conversational UI spacefront: every question opens its own page. The agent composes
4
+ `src/catalog.ts`'s types (your blocks in `src/blocks.tsx`, plus the conversation blocks
5
+ from `@40rty/ams-ui/conversation`) onto the page in `src/shell.tsx`; `prompts/composition.md`
6
+ tells it which blocks answer which question.
5
7
 
6
8
  ```bash
7
9
  npm install
10
+ npx forty init # sign in, pick (or --create) your space
11
+ npx forty connect --from https://your-store.com # reads the store's public Storefront token
8
12
  npm run dev # sign in, pick your space, then every save updates your preview
9
13
  npm run release # publish a new release — visitors see it
10
14
  ```
@@ -0,0 +1,7 @@
1
+ Answer with a page, not one block: 4-6 blocks that each add something; every turn is its own page, and every answer ends with `paths`.
2
+ - "Which one?" → `verdict` + `shortlist` of the runners-up, a `note` from __LABEL__'s experts, `facts` of the pick, then `paths`. If one answer would change the pick (budget, who it's for, how they'll use it), open with `guidedPick`.
3
+ - "X or Y?" → `tradeoff` with a product for each side, an `explain` of what decides it, then `paths`.
4
+ - A buying guide / "how do I choose" → an `explain` per thing that decides it, each carrying products that show it, a `productGrid` across the range, a `guidedPick`, then `paths`.
5
+ - Browsing a category → `productGrid`, a `note` on how to choose, a `guidedPick` to narrow it, then `paths`.
6
+ - A `productGrid` is for browsing, never for a recommendation.
7
+ - Open your reply with one `# ` line: the page headline; the rest is its supporting text.
@@ -1,8 +1,7 @@
1
- import {renderInline, useCommerceActions, useProductCard} from '@40rty/ams-sdk';
1
+ import {useCommerceActions, useProductCard} from '@40rty/ams-sdk';
2
2
  import type {Collection, Product} from '@40rty/ams-sdk';
3
- import type {ReactNode} from 'react';
4
3
 
5
- const GUTTER = 'px-6 md:px-10';
4
+ // The shell's canvas owns the side gutter (`ShellScaffold` `gutter`), so a block never pads itself sideways.
6
5
 
7
6
  /** Hydrated entities arrive as objects; anything still a reference is skipped. */
8
7
  function loaded<T>(items: Array<T | string> | undefined): T[] {
@@ -10,7 +9,8 @@ function loaded<T>(items: Array<T | string> | undefined): T[] {
10
9
  return items.filter((item): item is T => typeof item === 'object' && item !== null);
11
10
  }
12
11
 
13
- function ProductCard({product}: {product: Product}) {
12
+ /** The store's product card — the grid draws it, and so does every conversation block (`./shell.tsx`). */
13
+ export function ProductCard({product}: {product: Product}) {
14
14
  const card = useProductCard(product);
15
15
  const image = card.displayImage;
16
16
  return (
@@ -32,7 +32,7 @@ function ProductCard({product}: {product: Product}) {
32
32
  /** A titled grid of products. */
33
33
  export function ProductGrid({title, products}: {title?: string; products?: Array<Product | string>}) {
34
34
  return (
35
- <section className={`grid gap-6 py-8 ${GUTTER}`}>
35
+ <section className={"grid gap-6 py-8"}>
36
36
  {title && <h2 className="text-2xl font-semibold">{title}</h2>}
37
37
  <div className="grid grid-cols-2 gap-6 md:grid-cols-4">
38
38
  {loaded(products).map((product) => (
@@ -47,7 +47,7 @@ export function ProductGrid({title, products}: {title?: string; products?: Array
47
47
  export function CollectionList({title, collections}: {title?: string; collections?: Array<Collection | string>}) {
48
48
  const actions = useCommerceActions();
49
49
  return (
50
- <section className={`grid gap-6 py-8 ${GUTTER}`}>
50
+ <section className={"grid gap-6 py-8"}>
51
51
  {title && <h2 className="text-2xl font-semibold">{title}</h2>}
52
52
  <div className="grid grid-cols-2 gap-6 md:grid-cols-4">
53
53
  {loaded(collections).map((collection) => (
@@ -70,25 +70,10 @@ export function Hero({heading, byline, collection}: {heading?: string; byline?:
70
70
  return (
71
71
  <button type="button" className="relative block aspect-[2/1] w-full overflow-hidden text-left" onClick={() => target && actions?.showCollection(target.title)}>
72
72
  {target && target.image && <img className="absolute inset-0 h-full w-full object-cover" src={target.image.url} alt={target.title} />}
73
- <div className={`absolute inset-x-0 bottom-0 grid gap-2 bg-gradient-to-t from-ink/70 py-8 text-paper ${GUTTER}`}>
73
+ <div className={"absolute inset-x-0 bottom-0 grid gap-2 bg-gradient-to-t from-ink/70 px-6 py-8 text-paper md:px-10"}>
74
74
  {heading && <h2 className="text-4xl font-semibold">{heading}</h2>}
75
75
  {byline && <p className="text-lg">{byline}</p>}
76
76
  </div>
77
77
  </button>
78
78
  );
79
79
  }
80
-
81
- /** The agent's prose on the canvas. */
82
- export function AgentText({text}: {text?: string}) {
83
- return <p className={`max-w-3xl text-lg ${GUTTER}`}>{text && renderInline(text, 'agent-text')}</p>;
84
- }
85
-
86
- /** One exchange: the visitor's ask, then whatever the agent composed for it. */
87
- export function Turn({prompt, children}: {prompt?: string; children?: ReactNode}) {
88
- return (
89
- <section className="grid gap-4 border-b border-ink/10 py-6">
90
- {prompt && <h2 className={`text-lg font-medium ${GUTTER}`}>“{prompt}”</h2>}
91
- {children}
92
- </section>
93
- );
94
- }
@@ -0,0 +1,17 @@
1
+ import type {BrandDefinition} from '@40rty/ams-sdk';
2
+
3
+ // `sourceId` is the package name; it keys the space's binding, so it never changes.
4
+ export const brand: BrandDefinition = {
5
+ sourceId: '__PACKAGE__',
6
+ theme: {id: '__PACKAGE__-theme', themeClass: 'fourty-theme-__SLUG__'},
7
+ label: '__LABEL__',
8
+ // How the agent builds a page from the blocks (./prompts/composition.md) — without it every answer is one grid.
9
+ promptSections: [
10
+ {
11
+ id: 'composition',
12
+ order: 210,
13
+ file: 'composition.md',
14
+ requires: ['render:verdict', 'render:shortlist', 'render:tradeoff', 'render:guidedPick', 'render:facts', 'render:explain', 'render:note', 'render:paths', 'render:productGrid'],
15
+ },
16
+ ],
17
+ };
@@ -1,5 +1,6 @@
1
1
  import {CollectionSchema, ProductSchema, resolved, z} from '@40rty/ams-sdk';
2
2
  import type {HostComponents} from '@40rty/ams-sdk';
3
+ import {conversationBlocks} from '@40rty/ams-ui/conversation';
3
4
 
4
5
  /**
5
6
  * What the agent may compose with this package. Pure data — `forty dev` and
@@ -7,9 +8,11 @@ import type {HostComponents} from '@40rty/ams-sdk';
7
8
  * by a component in `./blocks.tsx` and described to the agent in `./catalogs/`.
8
9
  *
9
10
  * `productGrid` and `collectionList` are required for a store: the agent's
10
- * commerce instructions are written against those two names.
11
+ * commerce instructions are written against those two names. The conversation
12
+ * blocks come with `@40rty/ams-ui/conversation`, their descriptions too.
11
13
  */
12
14
  export const catalog: HostComponents['catalog'] = {
15
+ ...Object.fromEntries(conversationBlocks.map(({component: _component, ...entry}) => [entry.type, entry])),
13
16
  productGrid: {
14
17
  type: 'productGrid',
15
18
  propsSchema: z.object({
@@ -1,20 +1,23 @@
1
1
  // What 40rty loads to draw this spacefront: a component for every type the agent
2
- // may compose (plus `agentText` and `turn`, how the agent speaks), the catalog
3
- // that describes them, and the page shell.
2
+ // may compose, the catalog that describes them, and the page shell.
4
3
  import {adaptComponent} from '@40rty/ams-sdk';
5
- import type {PackageBundleModule} from '@40rty/ams-sdk';
4
+ import type {PackageBundleModule, TurnAskPlacement} from '@40rty/ams-sdk';
5
+ import {conversationBlocks} from '@40rty/ams-ui/conversation';
6
6
 
7
- import {AgentText, CollectionList, Hero, ProductGrid, Turn} from './blocks';
7
+ import {CollectionList, Hero, ProductGrid} from './blocks';
8
8
  import {Shell} from './shell';
9
9
 
10
10
  export {catalog} from './catalog';
11
11
 
12
12
  export const renderers: PackageBundleModule['renderers'] = {
13
+ // verdict, shortlist, tradeoff, guidedPick, facts, explain, note, paths — the conversation blocks.
14
+ ...Object.fromEntries(conversationBlocks.map((block) => [block.type, block.component])),
13
15
  productGrid: adaptComponent(ProductGrid),
14
16
  collectionList: adaptComponent(CollectionList),
15
17
  hero: adaptComponent(Hero),
16
- agentText: adaptComponent(AgentText),
17
- turn: adaptComponent(Turn),
18
18
  };
19
19
 
20
20
  export const shells: PackageBundleModule['shells'] = {default: Shell};
21
+
22
+ // The agent's closing question is the turn page's last line, so it stays out of the prose.
23
+ export const turnAsk: TurnAskPlacement = 'shell';
@@ -1,34 +1,78 @@
1
- import {SpacefrontCanvas, useCart, useGoHome} from '@40rty/ams-sdk';
2
- import {SpacefrontIsland} from '@40rty/ams-ui/island';
3
- import '@40rty/ams-ui/island.css';
1
+ import {useCart, useComposerChipSelect, useGoHome, useScrollContainerRef, useThreadRows, renderInline} from '@40rty/ams-sdk';
2
+ import {Composer, ShellScaffold} from '@40rty/ams-ui/shell';
3
+ import {ConversationCanvas, ConversationProvider, PageComposer, type ConversationTileProps} from '@40rty/ams-ui/conversation';
4
+ import '@40rty/ams-ui/conversation.css';
5
+ import type {RefObject} from 'react';
6
+ import {ProductCard} from './blocks';
4
7
 
5
- /**
6
- * The page: a header, the canvas the agent composes onto, and the AMS island —
7
- * the floating composer every 40rty spacefront is recognised by. The island is
8
- * `@40rty/ams-ui`'s: its shape is fixed (grip, latest answer, field, round send
9
- * stamp, suggestion chips, a pill when folded); its look is the brand tokens,
10
- * mapped onto its `--fourty-island-*` properties in `styles.css`.
11
- */
12
- export function Shell() {
13
- const goHome = useGoHome();
14
- const {cart} = useCart();
8
+ const HEADER_HEIGHT = 64;
9
+ const PLACEHOLDER = 'Ask for anything';
10
+ const STARTERS = ['What do you recommend?', 'Show me your best sellers', 'A gift under $100'];
15
11
 
12
+ /** A product inside the conversation blocks is the store's own card. */
13
+ function StoreTile({product, blurb}: ConversationTileProps) {
16
14
  return (
17
- <div className="min-h-screen bg-paper text-ink antialiased">
18
- <header className="sticky top-0 z-40 flex h-16 items-center justify-between border-b border-ink/10 bg-paper/90 px-6 backdrop-blur md:px-10">
19
- <button type="button" className="font-semibold" onClick={goHome}>
20
- __LABEL__
21
- </button>
22
- <a href={cart ? cart.checkoutUrl : undefined} className="text-sm">
23
- Cart ({cart ? cart.totalQuantity : 0})
24
- </a>
25
- </header>
15
+ <div className="flex h-full flex-col gap-2">
16
+ <ProductCard product={product} />
17
+ {blurb && <p className="text-sm text-ink/70">{blurb}</p>}
18
+ </div>
19
+ );
20
+ }
26
21
 
27
- <main className="min-w-0 pb-56">
28
- <SpacefrontCanvas />
29
- </main>
22
+ /** The store's header, pinned over the canvas (the scaffold mounts it after the scrolling page, so it is placed, not sticky). */
23
+ function Header() {
24
+ const goHome = useGoHome();
25
+ const {cart} = useCart();
26
+ return (
27
+ <div className="absolute inset-x-0 top-0 z-50 flex items-center justify-between border-b border-ink/10 bg-paper px-6 md:px-10" style={{height: HEADER_HEIGHT}}>
28
+ <button type="button" className="font-semibold" onClick={goHome}>
29
+ __LABEL__
30
+ </button>
31
+ <a href={cart ? cart.checkoutUrl : undefined} className="text-sm">
32
+ Cart ({cart ? cart.totalQuantity : 0})
33
+ </a>
34
+ </div>
35
+ );
36
+ }
30
37
 
31
- <SpacefrontIsland />
38
+ /** The side panel's thread: each ask and the answer's words. */
39
+ function Thread(_props: {scrollerRef: RefObject<HTMLElement | null>}) {
40
+ const {rows} = useThreadRows();
41
+ return (
42
+ <div className="flex flex-col gap-6">
43
+ {rows.map((row) => (
44
+ <div key={row.key} className="grid gap-2">
45
+ <p className="justify-self-end rounded-2xl bg-ink/5 px-3 py-2 text-sm">{row.visitorText}</p>
46
+ {row.prose && <div className="text-sm">{renderInline(row.prose, `thread-${row.key}`)}</div>}
47
+ </div>
48
+ ))}
32
49
  </div>
33
50
  );
34
51
  }
52
+
53
+ /**
54
+ * Conversational UI: every question opens its own page — the visitor's words,
55
+ * the answer as a headline, then a page of blocks drawn with the store's cards.
56
+ * The canvas is the shell's own scroller (`scrollRef`): the page around it does
57
+ * not scroll, so a shell without it cannot scroll at all. The island — the
58
+ * floating prompt box — is the page composer on desktop and the composer on a phone.
59
+ */
60
+ export function Shell() {
61
+ const scrollRef = useScrollContainerRef();
62
+ const onChipSelect = useComposerChipSelect();
63
+ return (
64
+ <ConversationProvider tile={StoreTile}>
65
+ <ShellScaffold
66
+ scrollRef={scrollRef}
67
+ canvasPaddingTop={HEADER_HEIGHT}
68
+ dockTop={HEADER_HEIGHT}
69
+ gutter={32}
70
+ placeholder={PLACEHOLDER}
71
+ header={<Header />}
72
+ canvas={<ConversationCanvas />}
73
+ canvasComposer={<PageComposer placeholder={PLACEHOLDER} starters={STARTERS} />}
74
+ composer={<Composer placeholder={PLACEHOLDER} starterSuggestions={STARTERS} onChipSelect={onChipSelect} threadHistory={(ref) => <Thread scrollerRef={ref} />} />}
75
+ />
76
+ </ConversationProvider>
77
+ );
78
+ }
@@ -8,10 +8,25 @@
8
8
  --color-paper: 250 250 249;
9
9
  --color-accent: 191 72 0;
10
10
 
11
- /* The AMS island (`@40rty/ams-ui/island`), in the same tokens. */
12
- --fourty-island-surface: rgb(var(--color-paper));
13
- --fourty-island-fg: rgb(var(--color-ink));
14
- --fourty-island-accent: rgb(var(--color-accent));
15
- --fourty-island-accent-fg: rgb(var(--color-paper));
16
- --fourty-island-error: rgb(var(--color-accent));
11
+ /* The conversation page (`@40rty/ams-ui/conversation`), in the same tokens. */
12
+ --fourty-convo-sheet: rgb(var(--color-paper));
13
+ --fourty-convo-ink: rgb(var(--color-ink));
14
+ --fourty-convo-muted: rgb(var(--color-ink) / 0.6);
15
+ --fourty-convo-surface: rgb(var(--color-ink) / 0.04);
16
+ --fourty-convo-rule: rgb(var(--color-ink) / 0.12);
17
+ --fourty-convo-accent: rgb(var(--color-accent));
18
+ --fourty-convo-on-accent: rgb(var(--color-paper));
19
+ --fourty-convo-highlight: rgb(var(--color-accent));
20
+ --fourty-convo-on-highlight: rgb(var(--color-paper));
21
+ --fourty-convo-radius: 6px;
22
+ --fourty-convo-button-transform: none;
23
+ --fourty-convo-card-radius: 6px;
24
+ --fourty-convo-sheet-radius: 0;
25
+ --fourty-convo-composer-radius: 12px;
26
+
27
+ /* The platform chrome (side panel, the island on a phone), in the same tokens. */
28
+ --fourty-surface: rgb(var(--color-paper));
29
+ --fourty-fg: rgb(var(--color-ink));
30
+ --fourty-accent: rgb(var(--color-accent));
31
+ --fourty-accent-fg: rgb(var(--color-paper));
17
32
  }