@gjsify/cli 0.64.27 → 0.64.29

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.
@@ -112,6 +112,11 @@ export const buildCommand = {
112
112
  description: 'Distribution channel this build is for (ADR 0113): flathub, web, microsoft-store or apple-app-store. Sets the __GJSIFY_CHANNEL__ define that @gjsify/distribution reads; overrides gjsify.ship.channel. Unset builds report no donation UI.',
113
113
  type: 'string',
114
114
  choices: ['flathub', 'web', 'microsoft-store', 'apple-app-store'],
115
+ })
116
+ .option('pricing', {
117
+ description: "Pricing tier this build is for (ADR 0139): 'free' or 'paid'. Sets the __GJSIFY_PRICING__ define that @gjsify/distribution reads; overrides gjsify.ship.pricing. Default 'free'.",
118
+ type: 'string',
119
+ choices: ['free', 'paid'],
115
120
  })
116
121
  .option('dialect', {
117
122
  description: "The dialect the SOURCE is written in. 'react-native' aliases 'react-native' onto '@gjsify/react-native' and fails the build on an import whose ADR 0032 support-table status is not supported/partial. GJS and Node app builds. This is NOT gjsify.runtimes['react-native'], which declares the runtime a package RUNS on — the two answer opposite questions.",
@@ -8,6 +8,7 @@ interface ShipOptions {
8
8
  'expect-target'?: string;
9
9
  'skip-build': boolean;
10
10
  channel?: string;
11
+ pricing?: string;
11
12
  arch?: string;
12
13
  sign?: string;
13
14
  notarize?: string;
@@ -23,6 +23,7 @@
23
23
  // HFS+/APFS volume that no Linux host in this tree can write (§ A1), and a
24
24
  // signature is made where the identity lives (§ A14).
25
25
  import { CHANNELS, CHANNEL_ENV, parseDeclaredChannel } from '../utils/channel.js';
26
+ import { PRICINGS, PRICING_ENV, parseDeclaredPricing } from '../utils/pricing.js';
26
27
  import { mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
27
28
  import { basename, dirname, join, relative, resolve } from 'node:path';
28
29
  import { Config } from '../config.js';
@@ -118,6 +119,12 @@ export const shipCommand = {
118
119
  choices: [...CHANNELS],
119
120
  description: 'Distribution channel (ADR 0113). Overrides gjsify.ship.channel; `--target flatpak` implies flathub. ' +
120
121
  'Passed to the project build, and gates the metainfo donation URL.',
122
+ })
123
+ .option('pricing', {
124
+ type: 'string',
125
+ choices: [...PRICINGS],
126
+ description: "Pricing tier (ADR 0139): 'free' or 'paid'. Overrides gjsify.ship.pricing; passed to the project " +
127
+ "build. Default 'free'.",
121
128
  })
122
129
  .option('skip-build', {
123
130
  type: 'boolean',
@@ -322,8 +329,11 @@ async function assemble(args) {
322
329
  const channel = parseDeclaredChannel(args.channel, '--channel') ??
323
330
  parseDeclaredChannel(ship.channel, 'gjsify.ship.channel') ??
324
331
  (formats.some((format) => format.id === 'flatpak') ? 'flathub' : undefined);
332
+ const pricing = parseDeclaredPricing(args.pricing, '--pricing') ??
333
+ parseDeclaredPricing(ship.pricing, 'gjsify.ship.pricing') ??
334
+ 'free';
325
335
  if (!args['skip-build'])
326
- await runProjectBuild(projectDir, channel);
336
+ await runProjectBuild(projectDir, channel, pricing);
327
337
  // THE OTHER HALF of the resolution above, and they are one decision: the
328
338
  // runtime a target execs and the entry it hands that runtime (#1545). Two
329
339
  // keys, resolved by two twin functions, compared by `assertEntryRunsUnder`
@@ -1613,18 +1623,25 @@ function assertFormatCanRunInterpreter(format, app) {
1613
1623
  * `completion: 'return'` because this handler returns afterwards; on GJS that
1614
1624
  * selects the blocking path rather than arming a main loop only an exit quits.
1615
1625
  */
1616
- async function runProjectBuild(projectDir, channel) {
1626
+ async function runProjectBuild(projectDir, channel, pricing) {
1617
1627
  const pkg = readPackageJson(join(projectDir, 'package.json'));
1618
1628
  if (typeof pkg?.scripts?.build !== 'string') {
1619
1629
  throw new Error('gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to ' +
1620
1630
  'package what is already built.');
1621
1631
  }
1622
1632
  console.log(`${LOG} running the project's build script`);
1633
+ const env = pricing === undefined && channel === undefined ? undefined : { ...process.env };
1634
+ if (env !== undefined) {
1635
+ if (channel !== undefined)
1636
+ env[CHANNEL_ENV] = channel;
1637
+ if (pricing !== undefined)
1638
+ env[PRICING_ENV] = pricing;
1639
+ }
1623
1640
  const result = await spawnToCompletion('gjsify', ['run', 'build'], {
1624
1641
  completion: 'return',
1625
1642
  cwd: projectDir,
1626
1643
  stdio: 'inherit',
1627
- env: channel === undefined ? undefined : { ...process.env, [CHANNEL_ENV]: channel },
1644
+ env,
1628
1645
  notFound: () => new Error('gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project ' +
1629
1646
  'yourself and pass --skip-build.'),
1630
1647
  });
package/lib/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { APP_NAME } from './constants.js';
2
2
  import { CHANNEL_ENV, parseDeclaredChannel } from './utils/channel.js';
3
+ import { PRICING_ENV, parseDeclaredPricing } from './utils/pricing.js';
3
4
  import { cosmiconfig } from 'cosmiconfig';
4
5
  import { basename, dirname } from 'node:path';
5
6
  import { pathToFileURL } from 'node:url';
@@ -379,6 +380,11 @@ export class Config {
379
380
  if (channel !== undefined && defineMap.__GJSIFY_CHANNEL__ === undefined) {
380
381
  defineMap.__GJSIFY_CHANNEL__ = JSON.stringify(channel);
381
382
  }
383
+ // flag > env (set by `gjsify ship` for the project's own build) > `gjsify.ship.pricing` > 'free'.
384
+ const pricing = parseDeclaredPricing(cliArgs.pricing ?? process.env[PRICING_ENV] ?? configData.ship?.pricing, cliArgs.pricing !== undefined ? '--pricing' : 'gjsify.ship.pricing');
385
+ if (defineMap.__GJSIFY_PRICING__ === undefined) {
386
+ defineMap.__GJSIFY_PRICING__ = JSON.stringify(pricing ?? 'free');
387
+ }
382
388
  const aliasMap = parseKvPairs(cliArgs.alias ?? [], 'alias');
383
389
  if (Object.keys(aliasMap).length) {
384
390
  configData.aliases = { ...configData.aliases, ...aliasMap };
@@ -213,23 +213,60 @@ function sleepMs(ms) {
213
213
  });
214
214
  }
215
215
 
216
- async function fetchOnce(session, url, { forceHttp1 = false } = {}) {
217
- const message = Soup.Message.new('GET', url);
218
- message.request_headers.append('User-Agent', USER_AGENT);
219
- // The failure this retries against announces its own protocol — libsoup reports it
220
- // verbatim as `HTTP/2 Error: NO_ERROR`, a stream closed mid-response. Retrying over
221
- // HTTP/1.1 sidesteps the multiplexing that produces it, so the first attempt keeps the
222
- // faster protocol and every retry drops to the one that cannot fail that way. Guarded:
223
- // `set_force_http1` is libsoup 3.4+, and this script must still run on older hosts.
224
- if (forceHttp1 && typeof message.set_force_http1 === 'function') message.set_force_http1(true);
225
- const bytes = await session.send_and_read_async(message, GLib.PRIORITY_DEFAULT, null);
226
- const status = message.get_status();
227
- if (status !== Soup.Status.OK) {
228
- const err = new Error(`HTTP ${status} from ${url}`);
229
- err.httpStatus = status;
230
- throw err;
216
+ /**
217
+ * Hosts that may receive the GitHub token. Release downloads redirect to
218
+ * objects.githubusercontent.com / release-assets.githubusercontent.com, which are
219
+ * deliberately NOT here. The env override exists so the e2e test can aim it at a mock.
220
+ */
221
+ const AUTH_HOSTS = (GLib.getenv('GJSIFY_INSTALL_AUTH_HOSTS') || 'github.com,api.github.com').split(',');
222
+ const MAX_REDIRECTS = 5;
223
+
224
+ /**
225
+ * The `Authorization` value for `url`, or null. An authenticated request escapes the
226
+ * unauthenticated rate/timeout tier GitHub sheds first during an incident, but the token
227
+ * must reach github.com and api.github.com ONLY, over https.
228
+ */
229
+ function authorizationFor(url, token = GLib.getenv('GITHUB_TOKEN') || GLib.getenv('GH_TOKEN')) {
230
+ if (!token) return null;
231
+ const uri = GLib.Uri.parse(url, GLib.UriFlags.NONE);
232
+ const secure = uri.get_scheme() === 'https' || GLib.getenv('GJSIFY_INSTALL_AUTH_HOSTS');
233
+ if (!secure || !AUTH_HOSTS.includes(uri.get_host())) return null;
234
+ return `Bearer ${token}`;
235
+ }
236
+
237
+ async function fetchOnce(session, startUrl, { forceHttp1 = false } = {}) {
238
+ // Redirects are followed by hand: libsoup would replay our headers on every hop, and a
239
+ // redirect to another host must not carry the token. The header is recomputed per hop.
240
+ let url = startUrl;
241
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
242
+ const message = Soup.Message.new('GET', url);
243
+ message.set_flags(Soup.MessageFlags.NO_REDIRECT);
244
+ message.request_headers.append('User-Agent', USER_AGENT);
245
+ const auth = authorizationFor(url);
246
+ if (auth) message.request_headers.append('Authorization', auth);
247
+ // The failure this retries against announces its own protocol — libsoup reports it
248
+ // verbatim as `HTTP/2 Error: NO_ERROR`, a stream closed mid-response. Retrying over
249
+ // HTTP/1.1 sidesteps the multiplexing that produces it, so the first attempt keeps the
250
+ // faster protocol and every retry drops to the one that cannot fail that way. Guarded:
251
+ // `set_force_http1` is libsoup 3.4+, and this script must still run on older hosts.
252
+ if (forceHttp1 && typeof message.set_force_http1 === 'function') message.set_force_http1(true);
253
+ const bytes = await session.send_and_read_async(message, GLib.PRIORITY_DEFAULT, null);
254
+ const status = message.get_status();
255
+ if ([301, 302, 303, 307, 308].includes(status)) {
256
+ const location = message.get_response_headers().get_one('Location');
257
+ if (!location)
258
+ throw Object.assign(new Error(`HTTP ${status} without Location from ${url}`), { httpStatus: status });
259
+ url = GLib.Uri.parse(url, GLib.UriFlags.NONE).parse_relative(location, GLib.UriFlags.NONE).to_string();
260
+ continue;
261
+ }
262
+ if (status !== Soup.Status.OK) {
263
+ const err = new Error(`HTTP ${status} from ${url}`);
264
+ err.httpStatus = status;
265
+ throw err;
266
+ }
267
+ return bytes.get_data();
231
268
  }
232
- return bytes.get_data();
269
+ throw new Error(`Too many redirects from ${startUrl}`);
233
270
  }
234
271
 
235
272
  /**
@@ -38,6 +38,8 @@ export interface CliBuildOptions {
38
38
  dialect?: string;
39
39
  /** Distribution channel (ADR 0113), becomes the `__GJSIFY_CHANNEL__` define. */
40
40
  channel?: string;
41
+ /** Pricing tier (ADR 0139), becomes the `__GJSIFY_PRICING__` define. Default `free`. */
42
+ pricing?: string;
41
43
  /**
42
44
  * Resolve `gi://Ns?version=X` to the target's widget renderer instead of an empty
43
45
  * module — `--gi-renderer` (ADR 0034 stage 9). `browser` and `nativescript` targets.
@@ -516,6 +516,12 @@ export interface ConfigDataShip extends AppMetadata {
516
516
  * `flathub` when nothing states one. Unset means no donation UI.
517
517
  */
518
518
  channel?: string;
519
+ /**
520
+ * Pricing tier (ADR 0139): `free` or `paid`. Becomes the `__GJSIFY_PRICING__` define that
521
+ * `@gjsify/distribution` reads. `--pricing` overrides it; the default is `'free'`, so a plain
522
+ * build drops the paid-listing badge at bundle time.
523
+ */
524
+ pricing?: string;
519
525
  /** Reverse-DNS app id. Falls back to `gjsify.flatpak.appId`, then `package.json#name`. */
520
526
  appId?: string;
521
527
  /**
@@ -10,7 +10,7 @@ export interface AppMetadataInputs {
10
10
  /** `'app'` renders a desktop-application component, `'cli'` a console one. */
11
11
  kind: 'app' | 'cli';
12
12
  metadata: AppMetadata;
13
- /** Distribution channel (ADR 0113). `<url type="donation">` is emitted only where it allows donations. */
13
+ /** Distribution channel (ADR 0113, 0139). `<url type="donation">` is emitted only where `support` is `external-link`. */
14
14
  channel?: string;
15
15
  /**
16
16
  * Config path the validator names in its hints, e.g. `gjsify.flatpak` or
@@ -4,5 +4,5 @@ export type DeclaredChannel = (typeof CHANNELS)[number];
4
4
  export declare const CHANNEL_ENV = "GJSIFY_CHANNEL";
5
5
  /** The channel `value` names, or a refusal that lists the alternatives. `undefined` stays unset. */
6
6
  export declare function parseDeclaredChannel(value: unknown, source: string): DeclaredChannel | undefined;
7
- /** Unset (an `unknown` build) permits no donation UI, as the ADR's quiet default. */
7
+ /** Unset (an `unknown` build) permits no donation URL, as the ADR's quiet default. */
8
8
  export declare function channelAllowsDonations(channel: string | undefined): boolean;
@@ -1,12 +1,12 @@
1
- // The distribution channel (ADR 0113), as the CLI needs it: validate a value, and ask whether
2
- // it permits donation UI. Mirrors `@gjsify/distribution`'s table on purpose and does not import
3
- // it: the CLI would then depend on a package it must be able to build and publish first.
1
+ // The distribution channel (ADR 0113, 0139), as the CLI needs it: validate a value, and ask whether
2
+ // it permits an external support link. Mirrors `@gjsify/distribution`'s table on purpose and does not
3
+ // import it: the CLI would then depend on a package it must be able to build and publish first.
4
4
  export const CHANNELS = ['flathub', 'web', 'microsoft-store', 'apple-app-store'];
5
- const DONATIONS = {
6
- flathub: true,
7
- web: true,
8
- 'microsoft-store': false,
9
- 'apple-app-store': false,
5
+ const SUPPORT_PATH = {
6
+ flathub: 'external-link',
7
+ web: 'external-link',
8
+ 'microsoft-store': 'none',
9
+ 'apple-app-store': 'store-purchase',
10
10
  };
11
11
  /** Env var `gjsify ship` hands to the project's own build, which has no `--channel` to pass. */
12
12
  export const CHANNEL_ENV = 'GJSIFY_CHANNEL';
@@ -18,7 +18,7 @@ export function parseDeclaredChannel(value, source) {
18
18
  return value;
19
19
  throw new Error(`${source}: "${String(value)}" is not a distribution channel. Known: ${CHANNELS.join(', ')}.`);
20
20
  }
21
- /** Unset (an `unknown` build) permits no donation UI, as the ADR's quiet default. */
21
+ /** Unset (an `unknown` build) permits no donation URL, as the ADR's quiet default. */
22
22
  export function channelAllowsDonations(channel) {
23
- return channel !== undefined && DONATIONS[channel] === true;
23
+ return channel !== undefined && SUPPORT_PATH[channel] === 'external-link';
24
24
  }
@@ -1,3 +1,4 @@
1
+ import { type TransientRetryOptions } from './transient-retry.js';
1
2
  interface OidcExchangeOptions {
2
3
  /** Full package name including scope, e.g. `@gjsify/cli`. */
3
4
  packageName: string;
@@ -6,16 +7,21 @@ interface OidcExchangeOptions {
6
7
  /** Optional verbose logger — receives single-line strings. */
7
8
  log?: (msg: string) => void;
8
9
  /**
9
- * Max retries on a TRANSIENT exchange failure (5xx / 429 / network error), default 3. A
10
- * single npm-side 503 mid-release used to fall straight through to token auth, which in
11
- * OIDC-only CI has no token → a 404 that broke the release while the workflow stayed green
12
- * (hit on `@gjsify/process` during v0.7.3). Retrying keeps the publish on the OIDC path.
13
- * Non-transient statuses (404 "package not found", 401/403 misconfig) are NOT retried, so
14
- * `--tolerate-untrusted-new` and the misconfig hints still fire on the first response.
10
+ * Max retries on a TRANSIENT failure (5xx / 429 / network error) of EITHER request — the GitHub
11
+ * id_token GET and the npm exchange POST — default 5 (six attempts, ~60 s of patience). A single
12
+ * 503 mid-release used to fall straight through to token auth, which in OIDC-only CI has no
13
+ * token → a 404 that broke the release while the workflow stayed green (v0.7.3,
14
+ * `@gjsify/process`); a GitHub-side 503 on the id_token GET killed three packages of the
15
+ * v0.64.27 train. Non-transient statuses (404 "package not found", 401/403 misconfig) are NOT
16
+ * retried, so `--tolerate-untrusted-new` and the misconfig hints still fire on the first response.
15
17
  */
16
18
  maxRetries?: number;
17
- /** Base backoff in ms for transient retries; doubles each attempt (capped 30s, `Retry-After` honored). Default 1000. Tests pass 0. */
19
+ /** Base backoff in ms, doubling per attempt with jitter (capped, `Retry-After` honored). Default 2000. Tests pass 0. */
18
20
  retryBaseMs?: number;
21
+ /** Injected for tests; defaults to real timers. */
22
+ sleep?: TransientRetryOptions['sleep'];
23
+ /** Injected for tests; defaults to `Math.random`. */
24
+ random?: TransientRetryOptions['random'];
19
25
  }
20
26
  export interface OidcExchangeResult {
21
27
  /** Short-lived npm token (`Authorization: Bearer <token>`-compatible). */
@@ -66,7 +72,7 @@ export declare function hasGithubOidcEnv(): boolean;
66
72
  * Request a GitHub Actions OIDC ID token for `audience`. Throws `OidcUnavailableError` when the
67
73
  * env vars are missing (the caller can fall back to token auth) or GitHub rejects the request.
68
74
  */
69
- export declare function fetchGithubOidcToken(audience: string, log?: (msg: string) => void): Promise<string>;
75
+ export declare function fetchGithubOidcToken(audience: string, log?: (msg: string) => void, retry?: Pick<OidcExchangeOptions, 'maxRetries' | 'retryBaseMs' | 'sleep' | 'random'>): Promise<string>;
70
76
  /**
71
77
  * Exchange a GitHub OIDC JWT for a short-lived npm publish token. A missing or non-matching
72
78
  * Trusted Publisher config comes back as a 4xx with a descriptive body, propagated as
@@ -13,8 +13,13 @@
13
13
  //
14
14
  // Reference: refs/npm-cli/lib/utils/oidc.js
15
15
  // Original: Copyright (c) npm contributors. Artistic-2.0.
16
- import { isTransientStatus, retryDelayMs } from './transient-retry.js';
17
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
16
+ import { DEFAULT_TRANSIENT_BASE_MS, DEFAULT_TRANSIENT_RETRIES, fetchWithTransientRetry, } from './transient-retry.js';
17
+ const retryOptions = (o) => ({
18
+ retries: o.maxRetries ?? DEFAULT_TRANSIENT_RETRIES,
19
+ baseMs: o.retryBaseMs ?? DEFAULT_TRANSIENT_BASE_MS,
20
+ sleep: o.sleep,
21
+ random: o.random,
22
+ });
18
23
  export class OidcUnavailableError extends Error {
19
24
  reason;
20
25
  constructor(message, reason) {
@@ -79,7 +84,7 @@ export function hasGithubOidcEnv() {
79
84
  * Request a GitHub Actions OIDC ID token for `audience`. Throws `OidcUnavailableError` when the
80
85
  * env vars are missing (the caller can fall back to token auth) or GitHub rejects the request.
81
86
  */
82
- export async function fetchGithubOidcToken(audience, log) {
87
+ export async function fetchGithubOidcToken(audience, log, retry = {}) {
83
88
  const url = process.env.ACTIONS_ID_TOKEN_REQUEST_URL;
84
89
  const bearer = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
85
90
  if (!url || !bearer) {
@@ -97,13 +102,19 @@ export async function fetchGithubOidcToken(audience, log) {
97
102
  const sep = url.includes('?') ? '&' : '?';
98
103
  const requestUrl = `${url}${sep}audience=${encodeURIComponent(audience)}`;
99
104
  log?.(`gjsify oidc: GET ${requestUrl.replace(bearer, '<bearer>')}`);
100
- const res = await fetch(requestUrl, {
101
- method: 'GET',
102
- headers: {
103
- Accept: 'application/json',
104
- Authorization: `Bearer ${bearer}`,
105
- },
106
- });
105
+ let res;
106
+ try {
107
+ ({ response: res } = await fetchWithTransientRetry(() => fetch(requestUrl, {
108
+ method: 'GET',
109
+ headers: {
110
+ Accept: 'application/json',
111
+ Authorization: `Bearer ${bearer}`,
112
+ },
113
+ }), { ...retryOptions(retry), log: log && ((m) => log(`gjsify oidc: id_token ${m}`)) }));
114
+ }
115
+ catch (netErr) {
116
+ throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: network error — ${netErr instanceof Error ? netErr.message : String(netErr)}`, 'fetch-id-token');
117
+ }
107
118
  if (!res.ok) {
108
119
  const text = await res.text().catch(() => '<no body>');
109
120
  throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`, 'fetch-id-token');
@@ -133,61 +144,46 @@ export async function exchangeOidcForNpmToken(args) {
133
144
  : encodeURIComponent(packageName);
134
145
  const exchangeUrl = `${registryClean}/-/npm/v1/oidc/token/exchange/package/${escapedName}`;
135
146
  log?.(`gjsify oidc: POST ${exchangeUrl}`);
136
- const maxRetries = args.maxRetries ?? 3;
137
- const retryBaseMs = args.retryBaseMs ?? 1000;
138
- for (let attempt = 0;; attempt++) {
139
- let res;
140
- try {
141
- res = await fetch(exchangeUrl, {
142
- method: 'POST',
143
- headers: {
144
- Authorization: `Bearer ${idToken}`,
145
- 'Content-Type': 'application/json',
146
- Accept: 'application/json',
147
- },
148
- // Empty JSON body: the JWT is the proof, no additional claims are needed.
149
- body: '{}',
150
- });
151
- }
152
- catch (netErr) {
153
- // Network-level failure (DNS, connection reset, TLS): transient.
154
- if (attempt < maxRetries) {
155
- const delay = retryDelayMs(attempt, retryBaseMs);
156
- log?.(`gjsify oidc: network error for ${packageName} (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms`);
157
- await sleep(delay);
158
- continue;
159
- }
160
- throw new OidcExchangeError(`npm OIDC token exchange network error for ${packageName} after ${attempt + 1} attempt(s): ${netErr instanceof Error ? netErr.message : String(netErr)}`, 0, '', packageName, decodeJwtPayload(idToken) ?? undefined);
161
- }
162
- const text = await res.text().catch(() => '');
163
- if (!res.ok) {
164
- // Only TRANSIENT npm-side failures retry — see `maxRetries`.
165
- if (isTransientStatus(res.status) && attempt < maxRetries) {
166
- // `Retry-After` wins over the backoff when npm sends one (429/503 during an incident).
167
- const delay = retryDelayMs(attempt, retryBaseMs, res.headers.get('retry-after'));
168
- log?.(`gjsify oidc: transient ${res.status} ${res.statusText} for ${packageName} (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms`);
169
- await sleep(delay);
170
- continue;
171
- }
172
- throw new OidcExchangeError(`npm OIDC token exchange failed for ${packageName}: ${res.status} ${res.statusText} — ${text.slice(0, 300)}`, res.status, text, packageName, decodeJwtPayload(idToken) ?? undefined);
173
- }
174
- let json;
175
- try {
176
- json = JSON.parse(text);
177
- }
178
- catch {
179
- throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${packageName}: ${text.slice(0, 200)}`, res.status, text, packageName);
180
- }
181
- if (!json.token) {
182
- throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${packageName}`, res.status, text, packageName);
183
- }
184
- return json.token;
147
+ let res;
148
+ let retried;
149
+ try {
150
+ ({ response: res, retried } = await fetchWithTransientRetry(() => fetch(exchangeUrl, {
151
+ method: 'POST',
152
+ headers: {
153
+ Authorization: `Bearer ${idToken}`,
154
+ 'Content-Type': 'application/json',
155
+ Accept: 'application/json',
156
+ },
157
+ // Empty JSON body: the JWT is the proof, no additional claims are needed.
158
+ body: '{}',
159
+ }), { ...retryOptions(args), log: log && ((m) => log(`gjsify oidc: ${m} for ${packageName}`)) }));
160
+ }
161
+ catch (netErr) {
162
+ // Network-level failure (DNS, connection reset, TLS) that outlived the retry budget.
163
+ throw new OidcExchangeError(`npm OIDC token exchange network error for ${packageName}: ${netErr instanceof Error ? netErr.message : String(netErr)}`, 0, '', packageName, decodeJwtPayload(idToken) ?? undefined);
164
+ }
165
+ const text = await res.text().catch(() => '');
166
+ if (!res.ok) {
167
+ // Only transient statuses were retried (404 "package not found" and 401/403 misconfig
168
+ // surface on the first response, so `--tolerate-untrusted-new` and the hints still fire).
169
+ throw new OidcExchangeError(`npm OIDC token exchange failed for ${packageName}: ${res.status} ${res.statusText} — ${text.slice(0, 300)}${retried ? ` (after ${retried} retries)` : ''}`, res.status, text, packageName, decodeJwtPayload(idToken) ?? undefined);
170
+ }
171
+ let json;
172
+ try {
173
+ json = JSON.parse(text);
174
+ }
175
+ catch {
176
+ throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${packageName}: ${text.slice(0, 200)}`, res.status, text, packageName);
177
+ }
178
+ if (!json.token) {
179
+ throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${packageName}`, res.status, text, packageName, decodeJwtPayload(idToken) ?? undefined);
185
180
  }
181
+ return json.token;
186
182
  }
187
183
  /** End-to-end: probe env → fetch id-token → exchange for an npm token. */
188
184
  export async function getNpmTrustedToken(opts) {
189
185
  const audience = `npm:${new URL(opts.registry).hostname}`;
190
- const idToken = await fetchGithubOidcToken(audience, opts.log);
186
+ const idToken = await fetchGithubOidcToken(audience, opts.log, opts);
191
187
  const token = await exchangeOidcForNpmToken({ ...opts, idToken });
192
188
  return { token, audience };
193
189
  }
@@ -0,0 +1,6 @@
1
+ export declare const PRICINGS: readonly ["free", "paid"];
2
+ export type DeclaredPricing = (typeof PRICINGS)[number];
3
+ /** Env var `gjsify ship` hands to the project's own build, which has no `--pricing` to pass. */
4
+ export declare const PRICING_ENV = "GJSIFY_PRICING";
5
+ /** The pricing `value` names, or a refusal that lists the alternatives. `undefined` stays unset. */
6
+ export declare function parseDeclaredPricing(value: unknown, source: string): DeclaredPricing | undefined;
@@ -0,0 +1,14 @@
1
+ // The pricing tier (ADR 0139), as the CLI needs it: validate a value. Mirrors
2
+ // `@gjsify/distribution`'s pricing() function on purpose and does not import it:
3
+ // the CLI would then depend on a package it must be able to build and publish first.
4
+ export const PRICINGS = ['free', 'paid'];
5
+ /** Env var `gjsify ship` hands to the project's own build, which has no `--pricing` to pass. */
6
+ export const PRICING_ENV = 'GJSIFY_PRICING';
7
+ /** The pricing `value` names, or a refusal that lists the alternatives. `undefined` stays unset. */
8
+ export function parseDeclaredPricing(value, source) {
9
+ if (value === undefined || value === '')
10
+ return undefined;
11
+ if (PRICINGS.includes(value))
12
+ return value;
13
+ throw new Error(`${source}: "${String(value)}" is not a pricing tier. Known: ${PRICINGS.join(', ')}.`);
14
+ }
@@ -16,6 +16,8 @@ export interface TransientRetryOptions {
16
16
  /** Base backoff in ms, doubling per attempt. Default {@link DEFAULT_TRANSIENT_BASE_MS}. Tests pass 0. */
17
17
  baseMs?: number;
18
18
  sleep?: (ms: number) => Promise<void>;
19
+ /** [0,1) source for the backoff jitter. Default `Math.random`; tests pass a constant. */
20
+ random?: () => number;
19
21
  log?: (msg: string) => void;
20
22
  }
21
23
  /**
@@ -46,6 +46,7 @@ export async function fetchWithTransientRetry(doFetch, opts = {}) {
46
46
  const retries = opts.retries ?? DEFAULT_TRANSIENT_RETRIES;
47
47
  const baseMs = opts.baseMs ?? DEFAULT_TRANSIENT_BASE_MS;
48
48
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
49
+ const random = opts.random ?? Math.random;
49
50
  for (let attempt = 0;; attempt++) {
50
51
  let response;
51
52
  let failure;
@@ -62,7 +63,12 @@ export async function fetchWithTransientRetry(doFetch, opts = {}) {
62
63
  return { response, retried: attempt };
63
64
  throw failure;
64
65
  }
65
- const delay = retryDelayMs(attempt, baseMs, response?.headers.get('retry-after'));
66
+ const retryAfter = response?.headers.get('retry-after');
67
+ const backoff = retryDelayMs(attempt, baseMs, retryAfter);
68
+ // Equal jitter (50-100%) on the computed backoff so the ~230 per-package exchanges of a
69
+ // sweep do not retry in lockstep against the same recovering endpoint. An explicit
70
+ // `Retry-After` is the server's number and stays exact.
71
+ const delay = parseRetryAfter(retryAfter) === undefined ? Math.round(backoff * (0.5 + 0.5 * random())) : backoff;
66
72
  const what = response
67
73
  ? `${response.status} ${response.statusText}`
68
74
  : `network error: ${failure instanceof Error ? failure.message : String(failure)}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjsify/cli",
3
- "version": "0.64.27",
3
+ "version": "0.64.29",
4
4
  "description": "CLI for Gjsify",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -142,22 +142,22 @@
142
142
  "cli"
143
143
  ],
144
144
  "dependencies": {
145
- "@gjsify/blueprint": "^0.64.27",
146
- "@gjsify/buffer": "^0.64.27",
147
- "@gjsify/create-app": "^0.64.27",
148
- "@gjsify/node-globals": "^0.64.27",
149
- "@gjsify/node-polyfills": "^0.64.27",
150
- "@gjsify/npm-registry": "^0.64.27",
151
- "@gjsify/resolve-npm": "^0.64.27",
152
- "@gjsify/rolldown-plugin-gjsify": "^0.64.27",
153
- "@gjsify/vite-plugin-blueprint": "^0.64.27",
154
- "@gjsify/rolldown-plugin-pnp": "^0.64.27",
155
- "@gjsify/semver": "^0.64.27",
156
- "@gjsify/tar": "^0.64.27",
157
- "@gjsify/tsc": "^0.64.27",
158
- "@gjsify/utils": "^0.64.27",
159
- "@gjsify/web-polyfills": "^0.64.27",
160
- "@gjsify/workspace": "^0.64.27",
145
+ "@gjsify/blueprint": "^0.64.29",
146
+ "@gjsify/buffer": "^0.64.29",
147
+ "@gjsify/create-app": "^0.64.29",
148
+ "@gjsify/node-globals": "^0.64.29",
149
+ "@gjsify/node-polyfills": "^0.64.29",
150
+ "@gjsify/npm-registry": "^0.64.29",
151
+ "@gjsify/resolve-npm": "^0.64.29",
152
+ "@gjsify/rolldown-plugin-gjsify": "^0.64.29",
153
+ "@gjsify/vite-plugin-blueprint": "^0.64.29",
154
+ "@gjsify/rolldown-plugin-pnp": "^0.64.29",
155
+ "@gjsify/semver": "^0.64.29",
156
+ "@gjsify/tar": "^0.64.29",
157
+ "@gjsify/tsc": "^0.64.29",
158
+ "@gjsify/utils": "^0.64.29",
159
+ "@gjsify/web-polyfills": "^0.64.29",
160
+ "@gjsify/workspace": "^0.64.29",
161
161
  "acorn": "^8.17.0",
162
162
  "cosmiconfig": "^9.0.2",
163
163
  "get-tsconfig": "^4.14.0",
@@ -166,13 +166,13 @@
166
166
  "yargs": "^18.0.0"
167
167
  },
168
168
  "devDependencies": {
169
- "@gjsify/unit": "^0.64.27",
169
+ "@gjsify/unit": "^0.64.29",
170
170
  "@types/yargs": "^17.0.35",
171
171
  "typescript": "^6.0.3"
172
172
  },
173
173
  "peerDependencies": {
174
- "@gjsify/oxfmt-native": "^0.64.27",
175
- "@gjsify/rolldown-native": "^0.64.27"
174
+ "@gjsify/oxfmt-native": "^0.64.29",
175
+ "@gjsify/rolldown-native": "^0.64.29"
176
176
  },
177
177
  "peerDependenciesMeta": {
178
178
  "@gjsify/oxfmt-native": {