@entrinsik/vite-plugin-informer 2.14.0-beta.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/bin/deploy.js CHANGED
@@ -9,7 +9,7 @@ import { useSignedIn } from '../src/signed-in.js';
9
9
  const mode = parseModeArg(process.argv);
10
10
  loadEnv({ mode });
11
11
  // No credential in the environment or .env: use the inf CLI's sign-in
12
- await useSignedIn(process.env);
12
+ const signedIn = await useSignedIn(process.env);
13
13
 
14
14
  const baseUrl = process.env.INFORMER_URL;
15
15
  const apiKey = process.env.INFORMER_API_KEY;
@@ -17,9 +17,15 @@ const user = process.env.INFORMER_USER;
17
17
  const pass = process.env.INFORMER_PASS;
18
18
 
19
19
  if (!baseUrl || (!apiKey && (!user || !pass))) {
20
- console.error('Not signed in to an Informer server.');
21
- console.error('Sign in once with the Informer CLI (npm install -g @entrinsik/informer-cli):');
22
- console.error(' inf login <your-informer-url>');
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
+ }
23
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
  }
package/bin/init.js CHANGED
@@ -241,7 +241,7 @@ async function init() {
241
241
 
242
242
  console.log('\nSetup complete!\n');
243
243
  console.log('Next steps:');
244
- 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)');
245
245
  console.log(' 2. Declare your data dependencies in informer.yaml (see comments inside)');
246
246
  console.log(' 3. Run: npm install');
247
247
  console.log(' 4. Run: npm run dev');
package/bin/workspace.js CHANGED
@@ -28,15 +28,17 @@ if (!command || !['init', 'migrate', 'reset'].includes(command)) {
28
28
  }
29
29
 
30
30
  // No credential in the environment or .env: use the inf CLI's sign-in
31
- await useSignedIn(process.env);
31
+ const signedIn = await useSignedIn(process.env);
32
32
  const baseUrl = process.env.INFORMER_URL;
33
33
  const apiKey = process.env.INFORMER_API_KEY;
34
34
  const user = process.env.INFORMER_USER;
35
35
  const pass = process.env.INFORMER_PASS;
36
36
 
37
37
  if (!baseUrl || (!apiKey && (!user || !pass))) {
38
- console.error('Not signed in to an Informer server. Run inf login <your-informer-url>,');
39
- console.error('or set INFORMER_URL with INFORMER_API_KEY (or INFORMER_USER and 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.');
40
42
  process.exit(1);
41
43
  }
42
44
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entrinsik/vite-plugin-informer",
3
- "version": "2.14.0-beta.0",
3
+ "version": "2.14.0",
4
4
  "description": "Vite plugin and deploy tool for Informer App development",
