@40rty/ams-cli 0.5.18 → 0.5.20

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.
@@ -0,0 +1,57 @@
1
+ // `forty connect <id> --<field> <value>` — the CLI maps flags onto the fields a
2
+ // connector declares and knows nothing else about it.
3
+ import { describe, expect, it } from 'vitest';
4
+ import { describeConnector, flagName, valuesFor } from '../connect.mjs';
5
+
6
+ const STORE = {
7
+ id: 'acme-store',
8
+ label: 'Acme',
9
+ blurb: 'A store.',
10
+ dataSource: true,
11
+ fields: [
12
+ { key: 'domain', label: 'Domain', hint: 'Where it is.', optional: false, env: ['STORE_DOMAIN', 'OTHER_DOMAIN'] },
13
+ { key: 'accessToken', label: 'Token', hint: 'Its key.', optional: false, env: ['STORE_TOKEN'] },
14
+ { key: 'savedCatalog', label: 'Saved catalog', hint: 'A view.', optional: true, env: [] },
15
+ ],
16
+ };
17
+
18
+ describe('flagName', () => {
19
+ it('is the field key in kebab case', () => {
20
+ expect(flagName('storefrontAccessToken')).toBe('storefront-access-token');
21
+ expect(flagName('domain')).toBe('domain');
22
+ });
23
+ });
24
+
25
+ describe('valuesFor', () => {
26
+ it('maps each flag onto the field it names, in both spellings, skipping the connector id', () => {
27
+ expect(valuesFor(STORE, ['acme-store', '--domain', 'a.example', '--access-token=t0k', '--saved-catalog', ''], {})).toEqual({
28
+ domain: 'a.example',
29
+ accessToken: 't0k',
30
+ savedCatalog: '',
31
+ });
32
+ });
33
+
34
+ it('reads a field left off the command line from `.env`, by the names the connector declares', () => {
35
+ expect(valuesFor(STORE, ['acme-store', '--access-token', 'flag'], { OTHER_DOMAIN: 'b.example', STORE_TOKEN: 'env' })).toEqual({
36
+ domain: 'b.example',
37
+ accessToken: 'flag',
38
+ });
39
+ });
40
+
41
+ it('refuses a flag the connector does not declare, naming the ones it does', () => {
42
+ expect(() => valuesFor(STORE, ['--token', 'x'], {})).toThrow(/--domain, --access-token, --saved-catalog/);
43
+ });
44
+
45
+ it('refuses a flag with no value', () => {
46
+ expect(() => valuesFor(STORE, ['--domain', '--access-token', 'x'], {})).toThrow(/--domain needs a value/);
47
+ });
48
+ });
49
+
50
+ describe('describeConnector', () => {
51
+ it('prints each field as the flag it is given by', () => {
52
+ const text = describeConnector(STORE);
53
+ expect(text).toContain('acme-store — Acme: A store.');
54
+ expect(text).toContain('--access-token Token — Its key. [.env: STORE_TOKEN]');
55
+ expect(text).toContain('--saved-catalog (optional)');
56
+ });
57
+ });
@@ -1,53 +1,72 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { cwd, fail, option, readConfig, storeBinding } from '../lib/context.mjs';
3
+ import { cwd, deployment, fail, flag, positionals, readConfig, readConfigIfPresent, readDotenv } from '../lib/context.mjs';
4
4
  import { call, request } from '../lib/credentials.mjs';
5
- import { resolveStorePage } from '../lib/store-page.mjs';
6
5
  import { displayName, titleCase } from './init.mjs';
7
6
 
8
- /** The Storefront API version the store is asked through. */
9
- const STOREFRONT_API = '2025-07';
10
- const SHOP_GID = /^gid:\/\/shopify\/Shop\/(\d+)$/;
7
+ // `forty connect` names no connector. What a deployment carries, and what each
8
+ // asks for, comes from the api (`GET /org/connectors`, the connector
9
+ // definitions the console draws its cards from); the values become what is
10
+ // stored on the server, by the connector's own definition.
11
+
12
+ /** The flag a field key is given as: `storefrontAccessToken` → `storefront-access-token`. */
13
+ export function flagName(key) {
14
+ return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
15
+ }
11
16
 
