velocious 1.0.576 → 1.0.577

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 (62) hide show
  1. package/README.md +46 -1
  2. package/build/background-jobs/main.js +13 -2
  3. package/build/background-jobs/scheduler.js +11 -7
  4. package/build/background-jobs/store.js +18 -13
  5. package/build/environment-handlers/node/cli/commands/test.js +2 -0
  6. package/build/environment-handlers/node/source-peer-package.js +172 -0
  7. package/build/routes/resolver.js +3 -50
  8. package/build/src/background-jobs/main.d.ts.map +1 -1
  9. package/build/src/background-jobs/main.js +13 -3
  10. package/build/src/background-jobs/scheduler.d.ts +2 -2
  11. package/build/src/background-jobs/scheduler.d.ts.map +1 -1
  12. package/build/src/background-jobs/scheduler.js +11 -8
  13. package/build/src/background-jobs/store.d.ts +5 -4
  14. package/build/src/background-jobs/store.d.ts.map +1 -1
  15. package/build/src/background-jobs/store.js +17 -12
  16. package/build/src/environment-handlers/node/cli/commands/test.d.ts.map +1 -1
  17. package/build/src/environment-handlers/node/cli/commands/test.js +3 -1
  18. package/build/src/environment-handlers/node/source-peer-package.d.ts +46 -0
  19. package/build/src/environment-handlers/node/source-peer-package.d.ts.map +1 -0
  20. package/build/src/environment-handlers/node/source-peer-package.js +148 -0
  21. package/build/src/routes/resolver.d.ts.map +1 -1
  22. package/build/src/routes/resolver.js +4 -45
  23. package/build/tsconfig.tsbuildinfo +1 -1
  24. package/package.json +2 -1
  25. package/scripts/run-tests.js +61 -20
  26. package/scripts/test-browser.js +6 -1
  27. package/src/background-jobs/main.js +13 -2
  28. package/src/background-jobs/scheduler.js +11 -7
  29. package/src/background-jobs/store.js +18 -13
  30. package/src/environment-handlers/node/cli/commands/test.js +2 -0
  31. package/src/environment-handlers/node/source-peer-package.js +172 -0
  32. package/src/routes/resolver.js +3 -50
  33. package/build/deployment-api/controller.js +0 -437
  34. package/build/deployment-api/index.js +0 -210
  35. package/build/deployment-api/path-matcher.js +0 -45
  36. package/build/deployment-api/registry.js +0 -84
  37. package/build/deployment-api/run-store.js +0 -798
  38. package/build/deployment-api/sanitize.js +0 -114
  39. package/build/src/deployment-api/controller.d.ts +0 -117
  40. package/build/src/deployment-api/controller.d.ts.map +0 -1
  41. package/build/src/deployment-api/controller.js +0 -384
  42. package/build/src/deployment-api/index.d.ts +0 -46
  43. package/build/src/deployment-api/index.d.ts.map +0 -1
  44. package/build/src/deployment-api/index.js +0 -178
  45. package/build/src/deployment-api/path-matcher.d.ts +0 -31
  46. package/build/src/deployment-api/path-matcher.d.ts.map +0 -1
  47. package/build/src/deployment-api/path-matcher.js +0 -39
  48. package/build/src/deployment-api/registry.d.ts +0 -106
  49. package/build/src/deployment-api/registry.d.ts.map +0 -1
  50. package/build/src/deployment-api/registry.js +0 -74
  51. package/build/src/deployment-api/run-store.d.ts +0 -402
  52. package/build/src/deployment-api/run-store.d.ts.map +0 -1
  53. package/build/src/deployment-api/run-store.js +0 -711
  54. package/build/src/deployment-api/sanitize.d.ts +0 -27
  55. package/build/src/deployment-api/sanitize.d.ts.map +0 -1
  56. package/build/src/deployment-api/sanitize.js +0 -100
  57. package/src/deployment-api/controller.js +0 -437
  58. package/src/deployment-api/index.js +0 -210
  59. package/src/deployment-api/path-matcher.js +0 -45
  60. package/src/deployment-api/registry.js +0 -84
  61. package/src/deployment-api/run-store.js +0 -798
  62. package/src/deployment-api/sanitize.js +0 -114
