gipity 1.1.21 → 1.1.23

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.
package/dist/adopt-cwd.js CHANGED
@@ -41,7 +41,7 @@ export function scanForAdoption(cwd) {
41
41
  for (const name of entries) {
42
42
  if (truncated)
43
43
  return;
44
- if (isSyncIgnored(name))
44
+ if (isSyncIgnored(name, { nested: dir !== cwd }))
45
45
  continue;
46
46
  const full = join(dir, name);
47
47
  let st;
@@ -86,7 +86,7 @@ export function isLikelyEmpty(cwd) {
86
86
  catch {
87
87
  return true;
88
88
  }
89
- return entries.every(isSyncIgnored);
89
+ return entries.every((name) => isSyncIgnored(name));
90
90
  }
91
91
  /** Hide-list for "Use this directory" - places where adopting cwd as a
92
92
  * project is obviously wrong. Exact-match only; subdirectories are fine
package/dist/api.js CHANGED
@@ -184,13 +184,23 @@ export async function getAuthHeader() {
184
184
  const headers = await getHeaders();
185
185
  return headers.Authorization;
186
186
  }
187
+ /** A FormData body goes out as multipart/form-data (fetch sets the boundary
188
+ * header itself, so callers must not send a JSON Content-Type with it); any
189
+ * other body is JSON. */
190
+ function encodeBody(body) {
191
+ if (body instanceof FormData)
192
+ return body;
193
+ return body ? JSON.stringify(body) : undefined;
194
+ }
187
195
  async function request(method, path, body, retrying = false, timeoutMs = REQUEST_TIMEOUT_MS) {
188
196
  const headers = await getHeaders();
189
197
  const url = `${baseUrl()}${path}`;
198
+ if (body instanceof FormData)
199
+ delete headers['Content-Type'];
190
200
  const res = await fetchWithTimeout(url, {
191
201
  method,
192
202
  headers,
193
- body: body ? JSON.stringify(body) : undefined,
203
+ body: encodeBody(body),
194
204
  }, timeoutMs, `${method} ${path}`);
195
205
  if (await shouldRetryAfter401(res.status, retrying)) {
196
206
  return request(method, path, body, true, timeoutMs);
@@ -425,13 +435,14 @@ export async function getAccountSlug() {
425
435
  /** Unauthenticated request (for login/verify, and anonymous-visitor calls like
426
436
  * `fn call --anon`). extraHeaders lets callers attach non-auth headers such as
427
437
  * X-App-Token; no Authorization header is ever sent. */
428
- export async function publicRequest(method, path, body, extraHeaders) {
438
+ export async function publicRequest(method, path, body, extraHeaders, timeoutMs = REQUEST_TIMEOUT_MS) {
429
439
  const url = `${baseUrl()}${path}`;
440
+ const isForm = body instanceof FormData;
430
441
  const res = await fetchWithTimeout(url, {
431
442
  method,
432
- headers: { ...clientHeaders(), 'Content-Type': 'application/json', ...extraHeaders },
433
- body: body === undefined ? undefined : JSON.stringify(body),
434
- }, REQUEST_TIMEOUT_MS, `${method} ${path}`);
443
+ headers: { ...clientHeaders(), ...(isForm ? {} : { 'Content-Type': 'application/json' }), ...extraHeaders },
444
+ body: isForm ? body : body === undefined ? undefined : JSON.stringify(body),
445
+ }, timeoutMs, `${method} ${path}`);
435
446
  if (!res.ok) {
436
447
  const json = await res.json().catch(() => null);
437
448
  throw apiErrorFrom(res, json, `${method} ${path}`, false);
@@ -27,7 +27,7 @@ function printBrand(d) {
27
27
  if (d.branding.tagline)
28
28
  console.log(`${bold('Tagline:')} ${d.branding.tagline}`);
29
29
  }
30
- const DEPLOY_HINT = 'Deploy to publish the new assets: gipity deploy dev';
30
+ const DEPLOY_HINT = 'Deploy to publish the new assets: gipity deploy';
31
31
  export const brandCommand = new Command('brand')
32
32
  .description("The app's generated icons + share card (favicons, iOS icon, og-image)")
33
33
  .addHelpText('after', `
@@ -1,6 +1,6 @@
1
1
  import { Command } from 'commander';
2
- import { post } from '../api.js';
3
- import { requireConfig, resolveApiBase } from '../config.js';
2
+ import { get, post } from '../api.js';
3
+ import { requireConfig, resolveApiBase, getEnvOption } from '../config.js';
4
4
  import { formatSize } from '../utils.js';
5
5
  import { success, error as clrError, warning, muted, bold, brand } from '../colors.js';
6
6
  import { run, syncBeforeAction } from '../helpers/index.js';
@@ -16,10 +16,39 @@ function statusIcon(status) {
16
16
  return warning('⚠');
17
17
  return muted('→');
18
18
  }
19
+ async function printPlan(appGuid, env, json) {
20
+ const res = await get(`/projects/${appGuid}/envs/${encodeURIComponent(env)}/plan`);
21
+ const p = res.data;
22
+ if (json) {
23
+ console.log(JSON.stringify(p));
24
+ return;
25
+ }
26
+ console.log(brand(bold(`Deploy plan for ${p.env}`)));
27
+ console.log(muted('─'.repeat(40)));
28
+ if (p.pending.length === 0) {
29
+ console.log(success(`✓ No pending migrations: ${p.env}'s database is up to date.`));
30
+ return;
31
+ }
32
+ for (const m of p.pending) {
33
+ const where = m.ranOn.length
34
+ ? muted(`ran on ${m.ranOn.map((r) => `${r.env} ${new Date(r.appliedAt).toLocaleDateString()}`).join(', ')}`)
35
+ : warning('has not run anywhere yet');
36
+ const edited = p.changed.includes(m.file) ? muted(' (edited since it ran here; runs again)') : '';
37
+ console.log(`${m.destructive.length ? clrError('!') : muted('→')} ${bold(m.file)} ${where}${edited}`);
38
+ for (const d of m.destructive)
39
+ console.log(` ${clrError(d)}`);
40
+ }
41
+ if (p.env === 'prod' && p.pending.some((m) => m.destructive.length)) {
42
+ console.log('');
43
+ console.log(warning('A prod deploy stops on the destructive statements above until you pass --yes-destructive.'));
44
+ }
45
+ }
19
46
  // ── Main Deploy Command ────────────────────────────────────────────────
20
47
  export const deployCommand = new Command('deploy')
21
- .description('Deploy to dev or prod')
22
- .argument('[target]', 'dev or prod', 'dev')
48
+ .description('Deploy the app to prod, or to an environment (created on first deploy)')
49
+ .argument('[env]', 'prod, or an environment name (dev, staging, ...). Omitted: prod while the app has no environments; once it has any, name one')
50
+ .option('--yes-destructive', 'Allow pending prod migrations that destroy data (DROP TABLE/COLUMN, TRUNCATE, DELETE without WHERE, column type changes)')
51
+ .option('--plan', 'Show the pending migrations this deploy would run (and where each already ran), without deploying')
23
52
  .option('--source-dir <dir>', 'Source directory to deploy from')
24
53
  .option('--only <phases>', 'Run only specific phases, comma-separated, matched by gipity.yaml phase name or type: files/static, database/sql, functions, workflows, services, jobs, records, realtime, env, auth_branding')
25
54
  .option('--force', 'Re-run all phases (ignore checksums) and bypass the sync bulk-deletion guard')
@@ -35,10 +64,12 @@ export const deployCommand = new Command('deploy')
35
64
  .option('--wait <ms>', 'With --inspect: sleep this many ms before capturing (max 30000)')
36
65
  .option('--wait-for <selector>', "With --inspect: wait until this CSS selector appears before capturing (deterministic; the app's own ready signal)")
37
66
  .option('--wait-timeout <ms>', 'With --inspect: max ms to wait for --wait-for before giving up', '5000')
38
- .action((target, opts) => run('Deploy', async () => {
39
- if (target !== 'dev' && target !== 'prod') {
40
- console.error(clrError('Target must be "dev" or "prod"'));
41
- process.exit(1);
67
+ .action((envArg, opts) => run('Deploy', async () => {
68
+ // `gipity deploy staging` and `gipity deploy --env staging` are the same.
69
+ const env = envArg ?? getEnvOption();
70
+ if (opts.plan) {
71
+ await printPlan(requireConfig().projectGuid, env ?? 'prod', !!opts.json);
72
+ return;
42
73
  }
43
74
  // A settle flag only means one thing on a deploy: "verify the page once it's
44
75
  // up, and give it time to come up." Asking for it without --inspect is not an
@@ -49,7 +80,8 @@ export const deployCommand = new Command('deploy')
49
80
  const config = requireConfig();
50
81
  await syncBeforeAction(opts);
51
82
  const doDeploy = () => post(`/projects/${config.projectGuid}/deploy`, {
52
- target,
83
+ ...(env ? { env } : {}),
84
+ ...(opts.yesDestructive ? { yesDestructive: true } : {}),
53
85
  sourceDir: opts.sourceDir,
54
86
  optimize: opts.optimize,
55
87
  force: opts.force,
@@ -57,8 +89,9 @@ export const deployCommand = new Command('deploy')
57
89
  });
58
90
  const res = opts.json
59
91
  ? await doDeploy()
60
- : await withSpinner(`Deploying to ${target}...`, doDeploy, { done: null });
92
+ : await withSpinner(env ? `Deploying to ${env}...` : 'Deploying...', doDeploy, { done: null });
61
93
  const d = res.data;
94
+ const where = d.env ?? d.target;
62
95
  // Deploy + verify in one command: after a successful deploy, run the
63
96
  // same inspect pipeline `page inspect` uses against the live URL. An
64
97
  // inspect failure is reported but never turns a successful deploy into
@@ -88,13 +121,17 @@ export const deployCommand = new Command('deploy')
88
121
  if (opts.json) {
89
122
  console.log(JSON.stringify(d));
90
123
  const failedJson = d.phases?.some(p => p.status === 'failed');
91
- if (!failedJson)
92
- await inspectAfter();
124
+ // The exit code carries the outcome too, so a script reading --json
125
+ // can't mistake a failed deploy (e.g. a refused destructive migration)
126
+ // for a good one.
127
+ if (failedJson)
128
+ process.exit(1);
129
+ await inspectAfter();
93
130
  return;
94
131
  }
95
132
  // Format output
96
133
  const batchLabel = d.batch ? muted(` (batch ${d.batch})`) : '';
97
- console.log(brand(bold(`Deploy to ${target}`)) + batchLabel);
134
+ console.log(brand(bold(`Deploy to ${where}`)) + batchLabel + (d.created ? muted(' (new environment)') : ''));
98
135
  console.log(muted('─'.repeat(40)));
99
136
  if (d.phases && d.phases.length > 0) {
100
137
  for (const phase of d.phases) {
@@ -140,7 +177,7 @@ export const deployCommand = new Command('deploy')
140
177
  process.exit(1);
141
178
  }
142
179
  else {
143
- console.log(success(`✓ Deployed to ${target}`) + muted(` (${d.elapsedMs}ms)`));
180
+ console.log(success(`✓ Deployed to ${where}`) + muted(` (${d.elapsedMs}ms)`));
144
181
  // The live URL is the one thing the caller (often an agent) needs next
145
182
  // - to open it, inspect it, or report it. Always surface it so nobody
146
183
  // has to reconstruct the URL convention or guess a subdomain.
@@ -154,9 +191,13 @@ export const deployCommand = new Command('deploy')
154
191
  // --api-base flag and GIPITY_API_BASE env), not the raw stored
155
192
  // config.apiBase - otherwise on any override we'd advertise a host we
156
193
  // didn't deploy to and send the caller probing the wrong instance.
157
- console.log(`${muted('Functions:')} POST ${brand(`${resolveApiBase()}/api/${config.projectGuid}/fn/<name>`)}`);
158
- console.log(muted(' (same address on dev and prod; names: gipity fn list; verify the public path: gipity fn call <name> --anon)'));
194
+ console.log(`${muted('Functions:')} POST ${brand(`${resolveApiBase()}/api/${d.appGuid ?? config.projectGuid}/fn/<name>`)}`);
195
+ // Each environment has its own functions at its own address.
196
+ const envFlag = d.env && d.env !== 'prod' ? ` --env ${d.env}` : '';
197
+ console.log(muted(` (names: gipity fn list${envFlag}; verify the public path: gipity fn call <name>${envFlag} --anon)`));
159
198
  }
199
+ for (const hint of d.hints ?? [])
200
+ console.log(muted(hint));
160
201
  await inspectAfter();
161
202
  }
162
203
  }));
@@ -0,0 +1,168 @@
1
+ import { Command } from 'commander';
2
+ import { get, post, patch, del } from '../api.js';
3
+ import { requireConfig, PROD_ENV } from '../config.js';
4
+ import { formatSize } from '../utils.js';
5
+ import { success, error as clrError, muted, bold, brand } from '../colors.js';
6
+ import { run } from '../helpers/index.js';
7
+ import { confirm } from '../utils.js';
8
+ import { withSpinner } from '../progress.js';
9
+ /** The app's guid: env commands always act on the app, whatever --env says. */
10
+ function appGuid() {
11
+ return requireConfig().projectGuid;
12
+ }
13
+ export const envCommand = new Command('env')
14
+ .description('App environments: prod plus any number of isolated copies (dev, staging, ...), each with its own database, functions and URL')
15
+ .addHelpText('after', `
16
+ An environment is created the first time you deploy to it:
17
+ gipity deploy dev # creates "dev" (own DB from migrations, own functions), deploys
18
+ gipity deploy prod # the live app
19
+
20
+ Run any project command against one with --env:
21
+ gipity db query "SELECT count(*) FROM orders" --env dev
22
+ gipity fn call checkout --env staging
23
+ gipity logs fn checkout --env dev
24
+
25
+ Envs share the app's secrets (an env can override one: gipity secrets set NAME value --env staging),
26
+ members and players. Cron workflows are off in an env until: gipity env set <name> --schedules on.
27
+ Email from an env reaches only the app owner and members; payments run in prod only.`);
28
+ envCommand
29
+ .command('list', { isDefault: true })
30
+ .description('List the app\'s environments')
31
+ .option('--json', 'Output as JSON')
32
+ .action((opts) => run('Env', async () => {
33
+ const res = await get(`/projects/${appGuid()}/envs`);
34
+ const d = res.data;
35
+ if (opts.json) {
36
+ console.log(JSON.stringify(d));
37
+ return;
38
+ }
39
+ console.log(`${bold('prod')} ${brand(d.prod.url)}`);
40
+ if (d.envs.length === 0) {
41
+ console.log(muted('No environments yet. `gipity deploy dev` creates one.'));
42
+ return;
43
+ }
44
+ for (const e of d.envs) {
45
+ const deployed = e.lastDeploy ? `deployed ${new Date(e.lastDeploy).toLocaleString()}` : 'never deployed';
46
+ const parts = [deployed, `DB ${formatSize(e.dbBytes)}`, e.schedules ? 'schedules on' : 'schedules off'];
47
+ if (e.customDomains.length)
48
+ parts.push(e.customDomains.join(', '));
49
+ console.log(`${bold(e.name)} ${brand(e.url)} ${muted(parts.join(' · '))}`);
50
+ }
51
+ }));
52
+ function printCopy(copy) {
53
+ if (!copy)
54
+ return;
55
+ for (const d of copy.databases) {
56
+ console.log(muted(`Copied ${d.rows} rows (${d.tables} tables) from ${copy.from}'s ${d.database} database`));
57
+ }
58
+ }
59
+ envCommand
60
+ .command('create <name>')
61
+ .description('Create an environment and deploy the app to it (`gipity deploy <name>` does the same, without --data)')
62
+ .option('--data', 'Copy the rows of prod (or --from) into it, to try a change against real data')
63
+ .option('--from <env>', 'With --data: the environment to copy from (default prod)')
64
+ .option('--json', 'Output as JSON')
65
+ .action((name, opts) => run('Env', async () => {
66
+ if (name === PROD_ENV) {
67
+ console.error(clrError('prod is the app itself. Deploy it with: gipity deploy prod'));
68
+ process.exit(1);
69
+ }
70
+ if (opts.from && !opts.data) {
71
+ console.error(clrError('--from goes with --data'));
72
+ process.exit(1);
73
+ }
74
+ const create = () => post(`/projects/${appGuid()}/envs`, { name, ...(opts.data ? { data: true } : {}), ...(opts.from ? { from: opts.from } : {}) });
75
+ const res = opts.json ? await create() : await withSpinner(`Creating ${name}...`, create, { done: null });
76
+ if (opts.json) {
77
+ console.log(JSON.stringify(res.data));
78
+ return;
79
+ }
80
+ const failed = res.data.phases.filter((p) => p.status === 'failed');
81
+ for (const p of failed)
82
+ console.log(`${clrError('✗')} ${bold(p.name)}: ${p.summary}`);
83
+ if (failed.length > 0) {
84
+ console.log(clrError(`Created ${name}, but its first deploy failed. Fix it and run: gipity deploy ${name}`));
85
+ process.exit(1);
86
+ }
87
+ console.log(success(`✓ Created ${name}`));
88
+ printCopy(res.data.data);
89
+ console.log(`${muted('Live:')} ${brand(res.data.url)}`);
90
+ }));
91
+ envCommand
92
+ .command('reset <name>')
93
+ .description('Start an environment over: drop its database, rerun every migration from zero, redeploy')
94
+ .option('--data', 'Then copy the rows of prod (or --from) into it')
95
+ .option('--from <env>', 'With --data: the environment to copy from (default prod)')
96
+ .option('--json', 'Output as JSON')
97
+ .action((name, opts) => run('Env', async () => {
98
+ if (name === PROD_ENV) {
99
+ console.error(clrError('prod can\'t be reset.'));
100
+ process.exit(1);
101
+ }
102
+ if (opts.from && !opts.data) {
103
+ console.error(clrError('--from goes with --data'));
104
+ process.exit(1);
105
+ }
106
+ const ok = await confirm(`Reset ${bold(name)}? Its database is dropped and rebuilt${opts.data ? ` from ${opts.from ?? 'prod'}'s data` : ' empty'}.`, { default: 'no' });
107
+ if (!ok) {
108
+ console.log(muted('Aborted.'));
109
+ process.exit(1);
110
+ }
111
+ const reset = () => post(`/projects/${appGuid()}/envs/${encodeURIComponent(name)}/reset`, { ...(opts.data ? { data: true } : {}), ...(opts.from ? { from: opts.from } : {}) });
112
+ const res = opts.json ? await reset() : await withSpinner(`Resetting ${name}...`, reset, { done: null });
113
+ if (opts.json) {
114
+ console.log(JSON.stringify(res.data));
115
+ return;
116
+ }
117
+ const failed = res.data.phases.filter((p) => p.status === 'failed');
118
+ for (const p of failed)
119
+ console.log(`${clrError('✗')} ${bold(p.name)}: ${p.summary}`);
120
+ if (failed.length > 0) {
121
+ console.log(clrError(`Reset ${name}, but its deploy failed.`));
122
+ process.exit(1);
123
+ }
124
+ console.log(success(`✓ Reset ${name}`));
125
+ printCopy(res.data.data);
126
+ if (res.data.url)
127
+ console.log(`${muted('Live:')} ${brand(res.data.url)}`);
128
+ }));
129
+ envCommand
130
+ .command('set <name>')
131
+ .description('Change an environment\'s settings')
132
+ .requiredOption('--schedules <on|off>', 'Turn the environment\'s cron workflows on or off')
133
+ .option('--json', 'Output as JSON')
134
+ .action((name, opts) => run('Env', async () => {
135
+ const value = String(opts.schedules).toLowerCase();
136
+ if (value !== 'on' && value !== 'off') {
137
+ console.error(clrError('--schedules takes on or off'));
138
+ process.exit(1);
139
+ }
140
+ const res = await patch(`/projects/${appGuid()}/envs/${encodeURIComponent(name)}`, { schedules: value === 'on' });
141
+ if (opts.json) {
142
+ console.log(JSON.stringify(res.data));
143
+ return;
144
+ }
145
+ console.log(success(`✓ Schedules ${value} in ${name}`));
146
+ }));
147
+ envCommand
148
+ .command('delete <name>')
149
+ .description('Delete an environment: its database, functions, files and custom domains (never prod)')
150
+ .option('--json', 'Output as JSON')
151
+ .action((name, opts) => run('Env', async () => {
152
+ if (name === PROD_ENV) {
153
+ console.error(clrError('prod is the app itself and can\'t be deleted as an environment.'));
154
+ process.exit(1);
155
+ }
156
+ const ok = await confirm(`Delete the ${bold(name)} environment and its database?`, { default: 'no' });
157
+ if (!ok) {
158
+ console.log(muted('Aborted.'));
159
+ process.exit(1);
160
+ }
161
+ const res = await del(`/projects/${appGuid()}/envs/${encodeURIComponent(name)}`);
162
+ if (opts.json) {
163
+ console.log(JSON.stringify(res.data));
164
+ return;
165
+ }
166
+ console.log(success(`✓ Deleted ${name}`));
167
+ }));
168
+ //# sourceMappingURL=env.js.map
@@ -21,7 +21,7 @@ fnCommand
21
21
  // The callable address is the deliverable for API-only apps - name it here
22
22
  // rather than leaving it to be inferred from a template comment.
23
23
  if (!opts.json && res.data.length > 0) {
24
- console.log(muted(`Endpoint: POST ${resolveApiBase()}/api/${config.projectGuid}/fn/<name> (same on dev and prod; public path: gipity fn call <name> --anon)`));
24
+ console.log(muted(`Endpoint: POST ${resolveApiBase()}/api/${config.projectGuid}/fn/<name> (this is ${config.env ? `the ${config.env.name} environment` : 'prod'}; each environment has its own address, see --env; public path: gipity fn call <name> --anon)`));
25
25
  }
26
26
  }));
27
27
  fnCommand
@@ -206,6 +206,6 @@ export const loadCommand = new Command('load')
206
206
  console.warn(warning('The project was still created and linked; the files above are missing from it.'));
207
207
  }
208
208
  console.log('');
209
- console.log(`${muted('Next:')} cd ${dir} && ${brand('gipity deploy dev')}`);
209
+ console.log(`${muted('Next:')} cd ${dir} && ${brand('gipity deploy')}`);
210
210
  }));
211
211
  //# sourceMappingURL=load.js.map
@@ -3,10 +3,11 @@ import { get, post, publicRequest, mintAppToken, ApiError, LONG_REQUEST_TIMEOUT_
3
3
  import { getAuth } from '../auth.js';
4
4
  import { requireConfig } from '../config.js';
5
5
  import { bold, muted } from '../colors.js';
6
- import { run, emitField, resolveBody } from '../helpers/index.js';
6
+ import { run, emitField, resolveBody, resolveFormBody } from '../helpers/index.js';
7
7
  /** Known app-service endpoints, shown by `gipity service list` and used to
8
- * give a helpful hint on typos. POST endpoints take a JSON body; GET
9
- * endpoints (model/voice listings) are reached with `--get`. */
8
+ * give a helpful hint on typos. POST endpoints take a JSON body, except
9
+ * transcribe, which takes a multipart upload via --form. GET endpoints
10
+ * (model/voice listings) are reached with `--get`. */
10
11
  const SERVICES = [
11
12
  { name: 'llm', method: 'POST', desc: 'Chat completion ({ prompt | messages, model?, ... })' },
12
13
  { name: 'llm/models', method: 'GET', desc: 'List available LLM models' },
@@ -18,6 +19,7 @@ const SERVICES = [
18
19
  { name: 'music', method: 'POST', desc: 'Music generation ({ prompt, duration_seconds? })' },
19
20
  { name: 'music/models', method: 'GET', desc: 'List music models (ids for --model / model)' },
20
21
  { name: 'video', method: 'POST', desc: 'Video generation ({ prompt, ... })' },
22
+ { name: 'transcribe', method: 'POST', desc: 'Speech-to-text, multipart (--form audio=@talk.mp3 [--form language=en] [--form diarize=true])' },
21
23
  { name: 'location/ip', method: 'POST', desc: 'IP geolocation ({ ip? })' },
22
24
  { name: 'location/geocode', method: 'POST', desc: 'Reverse geocode ({ lat, lon })' },
23
25
  ];
@@ -62,13 +64,14 @@ export function anonBillingHint(name, err) {
62
64
  `visitor to a public page is asked to sign in and pay from their own credits. If this app serves the ` +
63
65
  `public (a help bubble, a landing page), switch it to owner-pays in gipity.yaml and redeploy:\n` +
64
66
  ` deploy:\n phases:\n - services\n service_definitions:\n - service: ${service}\n billing_mode: owner_pays\n` +
65
- ` gipity deploy dev --only services`);
67
+ ` gipity deploy --only services`);
66
68
  }
67
69
  serviceCommand
68
70
  .command('call <name> [body]')
69
71
  .description('Call an app service by name (e.g. llm, image, music). Uses your logged-in session - no token wrangling; --anon calls it as a signed-out visitor instead.')
70
72
  .option('-d, --data <json>', 'JSON request body: inline JSON, @file to read a file, or @- / - for stdin (alternative to the positional [body])')
71
- .option('--file <field=@path>', 'Attach a file as { data, media_type } under <field> (the vision/media shape these services expect), repeatable, e.g. --file image=@receipt.png', (v, acc) => (acc || []).concat(v))
73
+ .option('--file <field=@path>', 'Attach a file as { data, media_type } under <field> in the JSON body (the shape image/vision services expect), repeatable, e.g. --file image=@receipt.png', (v, acc) => (acc || []).concat(v))
74
+ .option('--form <field=value>', 'Send multipart/form-data instead of JSON, curl -F style: field=@path attaches a file, field=value a text field. Repeatable. For upload endpoints like transcribe: --form audio=@talk.mp3 --form language=en', (v, acc) => (acc || []).concat(v))
72
75
  .option('--anon', 'Call as an anonymous visitor (the public path a signed-out user of your deployed app hits) instead of as your signed-in account')
73
76
  .option('--get', 'Issue a GET (for listing endpoints like llm/models, tts/voices)')
74
77
  .option('--field <path>', 'Print only this field of the result (dot path, e.g. choices.0.message.content)')
@@ -82,7 +85,10 @@ serviceCommand
82
85
  const [pathPart, query] = name.split('?', 2);
83
86
  const path = pathPart.split('/').map(encodeURIComponent).join('/');
84
87
  const url = `/api/${config.projectGuid}/services/${path}${query ? `?${query}` : ''}`;
85
- const body = resolveBody(bodyArg || opts.data, opts.file);
88
+ if (opts.form && (bodyArg || opts.data || opts.file || opts.get)) {
89
+ throw new Error('--form sends a multipart body, so it cannot be combined with a JSON body, --data, --file, or --get.');
90
+ }
91
+ const body = opts.form ? resolveFormBody(opts.form) : resolveBody(bodyArg || opts.data, opts.file);
86
92
  // Name the calling identity (stderr, so stdout stays parseable). An owner
87
93
  // call always succeeds regardless of billing mode, so without this line a
88
94
  // "the service works" verification silently proves nothing about the
@@ -104,10 +110,10 @@ serviceCommand
104
110
  const headers = await mintAppToken(config.projectGuid);
105
111
  if (!headers) {
106
112
  throw new Error(`Could not mint a visitor token for this project, so there is no anonymous path to call. ` +
107
- `That means the app is not deployed on this API base yet: run \`gipity deploy dev\` first, ` +
113
+ `That means the app is not deployed on this API base yet: run \`gipity deploy\` first, ` +
108
114
  `then re-run this command.`);
109
115
  }
110
- res = await publicRequest(opts.get ? 'GET' : 'POST', url, opts.get ? undefined : body, headers);
116
+ res = await publicRequest(opts.get ? 'GET' : 'POST', url, opts.get ? undefined : body, headers, LONG_REQUEST_TIMEOUT_MS);
111
117
  }
112
118
  else {
113
119
  // Generation services (music, video, image, ...) can hold the request
@@ -91,6 +91,7 @@ export const statusCommand = new Command('status')
91
91
  apiBase: config.apiBase,
92
92
  apiBaseInUse,
93
93
  url: liveUrl(config),
94
+ ...(config.env ? { env: config.env.name } : {}),
94
95
  } : null,
95
96
  // `valid` reflects the refresh token (the real session) - access
96
97
  // tokens auto-renew, so their expiry must not read as "invalid".
@@ -115,6 +116,8 @@ export const statusCommand = new Command('status')
115
116
  else {
116
117
  console.log(`${muted('Project:')} ${brand(config.projectSlug)} ${muted(`(${config.projectGuid})`)}`);
117
118
  console.log(`${muted('Account:')} ${config.accountSlug}`);
119
+ if (config.env)
120
+ console.log(`${muted('Env:')} ${config.env.name}`);
118
121
  console.log(`${muted('Live:')} ${liveUrl(config)}`);
119
122
  console.log(`${muted('API:')} ${config.apiBase}`);
120
123
  // apiBase is only what THIS project recorded - resolveApiBase() is what
@@ -247,15 +247,15 @@ export const testCommand = new Command('test')
247
247
  }
248
248
  console.log('');
249
249
  }
250
- // Tests call functions against the DEPLOYED build, so a function written
251
- // but not yet deployed 404s. That ordering (deploy → test) is invisible in
252
- // a bare 404, so when we see that failure shape, name the fix once.
250
+ // `gipity test` registers the working-tree functions/ before every run,
251
+ // so a 404 from ctx.fn.call means there is no such function file (or it
252
+ // failed to register). Name that once instead of a bare 404 per test.
253
253
  const undeployed = undeployedFunctionsFromFailures(data.results);
254
254
  if (undeployed.length > 0) {
255
255
  const list = undeployed.map((n) => `'${n}'`).join(', ');
256
- console.log(warning(`${undeployed.length === 1 ? 'Function' : 'Functions'} ${list} 404'd: tests call functions against the ` +
257
- `DEPLOYED build, and ${undeployed.length === 1 ? 'this one is' : 'these are'} not deployed yet.`));
258
- console.log(muted('Deploy first, then re-run: gipity deploy dev && gipity test'));
256
+ console.log(warning(`${undeployed.length === 1 ? 'Function' : 'Functions'} ${list} 404'd: \`gipity test\` registers every file in ` +
257
+ `functions/ before the run, so ${undeployed.length === 1 ? 'that name has' : 'those names have'} no function file, or failed to register.`));
258
+ console.log(muted('Check the name against functions/<name>.js (or functions/<name>/index.js) and gipity.yaml.'));
259
259
  console.log('');
260
260
  }
261
261
  // Summary
package/dist/config.js CHANGED
@@ -2,9 +2,31 @@ import { readFileSync, writeFileSync, existsSync } from 'fs';
2
2
  import { dirname, resolve } from 'path';
3
3
  import ignore from 'ignore';
4
4
  const CONFIG_FILE = '.gipity.json';
5
+ /** The app's prod environment name. */
6
+ export const PROD_ENV = 'prod';
5
7
  export const DEFAULT_API_BASE = 'https://a.gipity.ai';
6
8
  let cached = null;
7
9
  let cachedPath = null;
10
+ let envOption;
11
+ /** Record the global `--env <name>` flag (index.ts preAction). */
12
+ export function setEnvOption(name) {
13
+ envOption = name;
14
+ }
15
+ /** The `--env <name>` this invocation was given, if any. */
16
+ export function getEnvOption() {
17
+ return envOption;
18
+ }
19
+ /**
20
+ * Point this invocation's config at an app environment's project, so every
21
+ * project-scoped command (db, fn, logs, secrets, domain, ...) acts on that env.
22
+ * In memory only: saveConfig refuses while it is applied.
23
+ */
24
+ export function applyEnvOverride(env) {
25
+ const base = getConfig();
26
+ if (!base)
27
+ throw new Error('--env needs a Gipity project directory');
28
+ cached = { ...base, projectGuid: env.projectGuid, projectSlug: env.projectSlug, env: { name: env.name, appSlug: base.projectSlug } };
29
+ }
8
30
  /** Global --api-base override (set from root CLI option, takes precedence over config file) */
9
31
  let apiBaseOverride = null;
10
32
  export function setApiBaseOverride(url) {
@@ -182,9 +204,15 @@ export async function resolveProjectContext(opts) {
182
204
  * by hand or guess a subdomain like `<slug>.gipity.app` (which doesn't
183
205
  * resolve). Mirrors the server's deploy URL; `deploy` itself prints the
184
206
  * server-authoritative URL, the read-only commands derive it from config. */
185
- export function liveUrl(config, target = 'dev') {
186
- const host = target === 'prod' ? 'app.gipity.ai' : 'dev.gipity.ai';
187
- return `https://${host}/${config.accountSlug}/${config.projectSlug}/`;
207
+ export function liveUrl(config, env = config.env?.name ?? PROD_ENV) {
208
+ // The app's own slug, even when --env pointed the config at an env project.
209
+ const appSlug = config.env?.appSlug ?? config.projectSlug;
210
+ if (env === PROD_ENV)
211
+ return `https://app.gipity.ai/${config.accountSlug}/${appSlug}/`;
212
+ // Every other env is on the dev host: `dev` at the app's bare slug, the
213
+ // rest at `<slug>--<env>`.
214
+ const segment = env === 'dev' ? appSlug : `${appSlug}--${env}`;
215
+ return `https://dev.gipity.ai/${config.accountSlug}/${segment}/`;
188
216
  }
189
217
  export function clearConfigCache() {
190
218
  cached = null;
@@ -197,6 +225,9 @@ export function saveConfig(data) {
197
225
  // create-on-save here would silently turn that folder - in the wild, often
198
226
  // `$HOME` itself - into a Gipity project. Creating a config is always an
199
227
  // explicit act and must go through `saveConfigAt(dir, …)`.
228
+ if (cached?.env || data.env) {
229
+ throw new Error('Can\'t change the linked project while --env is set: run it without --env.');
230
+ }
200
231
  const path = getConfigPath();
201
232
  if (!path) {
202
233
  throw new Error('saveConfig: no .gipity.json found to update. ' +
@@ -12,6 +12,7 @@
12
12
  * path sidesteps the shell argument entirely.
13
13
  */
14
14
  import { readFileSync } from 'node:fs';
15
+ import { basename } from 'node:path';
15
16
  import { guessMime } from '../upload.js';
16
17
  /** Read all of stdin synchronously (fd 0). Returns '' if stdin is a TTY. */
17
18
  function readStdin() {
@@ -114,4 +115,41 @@ export function resolveJsonBody(raw) {
114
115
  throw new Error(`Invalid JSON in ${origin}: ${e.message}`);
115
116
  }
116
117
  }
118
+ /**
119
+ * Build a multipart/form-data body from repeatable `--form` specs, curl `-F`
120
+ * style: `field=@path` attaches a file (sent with its filename and detected
121
+ * media type), `field=value` sends a text field. This is for endpoints that
122
+ * take a real file upload rather than a JSON body, e.g. the transcribe service
123
+ * (`--form audio=@talk.mp3 --form language=en`). Multipart also carries much
124
+ * larger files than a base64 JSON body can.
125
+ */
126
+ export function resolveFormBody(specs) {
127
+ const form = new FormData();
128
+ for (const spec of specs) {
129
+ const eq = spec.indexOf('=');
130
+ if (eq === -1) {
131
+ throw new Error(`Invalid --form '${spec}': expected field=@path for a file or field=value for text (e.g. --form audio=@talk.mp3).`);
132
+ }
133
+ const field = spec.slice(0, eq).trim();
134
+ const value = spec.slice(eq + 1);
135
+ if (!field)
136
+ throw new Error(`Invalid --form '${spec}': missing field name before '='.`);
137
+ if (!value.startsWith('@')) {
138
+ form.append(field, value);
139
+ continue;
140
+ }
141
+ const path = value.slice(1);
142
+ if (!path)
143
+ throw new Error(`Invalid --form '${spec}': missing file path after '@'.`);
144
+ let data;
145
+ try {
146
+ data = readFileSync(path);
147
+ }
148
+ catch (e) {
149
+ throw new Error(`Cannot read --form '${path}': ${e.message}`);
150
+ }
151
+ form.append(field, new Blob([new Uint8Array(data)], { type: guessMime(path) }), basename(path));
152
+ }
153
+ return form;
154
+ }
117
155
  //# sourceMappingURL=body.js.map
@@ -4,6 +4,6 @@
4
4
  export { run } from './command.js';
5
5
  export { printOutput, printList, printResult, pluckField, emitField } from './output.js';
6
6
  export { syncBeforeAction } from './sync.js';
7
- export { resolveJsonBody, resolveBody } from './body.js';
7
+ export { resolveJsonBody, resolveBody, resolveFormBody } from './body.js';
8
8
  export { parseDuration } from './duration.js';
9
9
  //# sourceMappingURL=index.js.map