@cpajs/cpa 0.1.0-rc.4 → 0.1.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +213 -17
  2. package/dist/binary-packages.cjs +84 -0
  3. package/dist/binary-packages.d.cts +30 -0
  4. package/dist/binary.d.ts +11 -0
  5. package/dist/binary.d.ts.map +1 -0
  6. package/dist/binary.js +10 -0
  7. package/dist/binary.js.map +1 -0
  8. package/dist/client/errors.d.ts +50 -0
  9. package/dist/client/errors.d.ts.map +1 -1
  10. package/dist/client/errors.js +63 -0
  11. package/dist/client/errors.js.map +1 -1
  12. package/dist/client/index.d.ts +5 -4
  13. package/dist/client/index.d.ts.map +1 -1
  14. package/dist/client/index.js +2 -2
  15. package/dist/client/index.js.map +1 -1
  16. package/dist/client/resources/config.d.ts +51 -5
  17. package/dist/client/resources/config.d.ts.map +1 -1
  18. package/dist/client/resources/config.js +149 -0
  19. package/dist/client/resources/config.js.map +1 -1
  20. package/dist/client/resources/credentials.d.ts +170 -5
  21. package/dist/client/resources/credentials.d.ts.map +1 -1
  22. package/dist/client/resources/credentials.js +796 -9
  23. package/dist/client/resources/credentials.js.map +1 -1
  24. package/dist/client/resources/requests.d.ts +13 -0
  25. package/dist/client/resources/requests.d.ts.map +1 -1
  26. package/dist/client/resources/requests.js +40 -0
  27. package/dist/client/resources/requests.js.map +1 -1
  28. package/dist/client/transport.d.ts +11 -1
  29. package/dist/client/transport.d.ts.map +1 -1
  30. package/dist/client/transport.js +35 -14
  31. package/dist/client/transport.js.map +1 -1
  32. package/dist/client/types/config.d.ts +2 -0
  33. package/dist/client/types/config.d.ts.map +1 -1
  34. package/dist/server/binary.d.ts.map +1 -1
  35. package/dist/server/binary.js +7 -15
  36. package/dist/server/binary.js.map +1 -1
  37. package/dist/server/config.d.ts +11 -0
  38. package/dist/server/config.d.ts.map +1 -1
  39. package/dist/server/config.js +32 -0
  40. package/dist/server/config.js.map +1 -1
  41. package/dist/server/errors.d.ts +2 -0
  42. package/dist/server/errors.d.ts.map +1 -1
  43. package/dist/server/errors.js.map +1 -1
  44. package/dist/server/index.d.ts +33 -1
  45. package/dist/server/index.d.ts.map +1 -1
  46. package/dist/server/index.js +695 -178
  47. package/dist/server/index.js.map +1 -1
  48. package/dist/server/logs.d.ts +11 -0
  49. package/dist/server/logs.d.ts.map +1 -0
  50. package/dist/server/logs.js +39 -0
  51. package/dist/server/logs.js.map +1 -0
  52. package/dist/server/management.d.ts +12 -5
  53. package/dist/server/management.d.ts.map +1 -1
  54. package/dist/server/management.js +8 -1
  55. package/dist/server/management.js.map +1 -1
  56. package/dist/server/process.d.ts +3 -1
  57. package/dist/server/process.d.ts.map +1 -1
  58. package/dist/server/process.js +7 -2
  59. package/dist/server/process.js.map +1 -1
  60. package/dist/server/types.d.ts +210 -15
  61. package/dist/server/types.d.ts.map +1 -1
  62. package/package.json +31 -25
  63. package/src/binary-packages.cjs +84 -0
  64. package/src/binary-packages.d.cts +30 -0
  65. package/src/binary.ts +10 -0
  66. package/src/client/errors.ts +74 -0
  67. package/src/client/index.ts +33 -4
  68. package/src/client/resources/config.ts +197 -5
  69. package/src/client/resources/credentials.ts +972 -9
  70. package/src/client/resources/requests.ts +49 -0
  71. package/src/client/transport.ts +47 -15
  72. package/src/client/types/config.ts +3 -0
  73. package/src/server/binary.ts +5 -14
  74. package/src/server/config.ts +31 -0
  75. package/src/server/errors.ts +2 -0
  76. package/src/server/index.ts +831 -190
  77. package/src/server/logs.ts +43 -0
  78. package/src/server/management.ts +13 -5
  79. package/src/server/process.ts +9 -3
  80. package/src/server/types.ts +232 -15
