@prisma/cli-engine 0.0.2 → 0.0.5

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/dist/testing.js CHANGED
@@ -1,14 +1,20 @@
1
- import { i as credentialsRequiredError, o as noSessionForWorkspaceError, t as buildEngine } from "./engine-vF4FiZqo.js";
1
+ import { g as noSessionForWorkspaceError, i as buildEngine, m as credentialsRequiredError, n as claimedIdentity, p as credentialWorkspaceMismatchError, r as credentialWorkspaceId, t as claimedExpiresAt } from "./token-claims-Bpb1vA2N.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  //#region src/in-memory-credential-manager.ts
4
4
  /**
5
5
  * A complete CredentialManager whose state lives in memory rather than
6
6
  * in a file. It implements the same rules as the file-backed one — the
7
- * pinned decision, upsert by workspace, idempotent removal, and the two
8
- * token storages — and adds a seed and a state read-back. Tests are
9
- * what it is mostly used for, which is why it ships from the ./testing
10
- * subpath alongside the JWT minter that produces tokens to seed it, but
11
- * nothing about it is a stub.
7
+ * pinned decision, upsert by workspace, idempotent removal, in-process
8
+ * single-flight refresh, and the two token storages — and adds a seed
9
+ * and a state read-back. Tests are what it is mostly used for, which is
10
+ * why it ships from the ./testing subpath alongside the JWT minter that
11
+ * produces tokens to seed it, but nothing about it is a stub.
12
+ *
13
+ * One rule it cannot carry: the blank-PRISMA_SERVICE_TOKEN refusal
14
+ * belongs to the file-backed manager, which reads the variable. This
15
+ * one is handed a credential, so a blank value has no representation
16
+ * here. That rule is covered end to end through the real environment
17
+ * in the CLI's own tests.
12
18
  */
13
19
  /** The SDK's Tokens requires a workspace id, so an environment
14
20
  * credential whose claims name no workspace is given this instead. It
@@ -23,34 +29,6 @@ function mintTestJwt(claims) {
23
29
  typ: "JWT"
24
30
  })}.${encode(claims)}.test-signature`;
25
31
  }
26
- function decodeJwtClaims(token) {
27
- const parts = token.split(".");
28
- if (parts.length < 2) return;
29
- try {
30
- const parsed = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
31
- return typeof parsed === "object" && parsed !== null ? parsed : void 0;
32
- } catch {
33
- return;
34
- }
35
- }
36
- function claimedWorkspaceId(token) {
37
- const workspaceId = decodeJwtClaims(token)?.workspace_id;
38
- return typeof workspaceId === "string" ? workspaceId : void 0;
39
- }
40
- function claimedExpiresAt(token) {
41
- const exp = decodeJwtClaims(token)?.exp;
42
- return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
43
- }
44
- function claimedIdentity(token) {
45
- const claims = decodeJwtClaims(token);
46
- const userId = typeof claims?.sub === "string" ? claims.sub : void 0;
47
- const email = typeof claims?.email === "string" ? claims.email : void 0;
48
- return userId === void 0 && email === void 0 ? void 0 : {
49
- userId,
50
- email,
51
- name: void 0
52
- };
53
- }
54
32
  function asSession(record) {
55
33
  return {
56
34
  workspaceId: record.workspaceId,
@@ -69,7 +47,7 @@ function storedActiveCredential(record) {
69
47
  }
70
48
  function environmentActiveCredential(credential) {
71
49
  return {
72
- workspaceId: claimedWorkspaceId(credential.token),
50
+ workspaceId: credentialWorkspaceId(credential.token),
73
51
  workspaceName: void 0,
74
52
  expiresAt: claimedExpiresAt(credential.token) ?? credential.expiresAt,
75
53
  identity: claimedIdentity(credential.token),
@@ -83,9 +61,9 @@ function environmentActiveCredential(credential) {
83
61
  * credential whose workspace matches a stored session therefore cannot
84
62
  * delete that session.
85
63
  */
