@entrinsik/vite-plugin-informer 2.13.0 → 2.14.0

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/README.md CHANGED
@@ -5,14 +5,18 @@ Vite plugin and deploy tool for Informer App development: a local dev server wir
5
5
  ## Quick start
6
6
 
7
7
  ```bash
8
+ npm install -g @entrinsik/informer-cli
9
+ inf login <your-informer-url> # once: the sign-in dev and deploy use
8
10
  npm create vite@latest my-app -- --template react
9
11
  cd my-app
10
12
  npm install -D @entrinsik/vite-plugin-informer
11
- npx informer-init # wires vite config, informer.yaml, .env, deploy scripts
12
- npm run dev # local dev against the Informer in .env
13
- npm run deploy # assemble + upload + deploy
13
+ npx informer-init # wires vite config, informer.yaml, deploy scripts
14
+ npm run dev # local dev against the server you signed in to
15
+ npm run deploy # assemble + upload + deploy (or: inf deploy, which asks first)
14
16
  ```
15
17
 
18
+ No `.env` is needed: with no credential in the environment or `.env`, the plugin asks the Informer CLI (`inf auth token`) for the signed-in server and a current token, and a dev server renews it as it runs. `INFORMER_URL` with `INFORMER_API_KEY` (or `INFORMER_USER` and `INFORMER_PASS`) in `.env` still work, and win when set; `INFORMER_URL` alone picks which of your sign-ins to use.
19
+
16
20
  `informer-init` leaves an existing `@entrinsik/vite-plugin-informer` entry alone, and writes one only when the dependency is missing — in which case it uses its own version (2.12.0 and later; before that it wrote `^1.0.0`). A project scaffolded earlier still carries `^1.0.0`, which resolves to 1.0.5 and predates everything below: bump it by hand.
17
21
 
18
22
  ## What a deploy ships
package/bin/deploy.js CHANGED
@@ -4,9 +4,12 @@ import { readFile, writeFile } from 'node:fs/promises';
4
4
  import { resolve } from 'node:path';
5
5
  import { deploy } from '../src/deploy.js';
6
6
  import { loadEnv, parseModeArg } from '../src/env.js';
7
+ import { useSignedIn } from '../src/signed-in.js';
7
8
 
8
9
  const mode = parseModeArg(process.argv);
9
10
  loadEnv({ mode });
11
+ // No credential in the environment or .env: use the inf CLI's sign-in
12
+ const signedIn = await useSignedIn(process.env);
10
13
 
11
14
  const baseUrl = process.env.INFORMER_URL;
12
15
  const apiKey = process.env.INFORMER_API_KEY;
@@ -14,13 +17,16 @@ const user = process.env.INFORMER_USER;
14
17
  const pass = process.env.INFORMER_PASS;
15
18
 
16
19
  if (!baseUrl || (!apiKey && (!user || !pass))) {
17
- console.error('Missing required environment variables.');
18
- console.error('Create a .env file with:');
19
- console.error(' INFORMER_URL=http://localhost:3000');
20
- console.error(' INFORMER_API_KEY=your-api-key');
21
- console.error('Or use basic auth:');
22
- console.error(' INFORMER_USER=admin');
23
- console.error(' INFORMER_PASS=yourpassword');
20
+ if (signedIn.reason) {
21
+ console.error(signedIn.reason);
22
+ } else if (signedIn.source === 'env' && !baseUrl) {
23
+ console.error('INFORMER_URL is not set. Set it in .env next to your credential.');
24
+ } else {
25
+ console.error('Not signed in to an Informer server.');
26
+ console.error('Sign in once with the Informer CLI (npm install -g @entrinsik/informer-cli):');
27
+ console.error(' inf login <your-informer-url>');
28
+ }
29
+ console.error('Or set INFORMER_URL with INFORMER_API_KEY (or INFORMER_USER and INFORMER_PASS) in .env.');
24
30
  process.exit(1);
25
31
  }
26
32
 