package/README.md CHANGED
@@ -45,11 +45,19 @@ await server.stop();
45
45
  ```
46
46
 
47
47
  - `config` and `configPath` are mutually exclusive.
48
- - `config` is written as YAML to `<stateDir>/config.yaml` only when that file does not exist yet. On later
49
- starts the existing file is reused, so changes made through the management API (or by CPA itself) survive
50
- `stop()` and `startServer()`. Pass `overwriteConfig: true` to replace it; when a file is kept, `config`, `host`
51
- and `port` are not applied and a `configReused` warning is emitted. Credentials go to `<stateDir>/auths`
52
- unless `oauth.auth-dir` is set. The server binds `127.0.0.1` unless you pass `host` or set `server.host`.
48
+ - `config` is either a native config object or a function that returns one.
49
+ - An object is written as YAML to `<stateDir>/config.yaml` only when that file does not exist yet. On later
50
+ starts the existing file is reused, so changes made through the management API (or by CPA itself) survive
51
+ `stop()` and `startServer()`. Pass `overwriteConfig: true` to replace it; when a file is kept, `config`, `host`
52
+ and `port` are not applied and a `configReused` warning is emitted. Credentials go to `<stateDir>/auths`
53
+ unless `oauth.auth-dir` is set. The server binds `127.0.0.1` unless you pass `host` or set `server.host`.
54
+ - A function is called before the first start and again before every restart. It receives
55
+ `{ existing, reason }`: the parsed current `<stateDir>/config.yaml` (or `undefined`) and `'start'` or
56
+ `'restart'`. Its result replaces the file each time, like `overwriteConfig: true`, while cpajs still fills in
57
+ the listener, management secret and panel fields. It cannot be combined with `overwriteConfig`, and a
58
+ `configReused` warning is never emitted. The management key is resolved before the function runs, so
59
+ `management['secret-key']` in its result does not choose the key behind `server.client()`; pass
60
+ `management` for that (or keep the generated key).
53
61
  - `configPath` hands an existing file to CPA unchanged. CPA may rewrite it on startup: it hashes a plaintext
54
62
  `management.secret-key`, removes legacy keys that conflict with their v8 equivalents, and normalizes the
55
63
  layout (`internal/config/config_load.go` and `NormalizeConfigLayout`).
@@ -60,8 +68,11 @@ await server.stop();
60
68
  `tls.enable`. When cpajs writes the file and no port is given, it picks a free port first; a reused file keeps
61
69
  the port it already has.
62
70
  - `startServer` resolves only once `/healthz` answers. It rejects with `CpaStartError` on early exit, port
63
- conflict, timeout (`startupTimeoutMs`, default 30 s) or `signal` abort. In every failure case the process is
64
- stopped and the temporary directory removed.
71
+ conflict, timeout (`startupTimeoutMs`, default 30 s), `signal` abort, or an `afterStart` hook failure. In every
72
+ failure case the process is stopped and the temporary directory removed. With `restart.onStartFailure`, the
73
+ retryable failures (early exit, timeout, port conflict, a failing `afterStart`, or a config function that
74
+ throws) are retried with `restart.backoffMs`/`restart.maxAttempts` before the last error is thrown; invalid
75
+ options, an aborted signal and a missing binary still reject immediately.
65
76
  - `stop()` is idempotent: on POSIX it sends SIGTERM and then SIGKILL after `stopTimeoutMs` (default 10 s). On
66
77
  Windows Node cannot deliver a graceful shutdown signal, so `stop()` terminates the process forcefully (equivalent
67
78
  to SIGKILL), `stopTimeoutMs` has no effect, and CPA gets no chance to flush state or update auth files. The same
@@ -69,11 +80,52 @@ await server.stop();
69
80
  - `restart({ timeoutMs, signal })` stops the old process with the same SIGTERM → SIGKILL sequence
70
81
  (`timeoutMs` defaults to `stopTimeoutMs`) and starts it again with the original options. The handle keeps
71
82
  `origin`, `baseUrl`, `host`, `port`, `stateDir` and `configPath`; `pid`, `process` and `recentLogs` point at the
72
- new process. The existing `config.yaml` is reused and never rewritten, so changes made through the management
73
- API survive. A dynamic port is reused too; if another process took it meanwhile, restart fails with
74
- `CpaStartError` code `port-in-use` instead of changing `origin`. Concurrent `restart()` calls share one
75
- operation, `stop()` during a restart aborts it, and `restart()` after `stop()` rejects. A failed restart leaves
76
- the handle stopped and cleans up a temporary state directory like `startServer` does.
83
+ new process. With an object `config`, the existing `config.yaml` is reused and never rewritten, so changes made
84
+ through the management API survive. A function `config` is evaluated again before each restart and its result
85
+ replaces the file. A dynamic port is reused too; if another process took it meanwhile, restart fails with
86
+ `CpaStartError` code `port-in-use` instead of changing `origin`, unless `restart.allowNewPort` is set: then a
87
+ new free port is picked, `origin`, `baseUrl` and `port` move, the managed config's `server.port` follows, and
88
+ existing `server.client()` instances use the new origin. A fixed port is never changed. Concurrent `restart()`
89
+ calls share one operation, `stop()` during a restart aborts it, and `restart()` after `stop()` rejects. A
90
+ failed restart leaves the handle stopped and cleans up a temporary state directory like `startServer` does.
91
+ - `restart: { onUnexpectedExit, onStartFailure, backoffMs, stableAfterMs, maxAttempts, allowNewPort }` restarts
92
+ CPA by itself after an unexpected exit. It goes through the same path as `restart()`, so `origin`, `port`, the
93
+ handle, the existing config file and already-created `server.client()` instances keep working. `backoffMs`
94
+ defaults to `[500, 1000, 5000, 30_000]` and its last value repeats. A restarted process must stay up for
95
+ `stableAfterMs` (default 60 s) to count as healthy; one that exits before it keeps the backoff position, so a
96
+ crash loop escalates instead of restarting every 500 ms. `maxAttempts` consecutive restarts without a stable
97
+ run stop the server and settle `exited` (default `Infinity`); a manual `restart()` resets the count.
98
+ `onStartFailure` applies the same backoff/attempt policy to failures of the first start. `stop()` cancels a
99
+ pending wait, and `restart()` during one tries immediately. A port taken by another process makes that attempt
100
+ fail and retries after the next backoff, unless `allowNewPort` moves a dynamic port as described above.
101
+ - `singleton: true` reuses one server per process for the same resolved `stateDir` (or absolute `configPath`),
102
+ so a dev server that evaluates a module more than once cannot start CPA twice. Concurrent calls share the
103
+ in-flight start and its promise; a handle that has not stopped yet is returned as-is, including while it is
104
+ backing off or restarting. Once the handle stops, the next call starts a new process. It requires an explicit
105
+ `stateDir` or `configPath`, and the options of the first call win: options on later calls are not compared.
106
+ The registry lives on `globalThis` (keyed by `Symbol.for('cpajs.servers')`), so duplicate module instances
107
+ in the same process share it.
108
+ - Lifecycle events: `server.on('exit' | 'restart' | 'restarted' | 'restart-failed', listener)` returns an
109
+ unsubscribe function. An `exit` payload has `code`, `signal`, `recentLogs`, `willRestart` and `reason`:
110
+ `'stop'` when `stop()` stopped the process, `'restart'` when a manual or automatic restart replaced it, and
111
+ `'unexpected'` when the process exited by itself. `restart` and `restarted` carry `reason`
112
+ (`'unexpected-exit' | 'manual'`) and `attempt`, and `restarted` also has `originChanged` (`true` when
113
+ `allowNewPort` moved the server); `restart-failed` has `error`, `attempt` and `willRetry`. A failed first
114
+ start retried by `onStartFailure` is also reported as `restart-failed`, with `attempt` counting failed start
115
+ attempts. A listener that throws is reported through `process.emitWarning` and never disturbs the server. Pass
116
+ `on` to `startServer` to subscribe before the first process is watched; with `singleton: true` only the first
117
+ call's listeners are registered.
118
+ - `hooks.afterStart({ server, client, reason, requireClient })` runs after each process is ready: the first
119
+ start and every restart, manual or automatic. `reason` is `'start'` or `'restart'`; `client` is
120
+ `server.client()` when cpajs knows the plaintext management key and `undefined` otherwise. `startServer`
121
+ narrows `client` to `CpaClient` only when the key is provably known: no `management: false` or `configPath`,
122
+ and `config` omitted, a function, or an object whose type has no `management['secret-key']`. A wide
123
+ `CpaConfig` variable stays `CpaClient | undefined`; `requireClient()` returns the client or throws with the
124
+ reason it is unavailable. The hook may return a cleanup function (or a promise of one), which cpajs calls once
125
+ when that process exits: before the replacement starts on a restart, or after the final stop. A cleanup that
126
+ throws is reported through `process.emitWarning` and does not change the lifecycle. If the hook throws, the
127
+ first start rejects with `CpaStartError` code `hook-failed` after stopping the process, while a restart fails
128
+ like any other (`restart-failed`, then backoff or a rejected `restart()`).
77
129
  - Shutdown: CPA does not outlive your process, even if it is killed with SIGKILL, crashes, or is restarted by
78
130
  `tsx watch` / `nodemon`. Each platform package ships a small `cpa-launcher` (pure Go, in `launcher/`) that
79
131
  relies only on operating-system facilities:
@@ -99,6 +151,21 @@ await server.stop();
99
151
  ```