@@ -18,39 +18,6 @@ function normalizeActionName(actionName) {
18
18
  return inflection.camelize(actionName.replaceAll("-", "_").replaceAll("/", "_"), true)
19
19
  }
20
20
 
21
- /**
22
- * Runs missing module specifier from error.
23
- * @param {Error} error - Import error.
24
- * @returns {string | undefined} - Missing module specifier from an ERR_MODULE_NOT_FOUND message.
25
- */
26
- function missingModuleSpecifierFromError(error) {
27
- const firstLine = error.message.split("\n")[0] || ""
28
- const match = firstLine.match(/^Cannot find (?:module|package) ['"](.+?)['"] imported from /)
29
-
30
- return match?.[1]
31
- }
32
-
33
- /**
34
- * Runs is missing target module error.
35
- * @param {object} args - Arguments.
36
- * @param {Error} args.error - Import error.
37
- * @param {string} args.targetPath - Target controller path.
38
- * @param {string} args.targetImportSpecifier - Target controller import specifier.
39
- * @returns {boolean} - True when the missing module is the target controller file.
40
- */
41
- function isMissingTargetModuleError({error, targetPath, targetImportSpecifier}) {
42
- const ensuredError = ensureError(error)
43
- const isModuleNotFoundError = "code" in ensuredError && ensuredError.code === "ERR_MODULE_NOT_FOUND"
44
-
45
- if (!isModuleNotFoundError) return false
46
-
47
- const missingSpecifier = missingModuleSpecifierFromError(ensuredError)
48
-
49
- if (!missingSpecifier) return false
50
-
51
- return missingSpecifier === targetPath || missingSpecifier === targetImportSpecifier
52
- }
53
-
54
21
  export default class VelociousRoutesResolver {
55
22
  /**
56
23
  * Narrows the runtime value to the documented type.
@@ -274,25 +241,11 @@ export default class VelociousRoutesResolver {
274
241
  * @returns {Promise<typeof import("../controller.js").default>} - The resolved controller class.
275
242
  */
276
243
  async resolveControllerClass({controllerPath}) {
277
- const controllerImportSpecifier = toImportSpecifier(controllerPath)
244
+ if (this.routeHookControllerClass) return this.routeHookControllerClass
278
245
 
279
- if (!this.routeHookControllerClass) {
280
- return /** @type {typeof import("../controller.js").default} */ ((await import(controllerImportSpecifier)).default)
281
- }
282
-
283
- try {
284
- return /** @type {typeof import("../controller.js").default} */ ((await import(controllerImportSpecifier)).default)
285
- } catch (error) {
286
- const isMissingControllerFileError = isMissingTargetModuleError({
287
- error: ensureError(error),
288
- targetImportSpecifier: controllerImportSpecifier,
289
- targetPath: controllerPath
290
- })
291
-
292
- if (!isMissingControllerFileError) throw ensureError(error)
246
+ const controllerImportSpecifier = toImportSpecifier(controllerPath)
293
247
 
294
- return /** @type {typeof import("../controller.js").default} */ (this.routeHookControllerClass)
295
- }
248
+ return /** @type {typeof import("../controller.js").default} */ ((await import(controllerImportSpecifier)).default)
296
249
  }
297
250
 
298
251
  /**
@@ -1,437 +0,0 @@
1
- // @ts-check
2
-
3
- import Controller from "../controller.js"
4
- import DeploymentRunStore, {registerActiveDeploymentRun, unregisterActiveDeploymentRun} from "./run-store.js"
5
- import {bearerToken, constantTimeEqual} from "../utils/bearer-token.js"
6
- import {getDeploymentMount} from "./registry.js"
7
- import {sanitizeAdapterValue, sanitizeErrorPayload} from "./sanitize.js"
8
-
9
- const REVISION_PATTERN = /^[0-9a-f]{40}$/
10
- const MAX_IDEMPOTENCY_KEY_LENGTH = 255
11
-
12
- /**
13
- * Resolves allowlisted stage options with own-property checks only, so
14
- * request-controlled names like "__proto__" or "constructor" can never
15
- * resolve inherited values. The normalized maps are also null-prototype, so
16
- * this is defense in depth.
17
- * @param {import("./registry.js").DeploymentMountOptions} options - Mount options.
18
- * @param {string} project - Requested project identifier.
19
- * @param {string} stage - Requested stage identifier.
20
- * @returns {import("./registry.js").DeploymentStageOptions | undefined} - Stage options when allowlisted.
21
- */
22
- function lookupStageOptions(options, project, stage) {
23
- if (!Object.hasOwn(options.projects, project)) return undefined
24
-
25
- const stages = options.projects[project].stages
26
-
27
- if (!Object.hasOwn(stages, stage)) return undefined
28
-
29
- return stages[stage]
30
- }
31
-
32
- /**
33
- * Authenticated HTTP API for callable deployments. Mounted by
34
- * {@link import("./index.js").default} as a route-resolver hook so it can ship
35
- * inside the velocious package. Every action is gated by a bearer-token check
36
- * against the configured access tokens; the API exposes only allowlisted
37
- * project/stage pairs and full immutable revisions, and delegates all
38
- * execution to the configured adapter. It never accepts commands, paths,
39
- * arbitrary refs, environment variables, or raw log output.
40
- */
41
- export default class VelociousDeploymentApiController extends Controller {
42
- /**
43
- * Runs mount options.
44
- * @returns {import("./registry.js").DeploymentMountOptions} - Options for the mount that matched this request.
45
- */
46
- _mountOptions() {
47
- const at = /** @type {string} */ (this.params().velociousDeploymentMountAt)
48
- const options = getDeploymentMount(this.getConfiguration(), at)
49
-
50
- if (!options) throw new Error(`No deployment API mount registered at ${at}`)
51
-
52
- return options
53
- }
54
-
55
- /**
56
- * Runs store.
57
- * @returns {DeploymentRunStore} - Run store scoped to the mount's database.
58
- */
59
- _store() {
60
- if (!this._deploymentRunStore) {
61
- this._deploymentRunStore = new DeploymentRunStore({
62
- configuration: this.getConfiguration(),
63
- databaseIdentifier: this._mountOptions().databaseIdentifier,
64
- mountIdentifier: this._mountOptions().mountIdentifier,
65
- staleRunTimeoutMs: this._mountOptions().staleRunTimeoutMs
66
- })
67
- }
68
-
69
- return this._deploymentRunStore
70
- }
71
-
72
- /**
73
- * Reports one internally consumed framework failure on both documented
74
- * error channels so framework-specific and unified reporters see the same
75
- * payload.
76
- * @param {object} args - Options.
77
- * @param {string} args.context - Deployment API failure context.
78
- * @param {?} args.error - Consumed error.
79
- * @returns {void} - No return value.
80
- */
81
- _emitFrameworkError({context, error}) {
82
- const errorEvents = this.getConfiguration().getErrorEvents()
83
- const payload = {context, error, request: this.getRequest()}
84
-
85
- errorEvents.emit("framework-error", payload)
86
- errorEvents.emit("all-error", {...payload, errorType: "framework-error"})
87
- }
88
-
89
- /**
90
- * Authorizes the request with a constant-time bearer-token comparison and
91
- * runs the action body only when authorized. Renders a 401 otherwise. The
92
- * base controller has no before-action halting, so authorization is enforced
93
- * here per action. Tokens are only accepted through the Authorization header
94
- * — never through URLs — and are never rendered back.
95
- * @param {() => Promise<void>} actionFn - Action body.
96
- * @returns {Promise<void>} - Resolves when complete.
97
- */
98
- async _respond(actionFn) {
99
- const token = bearerToken(this.request())
100
- let authorized = false
101
-
102
- if (token) {
103
- for (const accessToken of this._mountOptions().accessTokens) {
104
- if (constantTimeEqual(token, accessToken)) {
105
- authorized = true
106
- break
107
- }
108
- }
109
- }
110
-
111
- if (!authorized) {
112
- await this.render({json: {error: "unauthorized"}, status: 401})
113
- return
114
- }
115
-
116
- await actionFn()
117
- }
118
-
119
- /**
120
- * Creates a deployment run for an allowlisted project/stage and a full
121
- * immutable revision reachable from the approved release branch. Idempotent:
122
- * a retried idempotency key reads the original run, a reused key with a
123
- * different payload conflicts, and an active run for the same project/stage
124
- * returns a bounded conflict.
125
- * @returns {Promise<void>} - Resolves when complete.
126
- */
127
- async create() {
128
- await this._respond(async () => {
129
- const params = this.params()
130
- const revision = typeof params.revision === "string" ? params.revision : null
131
- const idempotencyKey = typeof params.idempotencyKey === "string" ? params.idempotencyKey : null
132
- const invalidFields = []
133
-
134
- if (!revision || !REVISION_PATTERN.test(revision)) invalidFields.push("revision")
135
- if (!idempotencyKey || idempotencyKey.length === 0 || idempotencyKey.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
136
- invalidFields.push("idempotencyKey")
137
- }
138
-
139
- if (invalidFields.length > 0) {
140
- await this.render({json: {error: "invalid_params", fields: invalidFields}, status: 422})
141
- return
142
- }
143
-
144
- const options = this._mountOptions()
145
- const project = typeof params.project === "string" ? params.project : ""
146
- const stage = typeof params.stage === "string" ? params.stage : ""
147
- const stageOptions = lookupStageOptions(options, project, stage)
148
-
149
- if (!stageOptions) {
150
- await this.render({json: {error: "not_found"}, status: 404})
151
- return
152
- }
153
-
154
- const store = this._store()
155
- const validRevision = /** @type {string} */ (revision)
156
- const validIdempotencyKey = /** @type {string} */ (idempotencyKey)
157
-
158
- // Retries read the original run before anything else — a replay must
159
- // never re-validate or re-deploy.
160
- const existingRun = await store.findRunByKey(validIdempotencyKey)
161
-
162
- if (existingRun) {
163
- await this._renderExistingRun({existingRun, project, revision: validRevision, stage})
164
- return
165
- }
166
-
167
- const reachable = await options.adapter.validateRevision({
168
- configuration: this.getConfiguration(),
169
- project,
170
- releaseBranch: stageOptions.releaseBranch,
171
- revision: validRevision,
172
- stage
173
- })
174
-
175
- if (!reachable) {
176
- await this.render({json: {error: "revision_not_reachable"}, status: 422})
177
- return
178
- }
179
-
180
- const outcome = await store.createRunIfPossible({
181
- idempotencyKey: validIdempotencyKey,
182
- project,
183
- revision: validRevision,
184
- stage
185
- })
186
-
187
- if (outcome.outcome === "replay" || outcome.outcome === "conflict") {
188
- const existingFromStore = outcome.run
189
-
190
- if (!existingFromStore) throw new Error(`Deployment run store reported '${outcome.outcome}' without a run`)
191
-
192
- await this._renderExistingRun({existingRun: existingFromStore, project, revision: validRevision, stage})
193
- return
194
- }
195
-
196
- if (outcome.outcome === "in_progress") {
197
- const activeRun = outcome.run
198
-
199
- await this.render({json: {error: "deployment_in_progress", runId: activeRun ? activeRun.id : undefined}, status: 409})
200
- return
201
- }
202
-
203
- if (outcome.outcome === "reconciliation_required") {
204
- const blockedRun = outcome.run
205
-
206
- if (!blockedRun) throw new Error("Deployment run store reported 'reconciliation_required' without a run")
207
-
208
- await this.render({json: {error: "deployment_reconciliation_required", runId: blockedRun.id}, status: 409})
209
- return
210
- }
211
-
212
- const run = outcome.run
213
-
214
- if (!run) throw new Error("Deployment run store reported 'created' without a run")
215
-
216
- await this._audit({event: "run_requested", payload: {project, revision: validRevision, stage}, runId: run.id})
217
-
218
- // Execution is deliberately not awaited: the deploy runs under the
219
- // integration's own lock/build/health/rollback semantics and the caller
220
- // reads progress back through the show action.
221
- this._executeRun({options, run}).catch((error) => {
222
- this._emitFrameworkError({context: "deployment-api-execute-run", error})
223
- })
224
-
225
- await this.render({json: {run: this._serializeRun(run)}, status: 202})
226
- })
227
- }
228
-
229
- /**
230
- * Renders a previously created run for an idempotency-key hit: a replay when
231
- * the payload matches, a bounded conflict when it doesn't.
232
- * @param {object} args - Options.
233
- * @param {import("./run-store.js").DeploymentRunRow} args.existingRun - The stored run.
234
- * @param {string} args.project - Requested project.
235
- * @param {string} args.revision - Requested revision.
236
- * @param {string} args.stage - Requested stage.
237
- * @returns {Promise<void>} - Resolves when complete.
238
- */
239
- async _renderExistingRun({existingRun, project, revision, stage}) {
240
- const samePayload = existingRun.project === project && existingRun.stage === stage && existingRun.revision === revision
241
-
242
- if (!samePayload) {
243
- await this.render({json: {error: "idempotency_conflict", runId: existingRun.id}, status: 409})
244
- return
245
- }
246
-
247
- await this.render({json: {replayed: true, run: this._serializeRun(existingRun)}, status: 200})
248
- }
249
-
250
- /**
251
- * Returns the bounded state of a single run, enriched with the adapter's
252
- * live status when the integration provides one.
253
- * @returns {Promise<void>} - Resolves when complete.
254
- */
255
- async show() {
256
- await this._respond(async () => {
257
- const run = await this._store().findRunById(/** @type {string} */ (this.params().id))
258
-
259
- if (!run) {
260
- await this.render({json: {error: "not_found"}, status: 404})
261
- return
262
- }
263
-
264
- const options = this._mountOptions()
265
- /** @type {Record<string, ?>} */
266
- const body = {run: this._serializeRun(run)}
267
-
268
- if (options.adapter.readStatus) {
269
- const liveStatus = await options.adapter.readStatus({
270
- configuration: this.getConfiguration(),
271
- project: run.project,
272
- stage: run.stage
273
- })
274
-
275
- body.current = sanitizeAdapterValue(liveStatus, options.accessTokens) ?? null
276
- }
277
-
278
- await this.render({json: body, status: 200})
279
- })
280
- }
281
-
282
- /**
283
- * Executes a created run asynchronously: registers it as active in this
284
- * process, marks it running, heartbeats its ownership lease while the
285
- * adapter deploys, and records the sanitized outcome. A deployment failure
286
- * is an expected operational result — it is persisted with its sanitized
287
- * recovery information instead of being raised, so it stays visible through
288
- * readback and audit rather than crashing the worker.
289
- * @param {object} args - Options.
290
- * @param {import("./registry.js").DeploymentMountOptions} args.options - Mount options.
291
- * @param {import("./run-store.js").DeploymentRunRow} args.run - The created run.
292
- * @returns {Promise<void>} - Resolves when the outcome is recorded.
293
- */
294
- async _executeRun({options, run}) {
295
- const store = this._store()
296
- const secrets = options.accessTokens
297
- const stageOptions = lookupStageOptions(options, run.project, run.stage)
298
-
299
- if (!stageOptions) throw new Error(`Deployment run ${run.id} references non-allowlisted ${run.project}/${run.stage}`)
300
- if (!run.ownerToken) throw new Error(`Deployment run ${run.id} has no execution owner token`)
301
-
302
- const ownerToken = run.ownerToken
303
-
304
- registerActiveDeploymentRun(run.id)
305
-
306
- /** @type {ReturnType<typeof setInterval> | null} */
307
- let heartbeatTimer = null
308
-
309
- try {
310
- await store.markRunning({id: run.id, startedAtMs: Date.now()})
311
-
312
- // Renew the ownership lease while the deploy runs so reconciliation
313
- // never reclaims this genuinely active run; unref'd so the timer alone
314
- // keeps no process alive.
315
- const heartbeatIntervalMs = Math.max(1000, Math.floor(options.staleRunTimeoutMs / 4))
316
-
317
- heartbeatTimer = setInterval(() => {
318
- store.heartbeat({heartbeatAtMs: Date.now(), id: run.id}).catch((error) => {
319
- this._emitFrameworkError({context: "deployment-api-heartbeat", error})
320
- })
321
- }, heartbeatIntervalMs)
322
- heartbeatTimer.unref()
323
-
324
- await this._audit({event: "run_started", payload: {project: run.project, revision: run.revision, stage: run.stage}, runId: run.id})
325
-
326
- let report
327
-
328
- try {
329
- report = await options.adapter.deploy({
330
- configuration: this.getConfiguration(),
331
- project: run.project,
332
- releaseBranch: stageOptions.releaseBranch,
333
- revision: run.revision,
334
- runId: run.id,
335
- stage: run.stage
336
- })
337
- } catch (error) {
338
- const errorPayload = sanitizeErrorPayload(error, secrets)
339
-
340
- try {
341
- await store.markFailed({error: errorPayload, finishedAtMs: Date.now(), id: run.id, ownerToken})
342
- await this._audit({
343
- event: "run_failed",
344
- payload: {message: errorPayload.message, project: run.project, revision: run.revision, stage: run.stage},
345
- runId: run.id
346
- })
347
- } catch (storeError) {
348
- // Recording the failure itself failed — that is an unexpected bug
349
- // and must surface to process-level error reporters.
350
- this._emitFrameworkError({context: "deployment-api-record-failure", error: storeError})
351
- }
352
-
353
- return
354
- }
355
-
356
- try {
357
- const result = sanitizeAdapterValue(report ?? {}, secrets) ?? {}
358
-
359
- await store.markSucceeded({finishedAtMs: Date.now(), id: run.id, ownerToken, result})
360
- await this._audit({event: "run_succeeded", payload: {project: run.project, revision: run.revision, stage: run.stage}, runId: run.id})
361
- } catch (error) {
362
- // The adapter already returned success. Surface the recording error,
363
- // then fence the run in a durable non-retryable state rather than
364
- // falsely recording an external success as a deployment failure.
365
- this._emitFrameworkError({context: "deployment-api-record-success", error})
366
-
367
- const reconciliationError = {
368
- message: "Deployment activation succeeded, but its result could not be persisted; operator reconciliation is required"
369
- }
370
-
371
- try {
372
- await store.markReconciliationRequired({
373
- error: reconciliationError,
374
- finishedAtMs: Date.now(),
375
- id: run.id,
376
- ownerToken
377
- })
378
- await this._audit({
379
- event: "run_reconciliation_required",
380
- payload: {message: reconciliationError.message, project: run.project, revision: run.revision, stage: run.stage},
381
- runId: run.id
382
- })
383
- } catch (reconciliationErrorPersistenceError) {
384
- this._emitFrameworkError({
385
- context: "deployment-api-record-reconciliation-required",
386
- error: reconciliationErrorPersistenceError
387
- })
388
- }
389
- }
390
- } finally {
391
- if (heartbeatTimer) clearInterval(heartbeatTimer)
392
- unregisterActiveDeploymentRun(run.id)
393
- }
394
- }
395
-
396
- /**
397
- * Records a sanitized audit event. Audit persistence must never strand or
398
- * suppress a deployment, so a failure here is reported on the
399
- * framework-error and unified all-error channels (where process-level bug
400
- * reporters capture it), and execution continues.
401
- * @param {object} args - Options.
402
- * @param {string} args.event - Event name.
403
- * @param {Record<string, ?>} args.payload - Payload; sanitized and redacted before persistence.
404
- * @param {string | null} args.runId - Owning run id.
405
- * @returns {Promise<void>} - Resolves when recorded or reported.
406
- */
407
- async _audit({event, payload, runId}) {
408
- const sanitized = sanitizeAdapterValue(payload, this._mountOptions().accessTokens) ?? {}
409
-
410
- try {
411
- await this._store().addAuditEvent({event, payload: sanitized, runId})
412
- } catch (error) {
413
- this._emitFrameworkError({context: "deployment-api-audit", error})
414
- }
415
- }
416
-
417
- /**
418
- * Serializes a run for the API.
419
- * @param {import("./run-store.js").DeploymentRunRow} run - Run row.
420
- * @returns {Record<string, ?>} - Serialized run.
421
- */
422
- _serializeRun(run) {
423
- return {
424
- error: run.error,
425
- finishedAtMs: run.finishedAtMs,
426
- id: run.id,
427
- idempotencyKey: run.idempotencyKey,
428
- project: run.project,
429
- requestedAtMs: run.requestedAtMs,
430
- result: run.result,
431
- revision: run.revision,
432
- stage: run.stage,
433
- startedAtMs: run.startedAtMs,
434
- status: run.status
435
- }
436
- }
437
- }