5
5
  "scripts": {
6
6
  "test": "node --test",
package/src/compat.js CHANGED
@@ -23,7 +23,7 @@ export const FEATURE_FLOORS = Object.freeze({
23
23
  // The embedding pump: embeddings/ use cases and embed() on the handler bag.
24
24
  embeddings: '2026.1.3',
25
25
  // App CLI commands: cli/ handlers the installed Informer CLI runs.
26
- cli: '2026.1.4',
26
+ cli: '2026.2.0',
27
27
  // Staged uploads/downloads: the uploads/downloads services, /view/_uploads
28
28
  // and /view/_downloads, and __INFORMER__.upload() in the page.
29
29
  streams: '2026.1.3',
@@ -34,7 +34,9 @@ export const FEATURE_FLOORS = Object.freeze({
34
34
  // Server-side enforcement of the manifest's `requires:` block. Below this
35
35
  // floor the CLI is the only thing in the loop that can honour a declared
36
36
  // Informer floor, so it enforces it itself.
37
- requiresGate: '2026.1.3'
37
+ requiresGate: '2026.1.3',
38
+ // Outbound webhooks: `webhook: true` events delivered to registered endpoints.
39
+ webhooks: '2026.2.0'
38
40
  });
39
41
 
40
42
  /**
@@ -213,6 +215,12 @@ export function planDeploy({ server, files, manifest }) {
213
215
  + 'Nothing is relayed and broadcast() does not reach the page.'
214
216
  );
215
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
+ }
216
224
  if (!server.supports('streams') && uploaded.has('server')) {
217
225
  warnings.push(
218
226
  `${where} predates ${FEATURE_FLOORS.streams}: if a handler destructures uploads/downloads from its bag, or the page `
@@ -6,9 +6,11 @@
6
6
  * Every capability the dev server mirrors is on. `embeddings` is off by
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
- * `cli` is off for the same reason: cli/ commands run only once deployed.
10
9
  * Turning it on binds query-time `embed()` to a deployed app's `_embed` route
11
- * (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
12
14
  * `'dev'` (not semver) so a floor check treats the dev mirror as "unknown"
13
15
  * rather than as any particular release. `originMode` is on: the dev server
14
16
  * behaves like an app served from its own origin, where live channels work.
@@ -35,6 +37,9 @@ export const DEV_CAPABILITIES = Object.freeze({
35
37
  // channels/ files with config.actor: one live instance per channel (dev-channel-actors.js)
36
38
  channelActors: true,
37
39
  embeddings: false,
40
+ // the dev server neither serves anonymously (manifest `public:`) nor mirrors app sign-in
41
+ publicAccess: false,
42
+ accounts: false,
38
43
  // cli/ commands run only on a deployed app; the dev server does not mirror them
39
44
  cli: false
40
45
  });
package/src/index.js CHANGED
@@ -15,7 +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 { refreshingHeader, useSignedIn } from './signed-in.js';
18
+ import { forgetSignedIn, refreshingHeader, useSignedIn } from './signed-in.js';
19
19
 
20
20
  /**
21
21
  * The dev `window.__INFORMER__` context: defaults overlaid with the plugin's
@@ -143,6 +143,7 @@ async function writeAppDepTypes (projectRoot, dts) {
143
143
  * slots resolve their marketplace pin via installs dev doesn't have, so the
144
144
  * binding names the locally-installed app. See AppDevBinding in index.d.ts.
145
145
  * @param {Object} [options.proxy] - extra Vite proxy options merged onto /api.
146
+ * Its `configure` runs after the plugin's own, which sets Authorization.
146
147
  * @returns {import('vite').Plugin}
147
148
  */
148
149
  export default function informer(options = {}) {
@@ -156,12 +157,17 @@ export default function informer(options = {}) {
156
157
  // this is only needed under basic auth (INFORMER_USER/PASS).
157
158
  let appToken = null;
158
159
  let activeMode = null;
160
+ let renewed = null;
159
161
 
160
162
  return {
161
163
  name: 'vite-plugin-informer',
162
164
 
163
165
  async config(_, { command, mode }) {
164
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);
165
171
  loadEnv({ mode });
166
172
 
167
173
  isDev = command === 'serve';
@@ -181,7 +187,9 @@ export default function informer(options = {}) {
181
187
  devWorkspaceId = process.env.INFORMER_DEV_WORKSPACE || null;
182
188
  appToken = process.env.INFORMER_APP_TOKEN || null;
183
189
 
184
- if (baseUrl && !apiKey && !(user && pass)) {
190
+ if (signedIn.reason) {
191
+ console.warn(`[informer] ${signedIn.reason}`);
192
+ } else if (baseUrl && !apiKey && !(user && pass)) {
185
193
  console.warn('[informer] INFORMER_URL is set but there is no credential. Run inf login, or set INFORMER_API_KEY in .env.');
186
194
  }
187
195
  if (baseUrl) {
@@ -190,21 +198,24 @@ export default function informer(options = {}) {
190
198
  ? 'Bearer ' + apiKey
191
199
  : 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64');
192
200
  // the CLI's access token lasts 15 minutes, so a dev server renews it
193
- const renewed = signedIn.source === 'inf' ? refreshingHeader(header, { expiresAt: signedIn.expiresAt, url: serverOrigin }) : null;
201
+ renewed = signedIn.source === 'inf' ? refreshingHeader(header, { expiresAt: signedIn.expiresAt, url: serverOrigin }) : null;
194
202
  authHeader = renewed ? renewed.get : header;
203
+ const userConfigure = options.proxy && options.proxy.configure;
195
204
 
196
205
  cfg.server = {
197
206
  proxy: {
198
207
  '/api': {
199
208
  target: baseUrl,
200
209
  changeOrigin: true,
201
- // set per request, so a renewed header reaches the proxy
202
- configure: (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) => {
203
214
  proxy.on('proxyReq', (proxyReq) => {
204
215
  proxyReq.setHeader('Authorization', typeof authHeader === 'function' ? authHeader() : authHeader);
205
216
  });
206
- },
207
- ...options.proxy
217
+ if (typeof userConfigure === 'function') userConfigure(proxy, proxyOptions);
218
+ }
208
219
  },
209
220
  // NOTE: no /informer-api mount. The server
210
221
  // retired that spelling — /api is ONE namespace
@@ -220,6 +231,10 @@ export default function informer(options = {}) {
220
231
  },
221
232
 
222
233
  async configureServer(server) {
234
+ if (renewed && server.httpServer) {
235
+ const ending = renewed;
236
+ server.httpServer.on('close', () => ending.stop());
237
+ }
223
238
  if (!isDev || !serverOrigin) return;
224
239
 
225
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) {
package/src/signed-in.js CHANGED
@@ -10,9 +10,19 @@ import { promisify } from 'node:util';
10
10
  * the CLI: `inf auth token --json [--url $INFORMER_URL]` prints the signed-in
11
11
  * server and a current access token, refreshed by the CLI as needed. The
12
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 as
14
- * they always have. Running the CLI, rather than reading its files, keeps the
15
- * two packages' versions independent.
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.
16
26
  *
17
27
  * Access tokens from the CLI last 15 minutes; a dev server asks again before
18
28
  * one runs out (refreshingHeader). Credentials set by hand are never
@@ -20,6 +30,9 @@ import { promisify } from 'node:util';
20
30
  */
21
31
 
22
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'];
23
36
 
24
37
  // Ask again this long before the token's stated expiry
25
38
  const RENEW_MARGIN_MS = 3 * 60 * 1000;
@@ -30,71 +43,168 @@ export function hasOwnCredentials(env = process.env) {
30
43
  }
31
44
 
32
45
  /**
33
- * The CLI's sign-in for `url` (or its current one), or null when the CLI is
34
- * not installed, nobody is signed in, or the sign-in has run out.
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.
35
99
  *
36
100
  * @param {Object} [opts]
37
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
38
103
  * @param {Function} [opts.execFile] - promisified child_process.execFile, for tests
39
- * @returns {Promise<{ url: string, token: string, expiresAt: number|null, scope: string|null }|null>}
104
+ * @param {string} [opts.platform] - process.platform, for tests
105
+ * @returns {Promise<{ url: string, token: string, expiresAt: number|null, scope: string|null }|{ error: string }>}
40
106
  */
41
- export async function signedInCredentials({ url, execFile = promisify(execFileCb), timeoutMs = 15000 } = {}) {
107
+ export async function signedInCredentials({ url, env = process.env, execFile = promisify(execFileCb), platform = process.platform, timeoutMs = 15000 } = {}) {
42
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) {
43
135
  try {
44
- const { stdout } = await execFile(INF, args, { timeout: timeoutMs, shell: process.platform === 'win32' });
45
- const parsed = JSON.parse(String(stdout).trim());
46
- return parsed && parsed.token && parsed.url ? parsed : null;
136
+ return new URL(url).origin;
47
137
  } catch {
48
138
  return null;
49
139
  }
50
140
  }
51
141
 
142
+ const hasScope = (scope, id) => String(scope || '').split(' ').includes(id);
143
+
52
144
  /**
53
145
  * Fill INFORMER_URL and INFORMER_API_KEY from the CLI's sign-in when the
54
146
  * environment has no credential of its own.
55
147
  *
56
148
  * @param {Object} [env] - process.env, or a stand-in
57
149
  * @param {Object} [opts] - for signedInCredentials
58
- * @returns {Promise<{ source: 'env'|'inf'|null, expiresAt?: number|null }>}
59
- * `inf` when the CLI's sign-in filled them, `env` when they were already
60
- * set, null when there is neither
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
61
154
  */
62
155
  export async function useSignedIn(env = process.env, opts = {}) {
63
- if (env.INFORMER_URL && hasOwnCredentials(env)) return { source: 'env' };
64
- const signedIn = await signedInCredentials({ url: env.INFORMER_URL, ...opts });
65
- if (!signedIn) return { source: null };
66
- if (!env.INFORMER_URL) env.INFORMER_URL = signedIn.url;
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
+ }
67
171
  env.INFORMER_API_KEY = signedIn.token;
172
+ env[FROM_INF] = filled.join(',');
68
173
  return { source: 'inf', expiresAt: signedIn.expiresAt || null };
69
174
  }
70
175
 
71
176
  /**
72
177
  * The dev server's Authorization header as a function, renewed from the CLI
73
- * before its token runs out. `stop()` ends the renewal.
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.
74
181
  *
75
182
  * @param {string} header - the header to start with
76
183
  * @param {Object} opts
77
184
  * @param {number|null} opts.expiresAt - when the current token expires
78
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
79
187
  * @returns {{ get: () => string, stop: () => void }}
80
188
  */
81
- export function refreshingHeader(header, { expiresAt, url, now = Date.now, ...opts }) {
189
+ export function refreshingHeader(header, { expiresAt, url, env = process.env, now = Date.now, ...opts }) {
82
190
  let current = header;
83
191
  let expiry = expiresAt;
84
192
  let renewing = false;
193
+ let warned = false;
85
194
  const timer = setInterval(async () => {
86
195
  if (renewing || !expiry || expiry - now() > RENEW_MARGIN_MS) return;
87
196
  renewing = true;
88
197
  try {
89
- const signedIn = await signedInCredentials({ url, ...opts });
90
- if (signedIn) {
91
- current = `Bearer ${signedIn.token}`;
92
- expiry = signedIn.expiresAt || null;
93
- process.env.INFORMER_API_KEY = signedIn.token;
94
- } else {
95
- console.warn('[informer] Your inf sign-in has run out. Run inf login, then restart the dev server.');
96
- expiry = null;
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;
97
203
  }
204
+ warned = false;
205
+ current = `Bearer ${signedIn.token}`;
206
+ expiry = signedIn.expiresAt || null;
207
+ env.INFORMER_API_KEY = signedIn.token;
98
208
  } finally {
99
209
  renewing = false;
100
210
  }