package/bin/init.js CHANGED
@@ -208,14 +208,17 @@ async function init() {
208
208
  // 7. Update vite.config
209
209
  await updateViteConfig();
210
210
 
211
- // 8. Create .env.example
212
- const envExample = `# Informer connection settings
213
- INFORMER_URL=http://localhost:3000
214
-
215
- # Option 1: API Key (recommended)
216
- INFORMER_API_KEY=your-api-key
217
-
218
- # Option 2: Basic auth
211
+ // 8. Create .env.example. No .env: the Informer CLI's sign-in (inf login)
212
+ // is the credential, and a placeholder key would stand in its way
213
+ const envExample = `# Nothing here is required. Sign in once with the Informer CLI:
214
+ # npm install -g @entrinsik/informer-cli
215
+ # inf login <your-informer-url>
216
+ # and npm run dev / npm run deploy use that sign-in (inf deploy does too).
217
+ #
218
+ # To use another server or credential instead, copy this file to .env and set:
219
+ # INFORMER_URL=http://localhost:3000
220
+ # INFORMER_API_KEY=your-api-key
221
+ # or basic auth:
219
222
  # INFORMER_USER=admin
220
223
  # INFORMER_PASS=yourpassword
221
224
  `;
@@ -226,13 +229,6 @@ INFORMER_API_KEY=your-api-key
226
229
  console.log('Created .env.example');
227
230
  }
228
231
 
229
- // Also create .env if it doesn't exist
230
- const envPath = resolve(cwd, '.env');
231
- if (!await exists(envPath)) {
232
- await writeFile(envPath, envExample);
233
- console.log('Created .env (update with your credentials)');
234
- }
235
-
236
232
  // 9. Create informer.yaml if it doesn't exist
237
233
  const informerYamlPath = resolve(cwd, 'informer.yaml');
238
234
  if (!await exists(informerYamlPath)) {
@@ -245,7 +241,7 @@ INFORMER_API_KEY=your-api-key
245
241
 
246
242
  console.log('\nSetup complete!\n');
247
243
  console.log('Next steps:');
248
- console.log(' 1. Update .env with your Informer credentials');
244
+ console.log(' 1. Sign in once, if you have not: inf login <your-informer-url> (npm install -g @entrinsik/informer-cli)');
249
245
  console.log(' 2. Declare your data dependencies in informer.yaml (see comments inside)');
250
246
  console.log(' 3. Run: npm install');
251
247
  console.log(' 4. Run: npm run dev');
@@ -283,7 +279,7 @@ export default defineConfig({
283
279
  }
284
280
 
285
281
  // Check if plugin is already added
286
- if (configContent.includes('vite-plugin-informer') || configContent.includes("informer()")) {
282
+ if (configContent.includes('vite-plugin-informer') || configContent.includes('informer()')) {
287
283
  console.log('Informer plugin already in vite config');
288
284
  return;
289
285
  }
package/bin/workspace.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { resolve, basename } from 'node:path';
5
5
  import { createClient } from '../src/client.js';
6
+ import { useSignedIn } from '../src/signed-in.js';
6
7
  import { loadEnv, envWritePath, localEnvValue, parseModeArg } from '../src/env.js';
7
8
  import { init, migrate, reset } from '../src/workspace.js';
8
9
 
@@ -26,14 +27,18 @@ if (!command || !['init', 'migrate', 'reset'].includes(command)) {
26
27
  process.exit(1);
27
28
  }
28
29
 
30
+ // No credential in the environment or .env: use the inf CLI's sign-in
31
+ const signedIn = await useSignedIn(process.env);
29
32
  const baseUrl = process.env.INFORMER_URL;
30
33
  const apiKey = process.env.INFORMER_API_KEY;
31
34
  const user = process.env.INFORMER_USER;
32
35
  const pass = process.env.INFORMER_PASS;
33
36
 
34
37
  if (!baseUrl || (!apiKey && (!user || !pass))) {
35
- console.error('Missing required environment variables.');
36
- console.error('Set INFORMER_URL and either INFORMER_API_KEY or INFORMER_USER/INFORMER_PASS in .env');
38
+ if (signedIn.reason) console.error(signedIn.reason);
39
+ else if (signedIn.source === 'env' && !baseUrl) console.error('INFORMER_URL is not set. Set it in .env next to your credential.');
40
+ else console.error('Not signed in to an Informer server. Run inf login <your-informer-url>.');
41
+ console.error('Or set INFORMER_URL with INFORMER_API_KEY (or INFORMER_USER and INFORMER_PASS) in .env.');
37
42
  process.exit(1);
38
43
  }
39
44
 
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@entrinsik/vite-plugin-informer",
3
- "version": "2.13.0",
3
+ "version": "2.14.0",
4
4
  "description": "Vite plugin and deploy tool for Informer App development",
5
5
  "scripts": {
6
- "test": "node --test"
6
+ "test": "node --test",
7
+ "lint": "eslint ."
7
8
  },
8
9
  "repository": {
9
10
  "type": "git",
10
11
  "url": "https://github.com/entrinsik-org/i5.git",
11
- "directory": "packages/vite-plugin-informer"
12
+ "directory": "packages-standalone/vite-plugin-informer"
12
13
  },
13
14
  "author": "Entrinsik Inc.",
14
15
  "license": "UNLICENSED",
@@ -46,5 +47,10 @@
46
47
  "dependencies": {
47
48
  "dotenv": "16.6.1",
48
49
  "yaml": "^2.7.0"
50
+ },
51
+ "devDependencies": {
52
+ "@eslint/js": "9.22.0",
53
+ "eslint": "9.22.0",
54
+ "globals": "15.15.0"
49
55
  }
50
56
  }
package/src/agent-dev.js CHANGED
@@ -157,6 +157,8 @@ async function readSSE(response) {
157
157
  * @returns {Function} Connect middleware
158
158
  */
159
159
  export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, devWorkspaceId, projectRoot, devBindings, appToken, channels = createDevChannels(), platform = devPlatform(), appId = null }) {
160
+ // a string, or a function answering the current header (renewed from the CLI's sign-in)
161
+ const header = () => (typeof authHeader === 'function' ? authHeader() : authHeader);
160
162
 
161
163
  // query() — proxies to the workspace _sql endpoint (same as server-routes.js)
162
164
  async function query(sql, params) {
@@ -166,7 +168,7 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
166
168
 
167
169
  const resp = await globalThis.fetch(`${serverOrigin}/api/datasources/${devWorkspaceId}/_sql`, {
168
170
  method: 'POST',
169
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
171
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
170
172
  body: JSON.stringify({ sql, params: params || [] })
171
173
  });
172
174
 
@@ -221,7 +223,7 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
221
223
  const embed = createDevEmbed({ platform, apiFetch, appId });
222
224
 
223
225
  async function apiFetch(path, opts = {}) {
224
- return await fetchAs(authHeader, path, opts);
226
+ return await fetchAs(header(), path, opts);
225
227
  }
226
228
 
227
229
  // Cross-app request() hits the target's /view/_/ dispatch, which accepts only
@@ -229,11 +231,11 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
229
231
  // INFORMER_API_KEY Bearer is reused; under basic auth INFORMER_APP_TOKEN is
230
232
  // required. appFetch stamps x-informer-app-depth:1 for the one-hop guard.
231
233
  // See server-routes.js.
232
- const appAuth = appToken
234
+ const appAuth = () => (appToken
233
235
  ? `Bearer ${appToken}`
234
- : (authHeader && authHeader.startsWith('Bearer ') ? authHeader : null);
235
- const appFetch = appAuth
236
- ? async (path, opts = {}) => await fetchAs(appAuth, path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
236
+ : (header() && header().startsWith('Bearer ') ? header() : null));
237
+ const appFetch = appAuth()
238
+ ? async (path, opts = {}) => await fetchAs(appAuth(), path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
237
239
  : null;
238
240
 
239
241
  // notify/email — delivery is a console-logged no-op in dev, but required-field
@@ -401,7 +403,7 @@ export function createAgentMiddleware(viteServer, { serverOrigin, authHeader, de
401
403
  // Call the AI model
402
404
  const chatResp = await globalThis.fetch(`${serverOrigin}/api/models/${model}/_chat`, {
403
405
  method: 'POST',
404
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
406
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
405
407
  body: JSON.stringify({
406
408
  messages,
407
409
  system: instructions,
package/src/assemble.js CHANGED
@@ -25,8 +25,9 @@ const ROOT_CONFIG_FILES = ['informer.yaml', 'data-access.yaml', 'API.md', 'READM
25
25
  // channels/ holds live-channel join/leave handlers (App Channels); the server
26
26
  // scans and bundles it like server/ and webhooks/. `embeddings` holds the pump
27
27
  // use-case files: server-side like server/, so they ship with the library and
28
- // the platform can scan them.
29
- const SOURCE_DIRS = ['migrations', 'tools', 'mcp', 'server', 'webhooks', 'channels', 'embeddings', 'lib', 'shared'];
28
+ // the platform can scan them. `cli` holds the commands the installed Informer
29
+ // CLI runs, scanned and bundled like mcp/.
30
+ const SOURCE_DIRS = ['migrations', 'tools', 'mcp', 'cli', 'server', 'webhooks', 'channels', 'embeddings', 'lib', 'shared'];
30
31
 
31
32
  // Entries never worth shipping in an app's server-side library: OS/editor
32
33
  // dotfiles (.DS_Store, .env), nested dependency trees, and test files. Applied
package/src/compat.js CHANGED
@@ -22,6 +22,8 @@ export const FEATURE_FLOORS = Object.freeze({
22
22
  channels: '2026.1.3',
23
23
  // The embedding pump: embeddings/ use cases and embed() on the handler bag.
24
24
  embeddings: '2026.1.3',
25
+ // App CLI commands: cli/ handlers the installed Informer CLI runs.
26
+ cli: '2026.2.0',
25
27
  // Staged uploads/downloads: the uploads/downloads services, /view/_uploads
26
28
  // and /view/_downloads, and __INFORMER__.upload() in the page.
27
29
  streams: '2026.1.3',
@@ -32,7 +34,9 @@ export const FEATURE_FLOORS = Object.freeze({
32
34
  // Server-side enforcement of the manifest's `requires:` block. Below this
33
35
  // floor the CLI is the only thing in the loop that can honour a declared
34
36
  // Informer floor, so it enforces it itself.
35
- requiresGate: '2026.1.3'
37
+ requiresGate: '2026.1.3',
38
+ // Outbound webhooks: `webhook: true` events delivered to registered endpoints.
39
+ webhooks: '2026.2.0'
36
40
  });
37
41
 
38
42
  /**
@@ -50,7 +54,8 @@ export const FEATURE_FLOORS = Object.freeze({
50
54
  */
51
55
  export const GATED_SOURCE_DIRS = Object.freeze([
52
56
  Object.freeze({ dir: 'channels', feature: 'channels', holds: 'channel join/leave handlers' }),
53
- Object.freeze({ dir: 'embeddings', feature: 'embeddings', holds: 'embedding pump handlers (and the workspace SQL in them)' })
57
+ Object.freeze({ dir: 'embeddings', feature: 'embeddings', holds: 'embedding pump handlers (and the workspace SQL in them)' }),
58
+ Object.freeze({ dir: 'cli', feature: 'cli', holds: 'CLI command handlers' })
54
59
  ]);
55
60
 
56
61
  /**
@@ -179,10 +184,11 @@ export function planDeploy({ server, files, manifest }) {
179
184
  const where = server.version ? `Informer ${server.version}` : 'this Informer';
180
185
 
181
186
  if (server.unknown) {
187
+ const atRisk = GATED_SOURCE_DIRS.map(d => `${d.dir}/ (before ${FEATURE_FLOORS[d.feature]})`).join(', ');
182
188
  warnings.push(
183
189
  `Could not read a comparable version from ${server.version ? `"${server.version}"` : 'GET /api/about'}. `
184
- + 'Deploying everything on the assumption the server is current — if it is older than 2026.1.3, '
185
- + `${GATED_SOURCE_DIRS.map(d => `${d.dir}/`).join(' and ')} will be readable from the App's view URL.`
190
+ + 'Deploying everything on the assumption the server is current. On an older server these trees '
191
+ + `would be readable from the App's view URL: ${atRisk}.`
186
192
  );