100
152
 
101
153
  Lines longer than 64 KiB in CPA's output are truncated, with a marker saying how much was dropped.
154
+ - Logs: `onLog` receives every line with `stream` and the redacted `line`. When the line uses CPA's log format,
155
+ it also has `level` (`debug`, `info`, `warn`, `error` or `fatal`), the short 8-character `requestId` (omitted
156
+ for CPA's `--------` placeholder) and `message` (the text after CPA's timestamp, request-id, level and caller
157
+ prefixes). Output that does not match the format still arrives, with only `stream` and `line`.
158
+
159
+ Pass `logs: { minLevel: 'warn' }` to drop lower-severity lines from `onLog`; `recentLogs` keeps everything,
160
+ because error messages often need the surrounding info lines. Lines without a parsed level pass by default, so
161
+ unknown output is never hidden; `logs: { minLevel: 'warn', unleveled: 'stderr' }` keeps only those on stderr
162
+ (such as a Go panic) and drops CPA's stdout banner, and `unleveled: 'none'` drops them all.
163
+
164
+ ```ts
165
+ await startServer({ config, logs: { minLevel: 'warn' }, onLog: ({ level, message, line }) => {
166
+ console.log(`[${level ?? 'raw'}] ${message ?? line}`);
167
+ } });
168
+ ```
102
169
  - Management key: you usually don't need one. Without `management`, cpajs generates a random key for each start,
103
170
  writes only its bcrypt hash into the managed config (remote management off), keeps the plaintext in memory,
104
171
  and gives you `server.client()`: a management client bound to this server. The key is never exposed, and
@@ -199,9 +266,33 @@ const { data: config, etag } = await client.config.get();
199
266
  await client.config.patch({ routing: { strategy: 'round-robin' } }, { ifMatch: etag });
200
267
  await client.config.set('routing/retry/request-retry', 2); // value typed by path: number
201
268
 
269
+ // Read → change → write with If-Match. `auth_index` (injected on reads) is removed,
270
+ // a 412 re-reads and retries, and returning undefined skips the write.
271
+ await client.config.update('routing/strategy', (current) => current ?? 'fill-first');
272
+
273
+ // Deep-compares each top-level section and replaces only the ones that differ.
274
+ // A listed section is written wholesale, so nested keys absent from it are removed;
275
+ // sections not listed are untouched.
276
+ await client.config.reconcile({ routing: { strategy: 'fill-first' } });
277
+
202
278
  const { files } = await client.credentials.list();
203
279
  await client.credentials.upload({ name: 'codex-me.json', content: credentialJson });
204
280
 