86
- function memoryBackedStorage(credential) {
64
+ function memoryBackedStorage(credential, singleFlight) {
87
65
  let tokens = {
88
- workspaceId: claimedWorkspaceId(credential.token) ?? NO_WORKSPACE_CLAIMED,
66
+ workspaceId: credentialWorkspaceId(credential.token) ?? NO_WORKSPACE_CLAIMED,
89
67
  accessToken: credential.token,
90
68
  refreshToken: credential.refreshToken
91
69
  };
@@ -97,7 +75,7 @@ function memoryBackedStorage(credential) {
97
75
  clearTokens: async () => {
98
76
  tokens = null;
99
77
  },
100
- withRefreshLock: (fn) => fn()
78
+ withRefreshLock: (fn) => singleFlight(fn)
101
79
  };
102
80
  }
103
81
  /**
@@ -110,6 +88,10 @@ function memoryBackedStorage(credential) {
110
88
  * own tests.
111
89
  */
112
90
  var InMemoryCredentialManager = class {
91
+ /** §6 requires the refresh hook to serialise within a process. The
92
+ * file-backed manager runs this same queue; a harness that let two
93
+ * refreshes through would pass a test production would fail. */
94
+ #refreshLock = Promise.resolve();
113
95
  storedSessions;
114
96
  selection;
115
97
  environmentCredential;
@@ -120,11 +102,16 @@ var InMemoryCredentialManager = class {
120
102
  this.selection = seed.selectedWorkspaceId;
121
103
  this.environmentCredential = seed.environmentCredential;
122
104
  if (seed.credential !== void 0) {
123
- const workspaceId = claimedWorkspaceId(seed.credential.token);
105
+ const workspaceId = credentialWorkspaceId(seed.credential.token);
124
106
  if (workspaceId === void 0) throw new Error("@prisma/cli-engine/testing: the `credential` seed runs createSession's claims derivation — the token must be a JWT with `workspace_id` (use mintTestJwt)");
125
107
  this.applyCreateSession(seed.credential, workspaceId);
126
108
  }
127
109
  }
110
+ #singleFlight(fn) {
111
+ const queued = this.#refreshLock.then(fn, fn);
112
+ this.#refreshLock = queued.then(() => void 0, () => void 0);
113
+ return queued;
114
+ }
128
115
  state() {
129
116
  return {
130
117
  sessions: [...this.storedSessions],
@@ -176,9 +163,18 @@ var InMemoryCredentialManager = class {
176
163
  this.activeStorage ??= this.buildActiveStorage();
177
164
  return this.activeStorage;
178
165
  }
166
+ /** The spawn path's read: the active credential's access token,
167
+ * fresh on every call, never the refresh token. Null when there is
168
+ * no active credential to read — storage exists only once
169
+ * activeCredential() has returned non-null. */
170
+ async activeAccessToken() {
171
+ if (await this.activeCredential() === null) return null;
172
+ const tokens = await (await this.activeCredentialStorage()).getTokens();
173
+ return tokens === null ? null : tokens.accessToken;
174
+ }
179
175
  buildActiveStorage() {
180
176
  const pin = this.pin;
181
- if (pin.kind === "environment") return memoryBackedStorage(this.requireEnvironmentCredential());
177
+ if (pin.kind === "environment") return memoryBackedStorage(this.requireEnvironmentCredential(), (fn) => this.#singleFlight(fn));
182
178
  if (pin.kind === "session") return this.storedSessionStorage(pin.workspaceId);
183
179
  throw new Error("@prisma/cli-engine/testing: activeCredentialStorage() is only valid once activeCredential() has returned non-null");
184
180
  }
@@ -198,8 +194,8 @@ var InMemoryCredentialManager = class {
198
194
  },
199
195
  setTokens: async (tokens) => {
200
196
  if (pinnedRecord() === void 0) throw credentialsRequiredError("session-ended");
201
- const claimed = claimedWorkspaceId(tokens.accessToken);
202
- if (claimed !== void 0 && claimed !== workspaceId) throw new Error("@prisma/cli-engine/testing: a refreshed token's workspace_id claim disagrees with the pinned workspace — refresh cannot re-scope");
197
+ const claimed = credentialWorkspaceId(tokens.accessToken);
198
+ if (claimed !== void 0 && claimed !== workspaceId) throw credentialWorkspaceMismatchError(workspaceId);
203
199
  this.storedSessions = this.storedSessions.map((stored) => stored.workspaceId === workspaceId ? {
204
200
  ...stored,
205
201
  credential: {
@@ -217,7 +213,7 @@ var InMemoryCredentialManager = class {
217
213
  if (record === void 0 || tokens.workspaceId !== workspaceId || tokens.accessToken !== record.credential.token || tokens.refreshToken !== record.credential.refreshToken) return;
218
214
  this.removeRecord(workspaceId);
219
215
  },
220
- withRefreshLock: (fn) => fn()
216
+ withRefreshLock: (fn) => this.#singleFlight(fn)
221
217
  };
222
218
  }
223
219
  removeRecord(workspaceId) {
@@ -258,8 +254,8 @@ var InMemoryCredentialManager = class {
258
254
  return credential;
259
255
  }
260
256
  applyCreateSession(credential, workspaceId) {
261
- const claimed = claimedWorkspaceId(credential.token);
262
- if (claimed !== void 0 && claimed !== workspaceId) throw new Error("@prisma/cli-engine/testing: createSession's workspaceId argument disagrees with the credential's workspace_id claim");
257
+ const claimed = credentialWorkspaceId(credential.token);
258
+ if (claimed !== void 0 && claimed !== workspaceId) throw credentialWorkspaceMismatchError(workspaceId);
263
259
  const record = {
264
260
  workspaceId,
265
261
  workspaceName: this.storedSessions.find((stored) => stored.workspaceId === workspaceId)?.workspaceName,
@@ -280,6 +276,47 @@ var InMemoryCredentialManager = class {
280
276
  };
281
277
  //#endregion
282
278
  //#region src/testing.ts
279
+ function scriptedSpawn(program) {
280
+ return (request) => {
281
+ const delivered = [];
282
+ const waiting = [];
283
+ return {
284
+ ended: (async () => program(request, { nextKill: async () => {
285
+ return delivered.shift() ?? await new Promise((resolve) => {
286
+ waiting.push(resolve);
287
+ });
288
+ } }))(),
289
+ kill: (signal) => {
290
+ const waiter = waiting.shift();
291
+ if (waiter === void 0) {
292
+ delivered.push(signal);
293
+ return;
294
+ }
295
+ waiter(signal);
296
+ }
297
+ };
298
+ };
299
+ }
300
+ function recordingSpawn(adapter, spawns) {
301
+ return (request) => {
302
+ const record = {
303
+ command: request.command,
304
+ args: [...request.args],
305
+ cwd: request.cwd,
306
+ envKeys: Object.keys(request.env),
307
+ kills: []
308
+ };
309
+ spawns.push(record);
310
+ const child = adapter(request);
311
+ return {
312
+ ended: child.ended,
313
+ kill: (signal) => {
314
+ record.kills.push(signal);
315
+ child.kill(signal);
316
+ }
317
+ };
318
+ };
319
+ }
283
320
  function inputStreamFromString(text) {
284
321
  const bytes = new TextEncoder().encode(text);
285
322
  return { async *[Symbol.asyncIterator]() {
@@ -331,6 +368,7 @@ function createTestCli(spec) {
331
368
  const frames = [];
332
369
  const events = [];
333
370
  let presented;
371
+ const spawns = [];
334
372
  const signalListeners = /* @__PURE__ */ new Set();
335
373
  const deliverSignal = (reason) => {
336
374
  const signal = reason === "SIGTERM" ? "SIGTERM" : "SIGINT";
@@ -363,12 +401,17 @@ function createTestCli(spec) {
363
401
  signalListeners.delete(cb);
364
402
  };
365
403
  },
366
- config: {
404
+ loadConfig: spec.loadConfig ?? (async (configPath) => ({
405
+ path: configPath ?? "prisma.config.ts",
367
406
  sections: spec.config ?? {},
368
407
  diagnostics: []
369
- },
408
+ })),
370
409
  credentialManager,
371
410
  managementApiClientConfig,
411
+ spawn: recordingSpawn(spec.spawn ?? scriptedSpawn(spec.spawnScript ?? (() => ({
412
+ exitCode: 0,
413
+ signal: null
414
+ }))), spawns),
372
415
  openUrl: spec.openUrl ?? (() => {}),
373
416
  managementApi: { baseUrl: spec.managementApi?.baseUrl ?? "https://test.invalid" },
374
417
  packageManager: spec.packageManager ?? "unknown"
@@ -397,7 +440,8 @@ function createTestCli(spec) {
397
440
  stderr: stderrText,
398
441
  json: frames,
399
442
  events,
400
- presented
443
+ presented,
444
+ spawns
401
445
  };
402
446
  }
403
447
  };