12
17
  /**
13
- * Ask the store itself, with the app's own token: proves the token works, and
14
- * answers the two things the agent needs that `.env` rarely carries — the
15
- * store's numeric id and its market — plus one product title, the query a
16
- * search probe can be sure the store sells.
18
+ * The values `args` (the command line after `connect`) and `env` (the app's
19
+ * `.env`) give `connector`'s declared fields. A flag wins over `.env`, which is
20
+ * read only by the names the connector declares for a field. A flag the
21
+ * connector does not declare is a mistake, not something to ignore.
17
22
  */
18
- export async function askStore(domain, token) {
19
- const url = `https://${domain}/api/${STOREFRONT_API}/graphql.json`;
20
- let res;
21
- try {
22
- res = await fetch(url, {
23
- method: 'POST',
24
- headers: { 'Content-Type': 'application/json', 'X-Shopify-Storefront-Access-Token': token },
25
- body: JSON.stringify({ query: '{ shop { id name } localization { country { isoCode } } products(first: 1) { nodes { title } } }' }),
26
- });
27
- } catch (err) {
28
- fail(`cannot reach the store at ${url} (${err.message}) — is PUBLIC_STORE_DOMAIN right?`);
23
+ export function valuesFor(connector, args, env) {
24
+ const byFlag = new Map(connector.fields.map((field) => [flagName(field.key), field]));
25
+ const values = {};
26
+ for (let i = 0; i < args.length; i += 1) {
27
+ if (!args[i].startsWith('--')) continue;
28
+ const eq = args[i].indexOf('=');
29
+ const name = args[i].slice(2, eq === -1 ? undefined : eq);
30
+ const field = byFlag.get(name);
31
+ if (field === undefined) {
32
+ const known = [...byFlag.keys()].map((known) => `--${known}`).join(', ');
33
+ fail(`${connector.id} has no --${name} — it takes ${known === '' ? 'no values' : known}`);
34
+ }
35
+ let value;
36
+ if (eq !== -1) {
37
+ value = args[i].slice(eq + 1);
38
+ } else {
39
+ value = args[i + 1];
40
+ if (value === undefined || value.startsWith('--')) fail(`--${name} needs a value`);
41
+ i += 1;
42
+ }
43
+ values[field.key] = value;
29
44
  }
30
- const body = await res.json().catch((err) => fail(`the store at ${url} answered ${res.status} with no JSON (${err.message})`));
31
- if (!res.ok || Array.isArray(body.errors) || body.data === undefined || body.data === null) {
32
- const reason = Array.isArray(body.errors) ? body.errors.map((e) => e.message).join('; ') : `HTTP ${res.status}`;
33
- fail(`the store refused PUBLIC_STOREFRONT_API_TOKEN (${reason}) — create a Storefront API token for ${domain} and put it in .env`);
45
+ for (const field of connector.fields) {
46
+ if (field.key in values) continue;
47
+ const name = field.env.find((candidate) => typeof env[candidate] === 'string' && env[candidate].trim() !== '');
48
+ if (name !== undefined) values[field.key] = env[name];
49
+ }
50
+ return values;
51
+ }
52
+
53
+ /** One connector as `--list` prints it: what it is, then each flag it takes. */
54
+ export function describeConnector(connector) {
55
+ const lines = [`${connector.id} — ${connector.label}: ${connector.blurb}${connector.dataSource ? ' (the space\'s data source)' : ''}`];
56
+ for (const field of connector.fields) {
57
+ const from = field.env.length === 0 ? '' : ` [.env: ${field.env.join(' | ')}]`;
58
+ lines.push(` --${flagName(field.key)}${field.optional ? ' (optional)' : ''} ${field.label} — ${field.hint}${from}`);
34
59
  }
35
- const match = SHOP_GID.exec(String(body.data.shop.id));
36
- const country = body.data.localization === null ? undefined : body.data.localization.country.isoCode;
37
- const first = body.data.products === null || body.data.products === undefined ? undefined : body.data.products.nodes[0];
38
- return {
39
- shopId: match === null ? undefined : match[1],
40
- shopName: typeof body.data.shop.name === 'string' && body.data.shop.name.trim() !== '' ? body.data.shop.name.trim() : undefined,
41
- marketCountry: typeof country === 'string' && country.length === 2 ? country : undefined,
42
- sampleTitle: first === undefined || typeof first.title !== 'string' ? undefined : first.title,
43
- };
60
+ if (connector.fields.length === 0) lines.push(' (nothing to fill in)');
61
+ return lines.join('\n');
44
62
  }
45
63
 
46
64
  /**
47
65
  * One real catalog search through the space's own agent tools
48
- * (`POST /org/spaces/:slug/probe-search`) — the store answering its own API
49
- * does not mean the agent can find its products. `{ ok, count, titles, query }`,
50
- * or `{ ok: false, error }` when the search could not run.
66
+ * (`POST /org/spaces/:slug/probe-search`) — a connected data source answering
67
+ * its own API does not mean the agent can find anything in it. With no query,
68
+ * the server searches for something the data source says it holds.
69
+ * `{ ok, count, titles, query }`, or `{ ok: false, error }` when it could not run.
51
70
  */
52
71
  export async function probeSearch(config, query) {
53
72
  const res = await request(config.apiUrl, 'POST', `/org/spaces/${config.spaceSlug}/probe-search`, query === undefined ? {} : { query });
@@ -55,87 +74,47 @@ export async function probeSearch(config, query) {
55
74
  return { ok: true, ...res.body };
56
75
  }
57
76
 
58
- /** The space's current name when `forty init` derived it rather than a person choosing it, else `undefined`. */
59
- async function derivedName(config) {
77
+ /** Whether the space's current name is one `forty init` derived rather than a person chose. */
78
+ async function nameIsDerived(config) {
60
79
  const me = await request(config.apiUrl, 'GET', '/org/me');
61
80
  const space = me.ok ? me.body.spaces.find((candidate) => candidate.slug === config.spaceSlug) : undefined;
62
- if (space === undefined) return undefined;
81
+ if (space === undefined) return false;
63
82
  const manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8').catch((err) => {
64
83
  if (err.code === 'ENOENT') return '{}';
65
84
  throw err;
66
85
  }));
67
- const derived = [config.spaceSlug, titleCase(config.spaceSlug), displayName(manifest.name)];
68
- return derived.includes(space.name) ? space.name : undefined;
86
+ return [config.spaceSlug, titleCase(config.spaceSlug), displayName(manifest.name)].includes(space.name);
69
87
  }
70
88
 
71
- /** Why a search that ran found nothing — the one cause we see over and over. */
72
- export const ZERO_RESULTS_HINT = 'unpublished/dev stores are not in Shopify\'s global catalog — publish the store (remove its password) and put its products on the Shop channel, or search the store\'s own catalog instead: `forty connect --search storefront`';
73
-
74
- /** Where the agent's catalog search runs: Shopify's Global catalog (by shop id), or the store's own Storefront search. */
75
- const SEARCH_MODES = ['global', 'storefront'];
76
-
77
- /** `forty connect` — attach this app's store to the space. What the space renders is not decided here. */
89
+ /** `forty connect --list` | `forty connect <connector> [--<field> <value> ...]` */
78
90
  export async function connect() {
79
- const config = await readConfig();
80
- // `--from <storefront url>` reads the store's domain and its public Storefront
81
- // token off the page every visitor's browser already gets (./store-page.mjs).
82
- const from = option('from');
83
- const page = from === undefined ? undefined : await resolveStorePage(from);
84
- if (page !== undefined && 'error' in page) fail(`--from: ${page.error}`);
85
- // `--domain` / `--token` / `--shop-id` win over `--from`, which wins over `.env`.
86
- const env = page === undefined ? await storeBinding() : { ...(await storeBinding()), domain: page.domain, token: page.token };
87
- const pick = (flagName, fromEnv) => (option(flagName) !== undefined ? option(flagName) : fromEnv);
88
- const binding = { domain: pick('domain', env.domain), token: pick('token', env.token), shopId: pick('shop-id', env.shopId) };
89
- // An empty `.env` value is absence: `PUBLIC_STOREFRONT_API_TOKEN=` once
90
- // stored `storefrontAccessToken: ""`, which the connector refuses wholesale.
91
- const present = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);
92
- const domain = present(binding.domain);
93
- const token = present(binding.token);
94
- 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');
95
- const host = domain.replace(/^https?:\/\//, '').replace(/\/+$/, '');
96
- // `--search global` (default): Shopify's Global catalog, scoped by the
97
- // store's shop id, with the store's own search beside it. `--search
98
- // storefront`: the store's own Storefront search only — for a store Global
99
- // does not index (a dev store, mock.shop, a Storefront-shaped mock API).
100
- const search = option('search') === undefined ? 'global' : option('search');
101
- if (!SEARCH_MODES.includes(search)) fail(`--search must be one of ${SEARCH_MODES.join(', ')} (got "${search}")`);
102
- if (host === 'mock.shop' && search === 'global') fail('mock.shop is not in Shopify\'s Global catalog — connect it with `--search storefront`');
103
-
104
- const store = await askStore(host, token);
105
- const settings = { hosting: { embedded: true, headless: true }, storefrontAccessToken: token };
106
- let shopId;
107
- if (search === 'global') {
108
- shopId = present(binding.shopId) !== undefined ? present(binding.shopId) : store.shopId;
109
- if (shopId === undefined) {
110
- fail(`could not work out ${host}'s shop id, which Global catalog search is scoped by — set SHOP_ID in .env to the number in gid://shopify/Shop/<n>, or search the store's own catalog: \`--search storefront\``);
111
- }
112
- settings.globalShopId = shopId;
113
- // The store's market: Global search ranks by ship-to country and defaults to the US.
114
- if (store.marketCountry !== undefined) settings.marketCountry = store.marketCountry;
115
- } else {
116
- // An empty value removes a shop id an earlier `forty connect` stored, so
117
- // catalog search routes to the store's own search.
118
- settings.globalShopId = '';
91
+ const listing = flag('list');
92
+ const config = listing ? await readConfigIfPresent() : await readConfig();
93
+ const { apiUrl } = listing ? deployment(config) : config;
94
+ const { connectors } = await call(apiUrl, 'GET', '/org/connectors');
95
+ if (listing) {
96
+ console.log(connectors.map(describeConnector).join('\n\n'));
97
+ return;
119
98
  }
120
99
 
121
- const body = { platform: 'shopify', platformConfig: { platform: 'shopify', domain: host, config: settings }, vertical: 'ecommerce' };
122
- // The agent greets visitors by the space's name: a name `forty init` derived
123
- // (from the slug or package.json) gives way to the store's own.
124
- const rename = store.shopName === undefined ? undefined : await derivedName(config);
125
- if (rename !== undefined && rename !== store.shopName) body.name = store.shopName;
126
- const result = await call(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/storefront`, body);
127
- if (body.name !== undefined) console.log(`space "${result.slug}" is now named "${body.name}" (was "${rename}", derived by \`forty init\`)`);
128
- const how = search === 'global' ? `shop ${shopId}, Global catalog search${store.marketCountry === undefined ? '' : `, market ${store.marketCountry}`}` : 'the store\'s own catalog search';
129
- console.log(`space "${result.slug}" is connected to ${host} (${how}) — \`forty dev\` to work on it`);
100
+ const ids = connectors.map((connector) => connector.id).join('|');
101
+ const [id] = positionals();
102
+ if (id === undefined) fail(`usage: forty connect <${ids}> [--<field> <value> ...] — \`forty connect --list\` shows what each takes`);
103
+ const connector = connectors.find((candidate) => candidate.id === id);
104
+ if (connector === undefined) fail(`this deployment has no connector "${id}" — it has ${ids}`);
130
105
 
131
- // Connected is not searchable: run the agent's own search once, for a product the store just named.
132
- const probe = await probeSearch(config, store.sampleTitle);
133
- if (!probe.ok) {
134
- console.warn(`\n!! WARNING: the agent's catalog search could not run (${probe.error})`);
135
- } else if (probe.count === 0) {
136
- console.warn(`\n!! WARNING: the agent's catalog search for "${probe.query}" found NOTHING — visitors will see no products.`);
137
- console.warn(`!! ${ZERO_RESULTS_HINT}`);
138
- } else {
139
- console.log(`search works: "${probe.query}" → ${probe.count} result(s): ${probe.titles.join(', ')}`);
140
- }
106
+ const values = valuesFor(connector, process.argv.slice(3), await readDotenv(path.join(cwd, '.env')));
107
+ const res = await request(config.apiUrl, 'PUT', `/org/spaces/${config.spaceSlug}/connectors/${connector.id}`, { values, adoptName: await nameIsDerived(config) });
108
+ if (!res.ok) fail(`${connector.label} was not connected (${res.status}): ${res.body.error} — \`forty connect --list\` shows its fields`);
109
+ const result = res.body;
110
+ const shown = Object.entries(result.values).map(([key, value]) => `${flagName(key)} ${value}`).join(', ');
111
+ console.log(`space "${config.spaceSlug}" is connected to ${connector.label}${shown === '' ? '' : ` (${shown})`}`);
112
+ if (result.name !== undefined) console.log(`space "${config.spaceSlug}" is now named "${result.name}" (its name was derived by \`forty init\`)`);
113
+ if (!result.dataSource) return;
114
+
115
+ // Connected is not searchable: run the agent's own search once.
116
+ const probe = await probeSearch(config);
117
+ if (!probe.ok) console.warn(`\n!! WARNING: the agent's search could not run (${probe.error})`);
118
+ else if (probe.count === 0) console.warn(`\n!! WARNING: the agent's search for "${probe.query}" found NOTHING — visitors will be shown nothing from ${connector.label}.`);
119
+ else console.log(`search works: "${probe.query}" → ${probe.count} result(s): ${probe.titles.join(', ')}`);
141
120
  }
@@ -11,10 +11,10 @@ import path from 'node:path';
11
11
  import { catalogToWire } from '../../dist/wire.js';
12
12
  import { askSpace, judgeTurn } from '../lib/ask.mjs';
13
13
  import { loadCatalog } from '../lib/build.mjs';
14
- import { appKind, cwd, FortyError, flag, option, positionals, readConfig, readDotenv, storeBinding } from '../lib/context.mjs';
14
+ import { appKind, cwd, flag, option, positionals, readConfig, readDotenv } from '../lib/context.mjs';
15
15
  import { findCredential, request } from '../lib/credentials.mjs';
16
16
  import { agenticFramework, agenticWiringProblems } from '../lib/agentic.mjs';
17
- import { askStore, probeSearch, ZERO_RESULTS_HINT } from './connect.mjs';
17
+ import { probeSearch } from './connect.mjs';
18
18
 
19
19
  /** What a space bound to a store requires a source to draw, and what the agent speaks through. */
20
20
  const STORE_TYPES = ['productGrid', 'collectionList'];
@@ -241,24 +241,14 @@ async function askCheck(config, check, linkToken) {
241
241
 
242
242
  /**
243
243
  * The agent's own catalog search, run once (`POST /org/spaces/:slug/probe-search`)
244
- * for a product the store itself names — a store whose API answers can still
245
- * be missing from the index the agent searches.
244
+ * for something the space's data source says it holds — a source whose API
245
+ * answers can still be missing from the index the agent searches.
246
246
  */
247
247
  async function searchCheck(config, check) {
248
- const binding = await storeBinding();
249
- let query;
250
- if (typeof binding.domain === 'string' && binding.domain !== '' && typeof binding.token === 'string' && binding.token !== '') {
251
- try {
252
- query = (await askStore(binding.domain.replace(/^https?:\/\//, '').replace(/\/+$/, ''), binding.token)).sampleTitle;
253
- } catch (err) {
254
- if (!(err instanceof FortyError)) throw err;
255
- console.log(` (could not ask the store for a product to search for: ${err.message})`);
256
- }
257
- }
258
- const probe = await probeSearch(config, query);
248
+ const probe = await probeSearch(config);
259
249
  if (!probe.ok) {
260
250
  check(false, 'the agent\'s catalog search runs', probe.error);
261
251
  return;
262
252
  }
263
- check(probe.count > 0, `the agent's catalog search finds "${probe.query}" (${probe.count} result(s)${probe.titles.length === 0 ? '' : `: ${probe.titles.slice(0, 3).join(', ')}`})`, ZERO_RESULTS_HINT);
253
+ check(probe.count > 0, `the agent's catalog search finds "${probe.query}" (${probe.count} result(s)${probe.titles.length === 0 ? '' : `: ${probe.titles.slice(0, 3).join(', ')}`})`, 'check what the space is connected to — `forty connect --list`, then reconnect it');
264
254
  }
package/bin/forty.mjs CHANGED
@@ -16,10 +16,11 @@
16
16
  // `--message "…"` (required, one line) says what the release changed
17
17
  // forty releases the package's release history, and which one is live
18
18
  // forty rollback make an earlier release live again (`forty rollback 3`)
19
- // forty connect attach this app's store to the space (`--from <store url>`
20
- // reads its public Storefront token off the live page;
21
- // `--search storefront` searches the store's own catalog
22
- // instead of Shopify's Global one)
19
+ // forty connect connect the space to one of the connectors this deployment
20
+ // carries: `forty connect --list` prints each one and the
21
+ // fields it takes; `forty connect <id> --<field> <value> …`
22
+ // connects it (a field left out is read from `.env` by the
23
+ // names the connector declares), then runs a real search
23
24
  // forty origin add let a deployed site's origin call the api (CORS)
24
25
  // forty domain add serve the space on your own domain; prints the DNS records
25
26
  // forty feedback report a problem to the 40rty team
@@ -1,5 +1,5 @@
1
- // What every command shares: where it is running, the config file, the store
2
- // binding, and which 40rty deployment it talks to.
1
+ // What every command shares: where it is running, the config file, and which
2
+ // 40rty deployment it talks to.
3
3
  import { readFile, writeFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
 
@@ -80,25 +80,6 @@ export async function readDotenv(file) {
80
80
  return out;
81
81
  }
82
82
 
83
- /** The first of `names` set (non-empty) in `env`. */
84
- function firstOf(env, names) {
85
- const name = names.find((candidate) => typeof env[candidate] === 'string' && env[candidate].trim() !== '');
86
- return name === undefined ? undefined : env[name];
87
- }
88
-
89
- /**
90
- * The store this app sells from, read from its own `.env` — Hydrogen's names
91
- * first, then Next.js Commerce's (`SHOPIFY_STORE_DOMAIN`, `SHOPIFY_STOREFRONT_ACCESS_TOKEN`).
92
- */
93
- export async function storeBinding() {
94
- const env = await readDotenv(path.join(cwd, '.env'));
95
- return {
96
- domain: firstOf(env, ['PUBLIC_STORE_DOMAIN', 'SHOPIFY_STORE_DOMAIN']),
97
- token: firstOf(env, ['PUBLIC_STOREFRONT_API_TOKEN', 'SHOPIFY_STOREFRONT_ACCESS_TOKEN']),
98
- shopId: env.SHOP_ID,
99
- };
100
- }
101
-
102
83
  /** Frameworks whose app serves its own pages — and so hosts the spacefront itself. */
103
84
  const APP_FRAMEWORKS = ['@shopify/hydrogen', 'next', 'react-router', '@remix-run/react', '@remix-run/node'];
104
85
 
@@ -155,7 +136,7 @@ export function flag(name) {
155
136
  }
156
137
 
157
138
  /** Valueless switches that do not start with `--no-` — every other flag takes a value. */
158
- const SWITCHES = new Set(['--detect', '--keep-locked', '--self-hosted', '--package']);
139
+ const SWITCHES = new Set(['--detect', '--keep-locked', '--self-hosted', '--package', '--list']);
159
140
 
160
141
  /** The command's arguments that are not flags or flag values, in order. */
161
142
  export function positionals() {