281
+ // Files and config `api-keys` entries in one list, with the runtime auth_index.
282
+ const all = await client.credentials.listAll();
283
+ const models = await client.credentials.modelsFor(all[0]!, { details: true });
284
+
285
+ const desired = [{ name: 'chat-a.json', content: credentialJson, revision: '2026-10-27' }];
286
+ const synced = await client.credentials.reconcile({
287
+ owner: 'chat',
288
+ files: desired,
289
+ // A legacy file without `x-cpajs` is claimed in place. Returning its desired
290
+ // revision keeps the tokens CPA already rotated; a different one uploads `desired`.
291
+ adopt: (name, body) =>
292
+ body.chat_seed === undefined ? undefined : desired.find((file) => file.name === name)?.revision,
293
+ });
294
+ console.log(synced); // { uploaded: ['chat-a.json'], deleted: [], unchanged: [], adopted: [] }
295
+
205
296
  const login = await client.oauth.start({ provider: 'claude' });
206
297
  console.log('open', login.url);
207
298
  await client.oauth.waitForCompletion(login.state);
@@ -213,22 +304,73 @@ try {
213
304
  }
214
305
  ```
215
306
 
307
+ `credentials.reconcile` keeps a set of files owned by one caller in sync. Uploads carry a reserved
308
+ `x-cpajs: { owner, revision }` field. Only `revision` is compared, so CPA rewriting a file during a token
309
+ refresh does not cause another upload. With `prune` (the default), files owned by `owner` that are no longer
310
+ in `files` are deleted; files owned by anyone else are never touched. The caller's content objects are not
311
+ mutated.
312
+
313
+ A same-name file without the marker is never overwritten. Reconcile throws `CpaReconcileError` with code
314
+ `unmarked` (also for files owned by another caller, code `owned-by-other`) unless `adopt(name, body)` returns
315
+ a revision. Adoption keeps the stored content, including tokens, writes only the marker, and then compares the
316
+ returned revision with the desired one: equal leaves the file alone, different uploads the desired content.
317
+ Returning `undefined` leaves the file unmanaged; a same-name unmarked file then still throws. `adopt` is also
318
+ called for unmarked files in the prune range, so a recognized legacy file can be claimed and deleted.
319
+ `files[].content` accepts an object, JSON text, bytes, or a `Blob`; strings and bytes are parsed and must
320
+ resolve to a JSON object, which is checked before any request.
321
+
322
+ `credentials.listAll` merges credential files with the config's `api-keys` entries, which `/credentials` only
323
+ exposes as a runtime view. It returns a discriminated union: a file entry has `raw: AuthFileEntry` and its
324
+ `name`, while a config entry has the provider key as `raw` and its group (without `keys`) as `group`. A config
325
+ key is `disabled` when its own or its group's effective `excluded-models` contains `*`, which is what
326
+ `PATCH /credentials/status` writes upstream.
327
+
328
+ `credentials.setStatus` takes a file `name` or a config key's `auth_index`, and `credentials.delete` takes file
329
+ names or one `{ auth_index }`. Upstream's status route can toggle native `api-keys` entries but requires the
330
+ runtime auth ID as `name`, which `GET /credentials` does not expose for config keys; its delete route only
331
+ handles files. For config keys cpajs therefore edits the config through `config.update` (ETag / 412 retry,
332
+ `auth_index` stripped): disable adds `*` to the key's `excluded-models`, enable removes it (other patterns and
333
+ the group are untouched, so a group-level `excluded-models: ["*"]` still disables it), and delete removes the
334
+ key from its group, keeping an empty native-provider group. The last key of an `openai-compatibility` group
335
+ removes the group, because a keyless compat group is itself a credential. OpenAI-compatible entries have no
336
+ per-key switch (and disabling a keyless group clears its `auth_index`), so `setStatus` throws for them; use
337
+ `delete({ auth_index })` instead.
338
+
339
+ `credentials.modelsFor` accepts either a selector (file `name` or `auth_index`) or a `listAll` entry; passing
340
+ the entry skips the extra list/config requests. Config-key models follow CPA's own resolution (model aliases,
341
+ `excluded-models` with `*` wildcards, and per-key overrides); `details: true` adds the channel's static model
342
+ definitions, which are cached for the client's lifetime. Pass `refreshDefinitions: true` or call
343
+ `clearModelDefinitionsCache()` after the CPA binary changes. Runtime state such as cooldowns is only available
344
+ for files.
345
+
216
346
  | Group | Routes |
217
347
  | --- | --- |
218
- | `config` | `/config`, `/config.yaml`, `/config/*path`, with ETag / `If-Match` |
219
- | `credentials` | list, upload (raw or multipart), delete, models, download, status, fields, refresh, SIWC status |
348
+ | `config` | `/config`, `/config.yaml`, `/config/*path`, with ETag / `If-Match`, plus `update` / `reconcile` |
349
+ | `credentials` | list all (files + config keys), models per credential (with details), upload (raw or multipart), reconcile by owner/revision (with adoption), delete / status (files or config keys by `auth_index`), download, fields, refresh, SIWC status |
220
350
  | `oauth` | auth URL, status / wait, cancel, callback, Vertex import, SIWC bind |
221
351
  | `logs` | main log with cursor, clear, error logs, request logs |
222
352
  | `usage` | API-key counters, usage queue (destructive pop) |
223
353
  | `routing` | cooldown reset, model definitions |
224
- | `requests` | server-side `api-call` |
354
+ | `requests` | server-side `api-call` (`apiCall`, `apiCallJson`) |
225
355
  | `plugins` | list, delete, store, install, quota |
226
356
  | `server` | `/healthz`, version headers, latest release |
227
357
 
228
- Every method takes `{ signal, timeoutMs, headers }`. Errors:
358
+ `requests.apiCallJson()` is the throwing variant of `apiCall` for JSON upstreams: the parsed body becomes `data`,
359
+ a non-2xx upstream status throws `CpaUpstreamError`, a 2xx body that is not JSON throws `CpaResponseError`, and
360
+ an unresolvable `$TOKEN$` throws `CpaCredentialTokenError`.
361
+
362
+ Every method takes `{ signal, timeoutMs, headers }`. GET requests retry CPA's transient
363
+ `500 invalid_config` (a read landing while `config.yaml` is rewritten) up to three times after
364
+ 100/200/400 ms; writes never retry. Pass `retryInvalidConfig: false` to `createClient` to disable it. Errors:
229
365
 
230
366
  - `CpaHttpError` for a non-2xx response. It carries `status`, the raw `body`, parsed `data`, and `errorCode` /
231
367
  `errorMessage`.
368
+ - `CpaUpstreamError` when `requests.apiCallJson` gets a non-2xx upstream status. It carries the upstream
369
+ `status`, `headers`, and `body` (parsed when JSON).
370
+ - `CpaCredentialTokenError` when `requests.apiCallJson` cannot resolve `$TOKEN$`. It carries `status` and
371
+ `errorCode`.
372
+ - `CpaReconcileError` when `credentials.reconcile` will not overwrite a file. It carries `code` (`unmarked` or
373
+ `owned-by-other`) and `file`.
232
374
  - `CpaNetworkError` when the request fails.
233
375
  - `CpaTimeoutError` when the request times out.
234
376
  - `CpaAbortError` when your `signal` aborts the request.
@@ -256,6 +398,58 @@ import OpenAI from 'openai';
256
398
  const openai = new OpenAI({ baseURL: server.baseUrl, apiKey: 'sk-my-model-key' });
257
399
  ```
258
400
 
401
+ ## Bundling and deploying
402
+
403
+ The platform package is an optional dependency picked at runtime, so a bundler cannot see it in a normal
404
+ `import`. `@cpajs/cpa/binary` is a small entry that contains a literal `require.resolve()` for every target;
405
+ importing it for its side effect puts the installed platform packages in the module graph:
406
+
407
+ ```ts
408
+ import '@cpajs/cpa/binary';
409
+ ```
410
+
411
+ Trace on the deployment platform (including glibc vs musl). A file tracer such as `@vercel/nft` then copies
412
+ the package that matches the build machine. Keep `@cpajs/cpa` and `@cpajs/<target>` external rather than
413
+ bundling them. nft reports a warning for every platform package that is not installed; those are expected
414
+ and non-fatal.
415
+
416
+ Nitro uses nft. Import the entry from the server code, and full-trace the platform package so its `bin/`
417
+ directory is copied too (`pkg*` copies every file, not only the traced ones):
418
+
419
+ ```ts
420
+ import { resolveBinary } from '@cpajs/cpa/server';
421
+
422
+ export default defineNitroConfig({
423
+ // The platform package installed on the build machine, e.g. @cpajs/linux-x64-gnu.
424
+ // Build on the platform you deploy to, or write the package name out instead.
425
+ traceDeps: ['@cpajs/cpa', `${resolveBinary().packageName}*`],
426
+ });
427
+ ```
428
+
429
+ Vite SSR leaves packages in `node_modules` external; make that explicit and run nft over the server output (or
430
+ over `@cpajs/cpa/binary`) as part of the deploy step:
431
+
432
+ ```ts
433
+ export default defineConfig({
434
+ ssr: { external: ['@cpajs/cpa'] },
435
+ });
436
+ ```
437
+
438
+ Next.js: keep cpajs outside the server bundle and let output file tracing include it:
439
+
440
+ ```js
441
+ module.exports = {
442
+ serverExternalPackages: ['@cpajs/cpa'],
443
+ };
444
+ ```
445
+
446
+ In all three setups the side-effect import is what makes the table visible; if a trace still misses the
447
+ binary, copy `node_modules/@cpajs/<target>/` into the deployment or pass `binaryPath` to `startServer`.
448
+
449
+ Bun ignores `libc`, so `bun install` on Linux installs both `@cpajs/linux-*-gnu` and `@cpajs/linux-*-musl`
450
+ (about 72 MB extra). Install with npm or pnpm, or delete the packages for the other libc before packaging;
451
+ cpajs still picks the right target at runtime. `binaryPath` also lets you ship a single binary yourself.
452
+
259
453
  ## Development
260
454
 
261
455
  ```sh
@@ -276,14 +470,16 @@ Release tooling, all in `scripts/` and run directly with Node's type stripping:
276
470
  | Script | Purpose |
277
471
  | --- | --- |
278
472
  | `fetch-source.ts` | Clone the pinned CPA tag and verify the commit. |
473
+ | `generate-binary-table.ts` | Regenerate `src/binary-packages.cjs` and its types from `TARGETS`; `--check` fails on drift. |
279
474
  | `build-binary.ts` | Build one or more targets, with the same CGO/plugin split as upstream. |
280
475
  | `verify-binary.ts` | Check format, CPU, static linking and the glibc baseline; `--smoke` starts the binary. |
281
476
  | `assemble-packages.ts` | Create the `@cpajs/*` platform packages. |
282
477
  | `pack.ts` | Produce the tarballs. |
283
478
  | `install-test.ts` | Install the tarballs through a local registry with npm, pnpm or bun, and run them. |
479
+ | `wait-for-packages.ts` | Poll the npm registry until every platform package resolves at a version; run it before publishing the main package. |
284
480
  | `trust-publishers.ts` | Configure npm trusted publishing for all packages (run locally after the first publish). |
285
481
 
286
- `.github/workflows/release.yml` runs these steps across the whole platform matrix and publishes on `v*` tags through npm trusted publishing (OIDC). Prerelease versions such as `0.0.1-alpha-1` go to a matching dist-tag (`alpha`). There is no npm token; `trust-publishers.ts` configures the trusted publisher for every package. A newly added platform package has to exist on npm before it can be trusted.
482
+ `.github/workflows/release.yml` runs these steps across the whole platform matrix and publishes on `v*` tags through npm trusted publishing (OIDC). Prerelease versions such as `0.0.1-alpha-1` go to a matching dist-tag (`alpha`). There is no npm token; `trust-publishers.ts` configures the trusted publisher for every package. A newly added platform package has to exist on npm before it can be trusted. The publish job runs `wait-for-packages.ts --version <version>` after publishing the platform packages and before the main package, so `@cpajs/cpa` is not published while one of its optional dependencies is still missing from the install packument that npm, pnpm and bun read (registry metadata is CDN-cached). It can be run locally against an already published release, e.g. `node scripts/wait-for-packages.ts --version 0.1.0-rc.5`; `--timeout` and `--interval` take seconds.
287
483
 
288
484
  ## License
289
485
 
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Static platform package table for `@cpajs/cpa/binary`.
3
+ *
4
+ * Generated by scripts/generate-binary-table.ts from TARGETS in
5
+ * src/server/targets.ts; do not edit. Importing the entry (for its side effect)
6
+ * lets bundlers such as @vercel/nft trace the optional platform packages:
7
+ *
8
+ * import '@cpajs/cpa/binary';
9
+ *
10
+ * Every lookup below is a literal require.resolve() call inside try/catch, so a
11
+ * trace does not depend on the runtime target selection in src/server/binary.ts.
12
+ * This file is CommonJS on purpose: @vercel/nft only follows require.resolve()
13
+ * in CommonJS input.
14
+ */
15
+ 'use strict';
16
+
17
+ /** Platform package names by target id. */
18
+ const PLATFORM_PACKAGES = {
19
+ 'darwin-x64': '@cpajs/darwin-x64',
20
+ 'darwin-arm64': '@cpajs/darwin-arm64',
21
+ 'win32-x64': '@cpajs/win32-x64',
22
+ 'win32-arm64': '@cpajs/win32-arm64',
23
+ 'win32-ia32': '@cpajs/win32-ia32',
24
+ 'linux-x64-gnu': '@cpajs/linux-x64-gnu',
25
+ 'linux-arm64-gnu': '@cpajs/linux-arm64-gnu',
26
+ 'linux-x64-musl': '@cpajs/linux-x64-musl',
27
+ 'linux-arm64-musl': '@cpajs/linux-arm64-musl',
28
+ 'linux-arm': '@cpajs/linux-arm',
29
+ 'linux-ia32': '@cpajs/linux-ia32',
30
+ 'linux-riscv64': '@cpajs/linux-riscv64',
31
+ 'linux-ppc64': '@cpajs/linux-ppc64',
32
+ 'linux-s390x': '@cpajs/linux-s390x',
33
+ 'linux-loong64': '@cpajs/linux-loong64',
34
+ 'linux-mips': '@cpajs/linux-mips',
35
+ 'linux-mipsel': '@cpajs/linux-mipsel',
36
+ 'freebsd-x64': '@cpajs/freebsd-x64',
37
+ 'freebsd-arm64': '@cpajs/freebsd-arm64',
38
+ 'freebsd-ia32': '@cpajs/freebsd-ia32',
39
+ 'openbsd-x64': '@cpajs/openbsd-x64',
40
+ 'openbsd-arm64': '@cpajs/openbsd-arm64',
41
+ 'netbsd-x64': '@cpajs/netbsd-x64',
42
+ };
43
+
44
+ const resolvers = {
45
+ 'darwin-x64': () => require.resolve('@cpajs/darwin-x64/package.json'),
46
+ 'darwin-arm64': () => require.resolve('@cpajs/darwin-arm64/package.json'),
47
+ 'win32-x64': () => require.resolve('@cpajs/win32-x64/package.json'),
48
+ 'win32-arm64': () => require.resolve('@cpajs/win32-arm64/package.json'),
49
+ 'win32-ia32': () => require.resolve('@cpajs/win32-ia32/package.json'),
50
+ 'linux-x64-gnu': () => require.resolve('@cpajs/linux-x64-gnu/package.json'),
51
+ 'linux-arm64-gnu': () => require.resolve('@cpajs/linux-arm64-gnu/package.json'),
52
+ 'linux-x64-musl': () => require.resolve('@cpajs/linux-x64-musl/package.json'),
53
+ 'linux-arm64-musl': () => require.resolve('@cpajs/linux-arm64-musl/package.json'),
54
+ 'linux-arm': () => require.resolve('@cpajs/linux-arm/package.json'),
55
+ 'linux-ia32': () => require.resolve('@cpajs/linux-ia32/package.json'),
56
+ 'linux-riscv64': () => require.resolve('@cpajs/linux-riscv64/package.json'),
57
+ 'linux-ppc64': () => require.resolve('@cpajs/linux-ppc64/package.json'),
58
+ 'linux-s390x': () => require.resolve('@cpajs/linux-s390x/package.json'),
59
+ 'linux-loong64': () => require.resolve('@cpajs/linux-loong64/package.json'),
60
+ 'linux-mips': () => require.resolve('@cpajs/linux-mips/package.json'),
61
+ 'linux-mipsel': () => require.resolve('@cpajs/linux-mipsel/package.json'),
62
+ 'freebsd-x64': () => require.resolve('@cpajs/freebsd-x64/package.json'),
63
+ 'freebsd-arm64': () => require.resolve('@cpajs/freebsd-arm64/package.json'),
64
+ 'freebsd-ia32': () => require.resolve('@cpajs/freebsd-ia32/package.json'),
65
+ 'openbsd-x64': () => require.resolve('@cpajs/openbsd-x64/package.json'),
66
+ 'openbsd-arm64': () => require.resolve('@cpajs/openbsd-arm64/package.json'),
67
+ 'netbsd-x64': () => require.resolve('@cpajs/netbsd-x64/package.json'),
68
+ };
69
+
70
+ /**
71
+ * Resolves an installed platform package's package.json, or returns undefined
72
+ * when the package is not installed for this platform.
73
+ */
74
+ function resolvePlatformPackage(id) {
75
+ const resolve = resolvers[id];
76
+ if (resolve === undefined) return undefined;
77
+ try {
78
+ return resolve();
79
+ } catch {
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ module.exports = { PLATFORM_PACKAGES, resolvePlatformPackage };
@@ -0,0 +1,30 @@
1
+ /** Generated by scripts/generate-binary-table.ts from TARGETS; do not edit. */
2
+ export declare const PLATFORM_PACKAGES: {
3
+ readonly 'darwin-x64': '@cpajs/darwin-x64';
4
+ readonly 'darwin-arm64': '@cpajs/darwin-arm64';
5
+ readonly 'win32-x64': '@cpajs/win32-x64';
6
+ readonly 'win32-arm64': '@cpajs/win32-arm64';
7
+ readonly 'win32-ia32': '@cpajs/win32-ia32';
8
+ readonly 'linux-x64-gnu': '@cpajs/linux-x64-gnu';
9
+ readonly 'linux-arm64-gnu': '@cpajs/linux-arm64-gnu';
10
+ readonly 'linux-x64-musl': '@cpajs/linux-x64-musl';
11
+ readonly 'linux-arm64-musl': '@cpajs/linux-arm64-musl';
12
+ readonly 'linux-arm': '@cpajs/linux-arm';
13
+ readonly 'linux-ia32': '@cpajs/linux-ia32';
14
+ readonly 'linux-riscv64': '@cpajs/linux-riscv64';
15
+ readonly 'linux-ppc64': '@cpajs/linux-ppc64';
16
+ readonly 'linux-s390x': '@cpajs/linux-s390x';
17
+ readonly 'linux-loong64': '@cpajs/linux-loong64';
18
+ readonly 'linux-mips': '@cpajs/linux-mips';
19
+ readonly 'linux-mipsel': '@cpajs/linux-mipsel';
20
+ readonly 'freebsd-x64': '@cpajs/freebsd-x64';
21
+ readonly 'freebsd-arm64': '@cpajs/freebsd-arm64';
22
+ readonly 'freebsd-ia32': '@cpajs/freebsd-ia32';
23
+ readonly 'openbsd-x64': '@cpajs/openbsd-x64';
24
+ readonly 'openbsd-arm64': '@cpajs/openbsd-arm64';
25
+ readonly 'netbsd-x64': '@cpajs/netbsd-x64';
26
+ };
27
+
28
+ export type PlatformTargetId = keyof typeof PLATFORM_PACKAGES;
29
+
30
+ export declare function resolvePlatformPackage(id: string): string | undefined;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Entry point for bundlers: importing `@cpajs/cpa/binary` (for its side effect)
3
+ * puts the installed platform packages in the module graph, so a tracer such as
4
+ * @vercel/nft copies the one that matches the deployment.
5
+ *
6
+ * The table itself is generated into binary-packages.cjs; see
7
+ * scripts/generate-binary-table.ts and src/server/binary.ts.
8
+ */
9
+ export { PLATFORM_PACKAGES, resolvePlatformPackage } from './binary-packages.cjs';
10
+ export type { PlatformTargetId } from './binary-packages.cjs';
11
+ //# sourceMappingURL=binary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binary.d.ts","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAClF,YAAY,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/binary.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Entry point for bundlers: importing `@cpajs/cpa/binary` (for its side effect)
3
+ * puts the installed platform packages in the module graph, so a tracer such as
4
+ * @vercel/nft copies the one that matches the deployment.
5
+ *
6
+ * The table itself is generated into binary-packages.cjs; see
7
+ * scripts/generate-binary-table.ts and src/server/binary.ts.
8
+ */
9
+ export { PLATFORM_PACKAGES, resolvePlatformPackage } from './binary-packages.cjs';
10
+ //# sourceMappingURL=binary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binary.js","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC"}
@@ -36,6 +36,54 @@ export declare class CpaHttpError extends CpaClientError {
36
36
  /** The `message` field of a CPA error body, when present. */
37
37
  get errorMessage(): string | undefined;
38
38
  }
39
+ /**
40
+ * The upstream call made through `requests.apiCallJson` returned a non-2xx status.
41
+ *
42
+ * `headers` and `body` are the upstream response's; `body` is parsed when it is
43
+ * JSON, the raw text when it is not, and `undefined` when it is empty.
44
+ */
45
+ export declare class CpaUpstreamError extends CpaClientError {
46
+ readonly name = "CpaUpstreamError";
47
+ readonly status: number;
48
+ readonly headers: Record<string, string[]>;
49
+ readonly body: unknown;
50
+ constructor(request: {
51
+ method: string;
52
+ url: string;
53
+ }, response: {
54
+ status: number;
55
+ headers: Record<string, string[]>;
56
+ body: string;
57
+ });
58
+ }
59
+ /**
60
+ * CPA answered 400 because it could not resolve the credential token behind
61
+ * `$TOKEN$`. `errorCode` is CPA's error, e.g. `"auth token not found"`;
62
+ * `cause` is the original `CpaHttpError`.
63
+ */
64
+ export declare class CpaCredentialTokenError extends CpaClientError {
65
+ readonly name = "CpaCredentialTokenError";
66
+ readonly status: number;
67
+ readonly errorCode: string;
68
+ constructor(error: CpaHttpError);
69
+ }
70
+ export type CpaReconcileErrorCode =
71
+ /** The file has no `x-cpajs` marker, so it may belong to someone else. */
72
+ 'unmarked'
73
+ /** The file carries another caller's `x-cpajs` marker. */
74
+ | 'owned-by-other';
75
+ /**
76
+ * `credentials.reconcile` found an existing file it must not overwrite.
77
+ *
78
+ * `unmarked` files can be claimed by passing `adopt`; `owned-by-other` files
79
+ * are never overwritten. `file` is the auth directory file name.
80
+ */
81
+ export declare class CpaReconcileError extends Error {
82
+ readonly name = "CpaReconcileError";
83
+ readonly code: CpaReconcileErrorCode;
84
+ readonly file: string;
85
+ constructor(code: CpaReconcileErrorCode, file: string, message: string);
86
+ }
39
87
  /** The request could not be sent or the response could not be read. */
40
88
  export declare class CpaNetworkError extends CpaClientError {
41
89
  readonly name = "CpaNetworkError";
@@ -67,4 +115,6 @@ export declare class CpaResponseError extends CpaClientError {
67
115
  cause?: unknown;
68
116
  });
69
117
  }
118
+ /** Parses an `api-call` body: JSON when possible, raw text otherwise, `undefined` when empty. */
119
+ export declare function parseApiCallBody(text: string): unknown;
70
120
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/client/errors.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,qBAAa,cAAe,SAAQ,KAAK;IACvC,SAAkB,IAAI,EAAE,MAAM,CAAoB;IAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAErB,YAAY,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAInG;CACF;AAED;;;;;GAKG;AACH,qBAAa,YAAa,SAAQ,cAAc;IAC9C,SAAkB,IAAI,kBAAkB;IACxC,QAAQ,CAAC,MAA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wC;AACxC,qBAAa,eAAgB,SAAQ,cAAc;IACjD,SAAkB,IAAI,qBAAqB;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAE3B,YAAY,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAGrG;CACF;AAED,4EAA4E;AAC5E,qBAAa,aAAc,SAAQ,cAAc;IAC/C,SAAkB,IAAI,mBAAmB;CAC1C;AAED,iFAAiF;AACjF,qBAAa,gBAAiB,SAAQ,cAAc;IAClD,SAAkB,IAAI,sBAAsB;IAC5C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,EAIjI;CACF;AAWD,iGAAiG;AACjG,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAOtD"}
@@ -43,6 +43,58 @@ export class CpaHttpError extends CpaClientError {
43
43
  return typeof value === 'string' ? value : undefined;
44
44
  }
45
45
  }