187
193
  }
188
194
 
@@ -209,6 +215,12 @@ export function planDeploy({ server, files, manifest }) {
209
215
  + 'Nothing is relayed and broadcast() does not reach the page.'
210
216
  );
211
217
  }
218
+ if (!server.supports('webhooks') && isMap(manifest.events) && Object.values(manifest.events).some(def => isMap(def) && def.webhook === true)) {
219
+ warnings.push(
220
+ `informer.yaml declares webhook: true events, which ${where} ignores (outbound webhooks need ${FEATURE_FLOORS.webhooks}). `
221
+ + 'No endpoint can subscribe and nothing is delivered.'
222
+ );
223
+ }
212
224
  if (!server.supports('streams') && uploaded.has('server')) {
213
225
  warnings.push(
214
226
  `${where} predates ${FEATURE_FLOORS.streams}: if a handler destructures uploads/downloads from its bag, or the page `
package/src/deploy.js CHANGED
@@ -122,7 +122,7 @@ export async function deploy({ baseUrl, apiKey, user, pass, distDir, name, descr
122
122
 
123
123
  // 6. Upload the app-library file set assembled in step 0: dist output at the
124
124
  // library root, plus informer.yaml / data-access.yaml and the
125
- // server/tools/mcp/migrations/webhooks/embeddings source trees, less any
125
+ // server/tools/mcp/cli/migrations/webhooks/embeddings source trees, less any
126
126
  // tree this server is too old to keep out of browsers (see compat.js).
127
127
  // Sourced from the shared collectAppFiles() so a deploy and a marketplace
128
128
  // publish package byte-identical contents.
package/src/dev-bag.js CHANGED
@@ -74,7 +74,9 @@ export function buildDevUser(user) {
74
74
  *
75
75
  * @param {Object} opts
76
76
  * @param {string} opts.serverOrigin - Informer server origin
77
- * @param {string} opts.authHeader - Basic or Bearer auth header for /api calls
77
+ * @param {string|Function} opts.authHeader - Basic or Bearer auth header for
78
+ * /api calls, or a function answering the current one (a header from the
79
+ * CLI's sign-in is renewed, signed-in.js)
78
80
  * @param {string|null} opts.devWorkspaceId - workspace datasource id for query()
79
81
  * @param {string} opts.projectRoot - app project root
80
82
  * @param {Object} [opts.devBindings] - dev bindings for `target: app` / `target: pack` deps
@@ -90,6 +92,8 @@ export function buildDevUser(user) {
90
92
  * @returns {{ query: Function, apiFetch: Function, build: (opts?: { forwarding?: Object|null }) => Promise<{ manifest: Object, bag: Object }> }}
91
93
  */
92
94
  export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId, projectRoot, devBindings = {}, appToken = null, channels = createDevChannels(), logPrefix = '[app]', platform = devPlatform(), appId = null }) {
95
+ const header = () => (typeof authHeader === 'function' ? authHeader() : authHeader);
96
+
93
97
  // query() implementation — proxies to the workspace _sql endpoint
94
98
  async function query(sql, params) {
95
99
  if (!devWorkspaceId) {
@@ -98,7 +102,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
98
102
 
99
103
  const resp = await globalThis.fetch(`${serverOrigin}/api/datasources/${devWorkspaceId}/_sql`, {
100
104
  method: 'POST',
101
- headers: { 'Content-Type': 'application/json', Authorization: authHeader },
105
+ headers: { 'Content-Type': 'application/json', Authorization: header() },
102
106
  body: JSON.stringify({ sql, params: params || [] })
103
107
  });
104
108
 
@@ -178,7 +182,7 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
178
182
  }
179
183
 
180
184
  async function apiFetch(path, opts = {}) {
181
- return await fetchAs(authHeader, path, opts);
185
+ return await fetchAs(header(), path, opts);
182
186
  }
183
187
 
184
188
  // Cross-app request() targets /api/apps/<id>/view/_/<path>, whose auth accepts
@@ -188,11 +192,11 @@ export function createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId,
188
192
  // the app proxy's request() throws a pointed error instead of a bare 401.
189
193
  // appFetch also stamps x-informer-app-depth:1 so the target runs one hop deep
190
194
  // and enforces the same one-hop guard it does in production.
191
- const appAuth = appToken
195
+ const appAuth = () => (appToken
192
196
  ? `Bearer ${appToken}`
193
- : (authHeader && authHeader.startsWith('Bearer ') ? authHeader : null);
194
- const appFetch = appAuth
195
- ? async (path, opts = {}) => await fetchAs(appAuth, path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
197
+ : (header() && header().startsWith('Bearer ') ? header() : null));
198
+ const appFetch = appAuth()
199
+ ? async (path, opts = {}) => await fetchAs(appAuth(), path, { ...opts, headers: { ...(opts.headers || {}), 'x-informer-app-depth': '1' } })
196
200
  : null;
197
201
 
198
202
  // notify/email — delivery is a console-logged no-op in dev, but the
@@ -7,7 +7,10 @@
7
7
  * default: the pump needs a real Informer, so an app that feature-detects on
8
8
  * it sees locally exactly what it sees on an install without the feature.
9
9
  * Turning it on binds query-time `embed()` to a deployed app's `_embed` route
10
- * (see createDevEmbed); the pump itself is still not mirrored. `version` is
10
+ * (see createDevEmbed); the pump itself is still not mirrored. `publicAccess`
11
+ * and `accounts` are off for the same reason: anonymous serving and app
12
+ * sign-in need a real Informer. `cli` is off too: cli/ commands run only once
13
+ * deployed. `version` is
11
14
  * `'dev'` (not semver) so a floor check treats the dev mirror as "unknown"
12
15
  * rather than as any particular release. `originMode` is on: the dev server
13
16
  * behaves like an app served from its own origin, where live channels work.
@@ -33,7 +36,12 @@ export const DEV_CAPABILITIES = Object.freeze({
33
36
  channels: true,
34
37
  // channels/ files with config.actor: one live instance per channel (dev-channel-actors.js)
35
38
  channelActors: true,
36
- embeddings: false
39
+ embeddings: false,
40
+ // the dev server neither serves anonymously (manifest `public:`) nor mirrors app sign-in
41
+ publicAccess: false,
42
+ accounts: false,
43
+ // cli/ commands run only on a deployed app; the dev server does not mirror them
44
+ cli: false
37
45
  });
38
46
 
39
47
  export function devPlatform(overrides = {}) {
@@ -216,6 +216,8 @@ export function isStreamRef(value, type) {
216
216
 
217
217
  export function createUpload(store, { filename, contentType, size, chunkSize, fingerprint }) {
218
218
  const { limits } = store;
219
+ // The control-character range is the point of this check.
220
+ // eslint-disable-next-line no-control-regex
219
221
  if (typeof filename !== 'string' || !filename || /[\\/\x00-\x1F]/.test(filename)) {
220
222
  throw httpError(400, 'filename is required and may not contain path separators or control characters');
221
223
  }
package/src/index.js CHANGED
@@ -15,6 +15,7 @@ import { createStreamStore, createUploadsMiddleware, createDownloadsMiddleware }
15
15
  import { streamsClientSource } from './streams-client.js';
16
16
  import { init, migrate } from './workspace.js';
17
17
  import { devPlatform } from './dev-platform.js';
18
+ import { forgetSignedIn, refreshingHeader, useSignedIn } from './signed-in.js';
18
19
 
19
20
  /**
20
21
  * The dev `window.__INFORMER__` context: defaults overlaid with the plugin's
@@ -142,6 +143,7 @@ async function writeAppDepTypes (projectRoot, dts) {
142
143
  * slots resolve their marketplace pin via installs dev doesn't have, so the
143
144
  * binding names the locally-installed app. See AppDevBinding in index.d.ts.
144
145
  * @param {Object} [options.proxy] - extra Vite proxy options merged onto /api.
146
+ * Its `configure` runs after the plugin's own, which sets Authorization.
145
147
  * @returns {import('vite').Plugin}
146
148
  */
147
149
  export default function informer(options = {}) {
@@ -155,12 +157,17 @@ export default function informer(options = {}) {
155
157
  // this is only needed under basic auth (INFORMER_USER/PASS).
156
158
  let appToken = null;
157
159
  let activeMode = null;
160
+ let renewed = null;
158
161
 
159
162
  return {
160
163
  name: 'vite-plugin-informer',
161
164
 
162
- config(_, { command, mode }) {
165
+ async config(_, { command, mode }) {
163
166
  activeMode = mode;
167
+ if (renewed) renewed.stop();
168
+ renewed = null;
169
+ // Before loadEnv, so a restart reads .env as if the CLI had filled nothing
170
+ forgetSignedIn(process.env);
164
171
  loadEnv({ mode });
165
172
 
166
173
  isDev = command === 'serve';
@@ -170,6 +177,8 @@ export default function informer(options = {}) {
170
177
  };
171
178
 
172
179
  if (isDev) {
180
+ // No credential in the environment or .env: use the inf CLI's sign-in (signed-in.js)
181
+ const signedIn = await useSignedIn(process.env);
173
182
  const baseUrl = process.env.INFORMER_URL;
174
183
  const apiKey = process.env.INFORMER_API_KEY;
175
184
  const user = process.env.INFORMER_USER;
@@ -178,21 +187,35 @@ export default function informer(options = {}) {
178
187
  devWorkspaceId = process.env.INFORMER_DEV_WORKSPACE || null;
179
188
  appToken = process.env.INFORMER_APP_TOKEN || null;
180
189
 
190
+ if (signedIn.reason) {
191
+ console.warn(`[informer] ${signedIn.reason}`);
192
+ } else if (baseUrl && !apiKey && !(user && pass)) {
193
+ console.warn('[informer] INFORMER_URL is set but there is no credential. Run inf login, or set INFORMER_API_KEY in .env.');
194
+ }
181
195
  if (baseUrl) {
182
196
  serverOrigin = baseUrl.replace(/\/+$/, '');
183
- authHeader = apiKey
197
+ const header = apiKey
184
198
  ? 'Bearer ' + apiKey
185
199
  : 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64');
200
+ // the CLI's access token lasts 15 minutes, so a dev server renews it
201
+ renewed = signedIn.source === 'inf' ? refreshingHeader(header, { expiresAt: signedIn.expiresAt, url: serverOrigin }) : null;
202
+ authHeader = renewed ? renewed.get : header;
203
+ const userConfigure = options.proxy && options.proxy.configure;
186
204
 
187
205
  cfg.server = {
188
206
  proxy: {
189
207
  '/api': {
190
208
  target: baseUrl,
191
209
  changeOrigin: true,
192
- headers: {
193
- Authorization: authHeader
194
- },
195
- ...options.proxy
210
+ ...options.proxy,
211
+ // set per request, so a renewed header reaches the proxy;
212
+ // a configure of the project's own runs after it
213
+ configure: (proxy, proxyOptions) => {
214
+ proxy.on('proxyReq', (proxyReq) => {
215
+ proxyReq.setHeader('Authorization', typeof authHeader === 'function' ? authHeader() : authHeader);
216
+ });
217
+ if (typeof userConfigure === 'function') userConfigure(proxy, proxyOptions);
218
+ }
196
219
  },
197
220
  // NOTE: no /informer-api mount. The server
198
221
  // retired that spelling — /api is ONE namespace
@@ -208,6 +231,10 @@ export default function informer(options = {}) {
208
231
  },
209
232
 
210
233
  async configureServer(server) {
234
+ if (renewed && server.httpServer) {
235
+ const ending = renewed;
236
+ server.httpServer.on('close', () => ending.stop());
237
+ }
211
238
  if (!isDev || !serverOrigin) return;
212
239
 
213
240
  const projectRoot = process.cwd();
@@ -1,9 +1,10 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
+ import yaml from 'yaml';
4
5
  import { filePathToRoute, walkJsFiles } from './server-routes.js';
5
6
 
6
- // Build the app's OpenAPI 3.0.3 document from the LOCAL project at publish
7
+ // Build the app's OpenAPI 3.1 document from the LOCAL project at publish
7
8
  // time — the frozen, per-version contract the marketplace stores alongside the
8
9
  // changelog. CI often has no access to the Informer host an app was developed
9
10
  // against, so this cannot fetch the live /apps/{id}/openapi.json; instead the
@@ -44,25 +45,46 @@ function operationId(method, path) {
44
45
  return `${method.toLowerCase()}_${slug}`;
45
46
  }
46
47
 
47
- // OpenAPI 3.0.3 Schema Object keywords, by required value type (port of the
48
- // server emitter's sanitizeSchema — see file header).
49
- const SCHEMA_STRING_KEYS = new Set(['type', 'format', 'title', 'description', 'pattern']);
50
- const SCHEMA_NUMBER_KEYS = new Set(['multipleOf', 'maximum', 'minimum', 'maxLength', 'minLength', 'maxItems', 'minItems', 'maxProperties', 'minProperties']);
51
- const SCHEMA_BOOLEAN_KEYS = new Set(['exclusiveMaximum', 'exclusiveMinimum', 'uniqueItems', 'nullable', 'readOnly', 'writeOnly', 'deprecated']);
52
- const SCHEMA_ANY_KEYS = new Set(['default', 'example']);
53
- const SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'array', 'object']);
48
+ // OpenAPI 3.1 Schema Object keywords (JSON Schema 2020-12), by required value
49
+ // type (port of the server emitter's sanitizeSchema — see file header). `type`
50
+ // and the bounds are handled apart, converting 3.0 spellings an author may write.
51
+ const SCHEMA_STRING_KEYS = new Set(['format', 'title', 'description', 'pattern']);
52
+ const SCHEMA_NUMBER_KEYS = new Set(['multipleOf', 'maxLength', 'minLength', 'maxItems', 'minItems', 'maxProperties', 'minProperties']);
53
+ const SCHEMA_BOOLEAN_KEYS = new Set(['uniqueItems', 'readOnly', 'writeOnly', 'deprecated']);
54
+ const SCHEMA_ANY_KEYS = new Set(['default', 'example', 'const']);
55
+ const SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'array', 'object', 'null']);
54
56
  const MAX_SCHEMA_DEPTH = 32;
55
57
 
58
+ // A single type name or a list of distinct names; 3.0 `nullable: true` joins 'null'.
59
+ function sanitizeType(type, nullable) {
60
+ const names = [...new Set([].concat(type === undefined ? [] : type).filter(t => typeof t === 'string' && SCHEMA_TYPES.has(t)))];
61
+ if (nullable === true && names.length && !names.includes('null')) names.push('null');
62
+ if (!names.length) return undefined;
63
+ return names.length === 1 ? names[0] : names;
64
+ }
65
+
66
+ // 3.1 bounds: exclusiveMaximum/exclusiveMinimum are the bound itself; the 3.0 boolean form is converted.
67
+ function sanitizeBounds(schema, out) {
68
+ for (const [inclusive, exclusive] of [['maximum', 'exclusiveMaximum'], ['minimum', 'exclusiveMinimum']]) {
69
+ const bound = schema[inclusive];
70
+ const flag = schema[exclusive];
71
+ if (typeof flag === 'number') out[exclusive] = flag;
72
+ else if (flag === true && typeof bound === 'number') out[exclusive] = bound;
73
+ if (typeof bound === 'number' && flag !== true) out[inclusive] = bound;
74
+ }
75
+ }
76
+
56
77
  function sanitizeSchema(schema, depth = 0) {
57
78
  if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return null;
58
79
  if (depth >= MAX_SCHEMA_DEPTH) return null;
59
80
 
60
81
  const out = {};
82
+ const type = sanitizeType(schema.type, schema.nullable);
83
+ if (type !== undefined) out.type = type;
84
+ sanitizeBounds(schema, out);
61
85
  for (const [key, value] of Object.entries(schema)) {
62
86
  if (SCHEMA_STRING_KEYS.has(key)) {
63
- if (typeof value !== 'string') continue;
64
- if (key === 'type' && !SCHEMA_TYPES.has(value)) continue;
65
- out[key] = value;
87
+ if (typeof value === 'string') out[key] = value;
66
88
  } else if (SCHEMA_NUMBER_KEYS.has(key)) {
67
89
  if (typeof value === 'number') out[key] = value;
68
90
  } else if (SCHEMA_BOOLEAN_KEYS.has(key)) {
@@ -98,11 +120,95 @@ function sanitizeSchema(schema, depth = 0) {
98
120
  // anything else (including $ref) is dropped
99
121
  }
100
122
 
101
- if (out.type === 'array' && !out.items) out.items = {};
123
+ if ([].concat(out.type || []).includes('array') && !out.items) out.items = {};
102
124
 
103
125
  return Object.keys(out).length ? out : null;
104
126
  }
105
127
 
128
+ const WEBHOOK_HEADERS = [
129
+ ['webhook-id', 'The delivery id: the same on every retry of one delivery, so receivers can drop duplicates'],
130
+ ['webhook-timestamp', 'When this attempt was sent, in Unix seconds'],
131
+ ['webhook-signature', 'Space-separated `v1,<base64>` HMAC-SHA256 signatures of `{webhook-id}.{webhook-timestamp}.{body}` with the endpoint secret (two during a secret rotation)']
132
+ ];
133
+
134
+ const WEBHOOK_ID_DESCRIPTION = 'The event id, the same for every endpoint that receives this event (the delivery id on a test delivery)';
135
+ const WEBHOOK_TIMESTAMP_DESCRIPTION = 'When the event was emitted (when a test delivery was queued); the same on every retry';
136
+ const WEBHOOK_RESPONSE_DESCRIPTION = 'Any 2xx acknowledges the delivery; 410 Gone stops deliveries to this endpoint; anything else is retried';
137
+
138
+ function claimOperationId(usedIds, op) {
139
+ while (usedIds.has(op.operationId)) {
140
+ const m = op.operationId.match(/^(.*?)(?:_(\d+))?$/);
141
+ op.operationId = `${m[1]}_${(parseInt(m[2], 10) || 1) + 1}`;
142
+ }
143
+ usedIds.add(op.operationId);
144
+ }
145
+
146
+ // The `webhooks:` section from the manifest's `webhook: true` events (port of the
147
+ // server emitter's buildWebhooks). Here a malformed entry is skipped, never thrown;
148
+ // a deploy that rejects the block publishes no webhooks, so the frozen document can
149
+ // list more than a live instance serves until the manifest is fixed.
150
+ function buildWebhooks(events, usedIds) {
151
+ const declared = Object.entries((events && typeof events === 'object' && !Array.isArray(events)) ? events : {})
152
+ .filter(([, def]) => def && typeof def === 'object' && def.webhook === true)
153
+ .sort(([a], [b]) => a.localeCompare(b));
154
+ if (!declared.length) return undefined;
155
+ const webhooks = {};
156
+ for (const [name, def] of declared) {
157
+ const data = sanitizeSchema(def.schema) || {};
158
+ if (def.example !== undefined) data.examples = [def.example];
159
+ const op = {
160
+ operationId: `webhook_${name.replace(/[^\w]/g, '_')}`,
161
+ summary: name,
162
+ parameters: WEBHOOK_HEADERS.map(([header, description]) => ({ name: header, in: 'header', required: true, description, schema: { type: 'string' } })),
163
+ requestBody: {
164
+ required: true,
165
+ content: {
166
+ 'application/json': {
167
+ schema: {
168
+ type: 'object',
169
+ required: ['id', 'type', 'timestamp', 'app', 'data'],
170
+ properties: {
171
+ id: { type: 'string', format: 'uuid', description: WEBHOOK_ID_DESCRIPTION },
172
+ type: { type: 'string', const: name },
173
+ timestamp: { type: 'string', format: 'date-time', description: WEBHOOK_TIMESTAMP_DESCRIPTION },
174
+ app: { type: 'object', properties: { id: { type: 'string', format: 'uuid' }, naturalId: { type: 'string' } } },
175
+ data,
176
+ test: { type: 'boolean', description: 'Present and true on a "Send test" delivery' }
177
+ }
178
+ }
179
+ }
180
+ }
181
+ },
182
+ responses: { '200': { description: WEBHOOK_RESPONSE_DESCRIPTION } }
183
+ };
184
+ claimOperationId(usedIds, op);
185
+ if (typeof def.description === 'string' && def.description) op.description = def.description;
186
+ const roles = [].concat(def.roles || []).filter(r => typeof r === 'string');
187
+ if (roles.length) op['x-informer-roles'] = roles;
188
+ webhooks[name] = { post: op };
189
+ }
190
+ return webhooks;
191
+ }
192
+
193
+ // The manifest's `events:` block; a missing manifest has none, and one that cannot be
194
+ // read or parsed adds a warning, since its webhooks would silently drop from the document
195
+ async function readManifestEvents(projectRoot, warnings) {
196
+ let text;
197
+ try {
198
+ text = await readFile(join(projectRoot, 'informer.yaml'), 'utf8');
199
+ } catch (err) {
200
+ if (err.code !== 'ENOENT') warnings.push(`informer.yaml could not be read (${err.message}); the webhooks section is omitted`);
201
+ return undefined;
202
+ }
203
+ try {
204
+ const manifest = yaml.parse(text);
205
+ return manifest && manifest.events;
206
+ } catch (err) {
207
+ warnings.push(`informer.yaml is not valid YAML (${err.message}); the webhooks section is omitted`);
208
+ return undefined;
209
+ }
210
+ }
211
+
106
212
  // A method-keyed `export const schema` returns its per-method slice; a flat
107
213
  // schema applies to every method (mirror of the server scanner's sliceSchema).
108
214
  function sliceSchema(schema, method) {
@@ -234,11 +340,11 @@ async function collectLocalRoutes(projectRoot) {
234
340
  * @param {string} opts.slug - marketplace slug
235
341
  * @param {string} opts.version - the version being published (info.version)
236
342
  * @returns {Promise<{ spec: Object|null, warnings: string[] }>} spec is null
237
- * when the app has no server/ routes at all (nothing to freeze).
343
+ * when the app has no server/ routes and declares no webhook events (nothing to freeze).
238
344
  */
239
345
  export async function buildLocalOpenApi({ projectRoot, name, slug, version }) {
240
346
  const { rows, warnings } = await collectLocalRoutes(projectRoot);
241
- if (!rows.length) return { spec: null, warnings };
347
+ const events = await readManifestEvents(projectRoot, warnings);
242
348
 
243
349
  const paths = {};
244
350
  const usedIds = new Set();
@@ -246,13 +352,11 @@ export async function buildLocalOpenApi({ projectRoot, name, slug, version }) {
246
352
  const oaPath = routePathToOpenApi(row.path);
247
353
  paths[oaPath] = paths[oaPath] || {};
248
354
  const op = buildOperation(row);
249
- while (usedIds.has(op.operationId)) {
250
- const m = op.operationId.match(/^(.*?)(?:_(\d+))?$/);
251
- op.operationId = `${m[1]}_${(parseInt(m[2], 10) || 1) + 1}`;
252
- }
253
- usedIds.add(op.operationId);
355
+ claimOperationId(usedIds, op);
254
356
  paths[oaPath][row.method.toLowerCase()] = op;
255
357
  }
358
+ const webhooks = buildWebhooks(events, usedIds);
359
+ if (!rows.length && !webhooks) return { spec: null, warnings };
256
360
 
257
361
  let description;
258
362
  try {
@@ -262,7 +366,7 @@ export async function buildLocalOpenApi({ projectRoot, name, slug, version }) {
262
366
  }
263
367
 
264
368
  const spec = {
265
- openapi: '3.0.3',
369
+ openapi: '3.1.0',
266
370
  info: {
267
371
  title: name || slug,
268
372
  version: String(version),
@@ -276,7 +380,8 @@ export async function buildLocalOpenApi({ projectRoot, name, slug, version }) {
276
380
  description: 'App server-route dispatch base ({app} is the installed naturalId, owner:name)',
277
381
  variables: { app: { default: slug } }
278
382
  }],
279
- paths
383
+ paths,
384
+ ...(webhooks ? { webhooks } : {})
280
385
  };
281
386
 
282
387
  return { spec, warnings };
@@ -24,23 +24,37 @@ function tsKey (k) {
24
24
  return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
25
25
  }
26
26
 
27
- // The JSON Schema subset an app declares → a TS type string.
28
- function jsonSchemaToTs (schema) {
29
- if (!schema || typeof schema !== 'object') return 'any';
30
- if (Array.isArray(schema.enum) && schema.enum.length) {
31
- return schema.enum.map((v) => JSON.stringify(v)).join(' | ');
32
- }
33
- switch (schema.type) {
27
+ // One JSON Schema type name (or none) of `schema` → a TS type string.
28
+ function singleType (schema, type) {
29
+ switch (type) {
34
30
  case 'string': return 'string';
35
31
  case 'integer':
36
32
  case 'number': return 'number';
37
33
  case 'boolean': return 'boolean';
38
34
  case 'null': return 'null';
39
- case 'array': return `${jsonSchemaToTs(schema.items || {})}[]`;
35
+ case 'array': {
36
+ const item = jsonSchemaToTs(schema.items || {});
37
+ // `string | null[]` would read as a string or an array of nulls
38
+ return item.includes('|') ? `(${item})[]` : `${item}[]`;
39
+ }
40
40
  default:
41
41
  if (schema.properties) return objectType(schema);
42
- return schema.type === 'object' ? 'Record<string, any>' : 'any';
42
+ return type === 'object' ? 'Record<string, any>' : 'any';
43
+ }
44
+ }
45
+
46
+ // The JSON Schema subset an app declares → a TS type string. Docs are OpenAPI
47
+ // 3.1 (a `type` list such as ['string', 'null'] becomes a union) or 3.0.3 for
48
+ // packs frozen by an older publisher, whose `nullable` is ignored.
49
+ function jsonSchemaToTs (schema) {
50
+ if (!schema || typeof schema !== 'object') return 'any';
51
+ if (Array.isArray(schema.enum) && schema.enum.length) {
52
+ return schema.enum.map((v) => JSON.stringify(v)).join(' | ');
43
53
  }
54
+ if (schema.const !== undefined) return JSON.stringify(schema.const);
55
+ if (!Array.isArray(schema.type)) return singleType(schema, schema.type);
56
+ const union = [...new Set(schema.type.map((t) => singleType(schema, t)))];
57
+ return union.includes('any') || !union.length ? 'any' : union.join(' | ');
44
58
  }
45
59
 
46
60
  function objectType (schema) {
@@ -223,7 +223,8 @@ function isDescriptor(value) {
223
223
  * @param {Object} viteServer - Vite dev server instance
224
224
  * @param {Object} opts
225
225
  * @param {string} opts.serverOrigin - Informer server origin
226
- * @param {string} opts.authHeader - Basic or Bearer auth header for /api calls
226
+ * @param {string|Function} opts.authHeader - Basic or Bearer auth header for
227
+ * /api calls, or a function answering the current one (dev-bag.js)
227
228
  * @param {string|null} opts.devWorkspaceId - workspace datasource id for query()
228
229
  * @param {string} opts.projectRoot - app project root
229
230
  * @param {string[]} [opts.roles] - dev user roles surfaced on request.roles
@@ -0,0 +1,214 @@
1
+ import { execFile as execFileCb } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ /**
5
+ * Credentials from the Informer CLI's sign-in, so an app folder needs no
6
+ * secrets in `.env`.
7
+ *
8
+ * When neither the environment nor `.env` gives a credential
9
+ * (INFORMER_API_KEY, or INFORMER_USER with INFORMER_PASS), the plugin asks
10
+ * the CLI: `inf auth token --json [--url $INFORMER_URL]` prints the signed-in
11
+ * server and a current access token, refreshed by the CLI as needed. The
12
+ * plugin then fills INFORMER_URL (when unset) and INFORMER_API_KEY in its own
13
+ * process, so the deploy, workspace and dev-server code paths read them from
14
+ * the environment as usual. Running the CLI, rather than reading its files,
15
+ * keeps the two packages' versions independent.
16
+ *
17
+ * The variables the plugin filled are listed in INFORMER_FROM_INF. A second
18
+ * pass in the same process (a Vite in-process restart) clears them and asks
19
+ * the CLI again rather than mistaking them for hand-set ones, and `inf` is
20
+ * always spawned without them: the CLI prefers an INFORMER_URL plus token in
21
+ * its environment over its own sign-in, so it would hand the same token back
22
+ * with no expiry.
23
+ *
24
+ * A sign-in whose scope lacks `develop` is refused with the sentence
25
+ * `inf deploy` uses, since every deploy, workspace and API call would 403.
26
+ *
27
+ * Access tokens from the CLI last 15 minutes; a dev server asks again before
28
+ * one runs out (refreshingHeader). Credentials set by hand are never
29
+ * replaced, so an existing `.env` keeps working unchanged.
30
+ */
31
+
32
+ const INF = process.platform === 'win32' ? 'inf.cmd' : 'inf';
33
+ const FROM_INF = 'INFORMER_FROM_INF';
34
+ // The variables useSignedIn may fill, and so the only ones forgetSignedIn removes
35
+ const FILLABLE = ['INFORMER_API_KEY', 'INFORMER_URL'];
36
+
37
+ // Ask again this long before the token's stated expiry
38
+ const RENEW_MARGIN_MS = 3 * 60 * 1000;
39
+ const CHECK_EVERY_MS = 60 * 1000;
40
+
41
+ export function hasOwnCredentials(env = process.env) {
42
+ return Boolean(env.INFORMER_API_KEY || (env.INFORMER_USER && env.INFORMER_PASS));
43
+ }
44
+
45
+ /**
46
+ * Remove the variables an earlier useSignedIn filled from the CLI (listed in
47
+ * INFORMER_FROM_INF), leaving hand-set ones alone. Only INFORMER_API_KEY and
48
+ * INFORMER_URL are ever removed, whatever else the marker names.
49
+ *
50
+ * @param {Object} [env] - process.env, or a stand-in
51
+ */
52
+ export function forgetSignedIn(env = process.env) {
53
+ // Only these two: a hand-written marker in .env must not delete PATH or HOME
54
+ for (const key of String(env[FROM_INF] || '').split(',').filter((k) => FILLABLE.includes(k))) delete env[key];
55
+ delete env[FROM_INF];
56
+ }
57
+
58
+ /**
59
+ * The environment `inf` runs with: `env` without the credential variables
60
+ * the CLI would take over its own sign-in, nor the ones the plugin filled.
61
+ */
62
+ function infEnv(env) {
63
+ const child = { ...env };
64
+ forgetSignedIn(child);
65
+ delete child.INFORMER_API_KEY;
66
+ delete child.INFORMER_TOKEN;
67
+ return child;
68
+ }
69
+
70
+ /**
71
+ * The command line for cmd.exe, which a `.cmd` shim needs: one string with
72
+ * each argument quoted unless it is plainly safe, so `&`, `^` or `|` in a
73
+ * URL stays inside its argument.
74
+ */
75
+ function winCommand(args) {
76
+ return [INF, ...args]
77
+ .map((arg) => (/^[\w.:/=@-]+$/.test(arg) ? arg : `"${arg.replace(/"/g, '""')}"`))
78
+ .join(' ');
79
+ }
80
+
81
+ /**
82
+ * Why `inf auth token` gave no sign-in, as a line to show the person.
83
+ */
84
+ function failureReason(err, timeoutMs) {
85
+ if (err.code === 'ENOENT') {
86
+ return 'The Informer CLI (inf) is not installed. Install it with npm install -g @entrinsik/informer-cli, then run inf login <your-informer-url>.';
87
+ }
88
+ if (err.killed) return `inf auth token did not answer within ${Math.round(timeoutMs / 1000)} s.`;
89
+ const stderr = String(err.stderr || '').trim();
90
+ if (stderr) return stderr;
91
+ return `inf auth token failed${typeof err.code === 'number' ? ` (exit ${err.code})` : ''}: ${err.message}`;
92
+ }
93
+
94
+ /**
95
+ * The CLI's sign-in for `url` (or its current one), or the reason there is
96
+ * none: the CLI's own message when it exits non-zero (nobody signed in, the
97
+ * sign-in expired, an `inf` too old for `auth token`), that `inf` is not
98
+ * installed, or that it timed out.
99
+ *
100
+ * @param {Object} [opts]
101
+ * @param {string} [opts.url] - the server to find the sign-in for
102
+ * @param {Object} [opts.env] - the environment to run `inf` from, minus its credential variables
103
+ * @param {Function} [opts.execFile] - promisified child_process.execFile, for tests
104
+ * @param {string} [opts.platform] - process.platform, for tests
105
+ * @returns {Promise<{ url: string, token: string, expiresAt: number|null, scope: string|null }|{ error: string }>}
106
+ */
107
+ export async function signedInCredentials({ url, env = process.env, execFile = promisify(execFileCb), platform = process.platform, timeoutMs = 15000 } = {}) {
108
+ const args = ['auth', 'token', '--json', ...(url ? ['--url', url] : [])];
109
+ const options = { timeout: timeoutMs, env: infEnv(env) };
110
+ let stdout;
111
+ try {
112
+ ({ stdout } = platform === 'win32'
113
+ ? await execFile(winCommand(args), [], { ...options, shell: true })
114
+ : await execFile(INF, args, options));
115
+ } catch (err) {
116
+ return { error: failureReason(err, timeoutMs) };
117
+ }
118
+ let parsed = null;
119
+ try {
120
+ parsed = JSON.parse(String(stdout).trim());
121
+ } catch {
122
+ // answered below
123
+ }
124
+ if (!parsed || !parsed.token || !parsed.url) {
125
+ return { error: 'inf auth token did not print a sign-in. Update the Informer CLI with npm install -g @entrinsik/informer-cli.' };
126
+ }
127
+ // the token goes to INFORMER_URL, so it must be that server's own
128
+ if (url && originOf(parsed.url) !== originOf(url)) {
129
+ return { error: `inf auth token answered with a sign-in for ${parsed.url}, not INFORMER_URL (${url}). Run inf login ${url}.` };
130
+ }
131
+ return parsed;
132
+ }
133
+
134
+ function originOf(url) {
135
+ try {
136
+ return new URL(url).origin;
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+
142
+ const hasScope = (scope, id) => String(scope || '').split(' ').includes(id);
143
+
144
+ /**
145
+ * Fill INFORMER_URL and INFORMER_API_KEY from the CLI's sign-in when the
146
+ * environment has no credential of its own.
147
+ *
148
+ * @param {Object} [env] - process.env, or a stand-in
149
+ * @param {Object} [opts] - for signedInCredentials
150
+ * @returns {Promise<{ source: 'env'|'inf'|null, expiresAt?: number|null, reason?: string }>}
151
+ * `inf` when the CLI's sign-in filled them, `env` when a credential was
152
+ * already set (with or without INFORMER_URL), null with the reason when
153
+ * there is neither
154
+ */
155
+ export async function useSignedIn(env = process.env, opts = {}) {
156
+ forgetSignedIn(env);
157
+ if (hasOwnCredentials(env)) return { source: 'env' };
158
+ const signedIn = await signedInCredentials({ url: env.INFORMER_URL, env, ...opts });
159
+ if (signedIn.error) return { source: null, reason: signedIn.error };
160
+ if (signedIn.scope && !hasScope(signedIn.scope, 'develop')) {
161
+ return {
162
+ source: null,
163
+ reason: `Your sign-in for ${new URL(signedIn.url).host} can't deploy apps. That needs the API Token Creation permission; ask an administrator, then run inf login again.`
164
+ };
165
+ }
166
+ const filled = ['INFORMER_API_KEY'];
167
+ if (!env.INFORMER_URL) {
168
+ env.INFORMER_URL = signedIn.url;
169
+ filled.push('INFORMER_URL');
170
+ }
171
+ env.INFORMER_API_KEY = signedIn.token;
172
+ env[FROM_INF] = filled.join(',');
173
+ return { source: 'inf', expiresAt: signedIn.expiresAt || null };
174
+ }
175
+
176
+ /**
177
+ * The dev server's Authorization header as a function, renewed from the CLI
178
+ * before its token runs out. A failed renewal keeps the old expiry, so the
179
+ * next check asks again; the first failure in a row is warned with the CLI's
180
+ * reason. `stop()` ends the renewal.
181
+ *
182
+ * @param {string} header - the header to start with
183
+ * @param {Object} opts
184
+ * @param {number|null} opts.expiresAt - when the current token expires
185
+ * @param {string} opts.url - the server, to ask the CLI about
186
+ * @param {Object} [opts.env] - the environment whose INFORMER_API_KEY follows the renewed token
187
+ * @returns {{ get: () => string, stop: () => void }}
188
+ */
189
+ export function refreshingHeader(header, { expiresAt, url, env = process.env, now = Date.now, ...opts }) {
190
+ let current = header;
191
+ let expiry = expiresAt;
192
+ let renewing = false;
193
+ let warned = false;
194
+ const timer = setInterval(async () => {
195
+ if (renewing || !expiry || expiry - now() > RENEW_MARGIN_MS) return;
196
+ renewing = true;
197
+ try {
198
+ const signedIn = await signedInCredentials({ url, env, ...opts });
199
+ if (signedIn.error) {
200
+ if (!warned) console.warn(`[informer] Could not renew the dev server's inf sign-in; retrying every minute. ${signedIn.error}`);
201
+ warned = true;
202
+ return;
203
+ }
204
+ warned = false;
205
+ current = `Bearer ${signedIn.token}`;
206
+ expiry = signedIn.expiresAt || null;
207
+ env.INFORMER_API_KEY = signedIn.token;
208
+ } finally {
209
+ renewing = false;
210
+ }
211
+ }, CHECK_EVERY_MS);
212
+ if (timer.unref) timer.unref();
213
+ return { get: () => current, stop: () => clearInterval(timer) };
214
+ }