46
+ /**
47
+ * The upstream call made through `requests.apiCallJson` returned a non-2xx status.
48
+ *
49
+ * `headers` and `body` are the upstream response's; `body` is parsed when it is
50
+ * JSON, the raw text when it is not, and `undefined` when it is empty.
51
+ */
52
+ export class CpaUpstreamError extends CpaClientError {
53
+ name = 'CpaUpstreamError';
54
+ status;
55
+ headers;
56
+ body;
57
+ constructor(request, response) {
58
+ const body = parseApiCallBody(response.body);
59
+ const detail = describeErrorBody(body);
60
+ super(`${request.method} ${request.url} failed with upstream ${response.status}${detail ? `: ${detail}` : ''}`, request);
61
+ this.status = response.status;
62
+ this.headers = response.headers;
63
+ this.body = body;
64
+ }
65
+ }
66
+ /**
67
+ * CPA answered 400 because it could not resolve the credential token behind
68
+ * `$TOKEN$`. `errorCode` is CPA's error, e.g. `"auth token not found"`;
69
+ * `cause` is the original `CpaHttpError`.
70
+ */
71
+ export class CpaCredentialTokenError extends CpaClientError {
72
+ name = 'CpaCredentialTokenError';
73
+ status;
74
+ errorCode;
75
+ constructor(error) {
76
+ const code = error.errorCode ?? 'unknown error';
77
+ super(`${error.method} ${error.url} could not resolve a credential token: ${code}`, error, { cause: error });
78
+ this.status = error.status;
79
+ this.errorCode = code;
80
+ }
81
+ }
82
+ /**
83
+ * `credentials.reconcile` found an existing file it must not overwrite.
84
+ *
85
+ * `unmarked` files can be claimed by passing `adopt`; `owned-by-other` files
86
+ * are never overwritten. `file` is the auth directory file name.
87
+ */
88
+ export class CpaReconcileError extends Error {
89
+ name = 'CpaReconcileError';
90
+ code;
91
+ file;
92
+ constructor(code, file, message) {
93
+ super(message);
94
+ this.code = code;
95
+ this.file = file;
96
+ }
97
+ }
46
98
  /** The request could not be sent or the response could not be read. */
47
99
  export class CpaNetworkError extends CpaClientError {
48
100
  name = 'CpaNetworkError';
@@ -81,6 +133,17 @@ function parseJsonOrUndefined(text) {
81
133
  return undefined;
82
134
  }
83
135
  }
136
+ /** Parses an `api-call` body: JSON when possible, raw text otherwise, `undefined` when empty. */
137
+ export function parseApiCallBody(text) {
138
+ if (text === '')
139
+ return undefined;
140
+ try {
141
+ return JSON.parse(text);
142
+ }
143
+ catch {
144
+ return text;
145
+ }
146
+ }
84
147
  function describeErrorBody(data) {
85
148
  if (typeof data !== 'object' || data === null)
86
149
  return undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/client/errors.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD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