@sebspark/test-iap 0.1.5 → 1.0.1

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/index.js CHANGED
@@ -1,56 +1,29 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- StartedTestIapContainer: () => StartedTestIapContainer,
34
- TestIapContainer: () => TestIapContainer,
35
- createProxyServer: () => createProxyServer
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
36
6
  });
37
- module.exports = __toCommonJS(index_exports);
38
7
 
39
8
  // src/server.ts
40
- var import_node_http = __toESM(require("http"));
41
- var import_node_https = __toESM(require("https"));
42
- var import_node_net = __toESM(require("net"));
9
+ import http from "http";
10
+ import https from "https";
11
+ import net from "net";
43
12
 
44
13
  // src/jwt.ts
45
- var import_node_crypto = require("crypto");
46
- var import_jose2 = require("jose");
14
+ import { randomUUID } from "crypto";
15
+ import { SignJWT } from "jose";
47
16
 
48
17
  // src/keys.ts
49
- var import_jose = require("jose");
18
+ import {
19
+ calculateJwkThumbprint,
20
+ exportJWK,
21
+ generateKeyPair
22
+ } from "jose";
50
23
  var generateKey = async () => {
51
- const { publicKey, privateKey } = await (0, import_jose.generateKeyPair)("RS256");
52
- const jwk = await (0, import_jose.exportJWK)(publicKey);
53
- jwk.kid = await (0, import_jose.calculateJwkThumbprint)(jwk);
24
+ const { publicKey, privateKey } = await generateKeyPair("RS256");
25
+ const jwk = await exportJWK(publicKey);
26
+ jwk.kid = await calculateJwkThumbprint(jwk);
54
27
  jwk.alg = "RS256";
55
28
  return { publicKey, privateKey, jwk };
56
29
  };
@@ -64,11 +37,11 @@ var getKey = async () => {
64
37
  return _key;
65
38
  };
66
39
  var defaultClaims = () => ({
67
- jti: (0, import_node_crypto.randomUUID)(),
68
- sub: (0, import_node_crypto.randomUUID)(),
40
+ jti: randomUUID(),
41
+ sub: randomUUID(),
69
42
  groups: [],
70
43
  aud: ["SEB"],
71
- sid: (0, import_node_crypto.randomUUID)()
44
+ sid: randomUUID()
72
45
  });
73
46
  var createJwt = async (claims) => {
74
47
  const payload = { ...defaultClaims(), ...claims };
@@ -82,7 +55,7 @@ var createJwt = async (claims) => {
82
55
  }
83
56
  const key = await getKey();
84
57
  const { alg, kid } = key.jwk;
85
- return await new import_jose2.SignJWT(payload).setIssuedAt().setNotBefore("0s").setExpirationTime("5m").setProtectedHeader({ alg, kid, typ: "JWT" }).sign(key.privateKey);
58
+ return await new SignJWT(payload).setIssuedAt().setNotBefore("0s").setExpirationTime("5m").setProtectedHeader({ alg, kid, typ: "JWT" }).sign(key.privateKey);
86
59
  };
87
60
  var getRemoteJwt = async (remoteUrl, claims) => {
88
61
  const url = new URL(remoteUrl);
@@ -179,8 +152,8 @@ var createProxyServer = (config) => {
179
152
  "config.target must be set, e.g. http://core:3000 or ws://gateway:4000"
180
153
  );
181
154
  const target = new URL(config.target);
182
- const httpClient = target.protocol === "https:" || target.protocol === "wss:" ? import_node_https.default : import_node_http.default;
183
- const server = import_node_http.default.createServer(async (req, res) => {
155
+ const httpClient = target.protocol === "https:" || target.protocol === "wss:" ? https : http;
156
+ const server = http.createServer(async (req, res) => {
184
157
  try {
185
158
  const upstream = new URL(req.url ?? "/", toHttpBase(target));
186
159
  const introspected = await introspect(config, req.headers);
@@ -225,7 +198,7 @@ var createProxyServer = (config) => {
225
198
  setHeader(introspected, "connection", "Upgrade");
226
199
  setHeader(introspected, "host", target.host);
227
200
  const port = Number(target.port) || defaultPort(target);
228
- const upstream = import_node_net.default.connect(port, target.hostname, () => {
201
+ const upstream = net.connect(port, target.hostname, () => {
229
202
  const wsBase = new URL(req.url ?? "/", toWsBase(target));
230
203
  const lines = [
231
204
  `GET ${wsBase.pathname}${wsBase.search} HTTP/1.1`,
@@ -262,23 +235,26 @@ Content-Length: ${body.length}
262
235
  };
263
236
 
264
237
  // src/test-iap-container.ts
265
- var import_node_assert = __toESM(require("assert"));
266
- var import_node_fs = __toESM(require("fs"));
267
- var import_node_path2 = __toESM(require("path"));
268
- var import_testcontainers = require("testcontainers");
238
+ import assert from "assert";
239
+ import fs from "fs";
240
+ import path2 from "path";
241
+ import {
242
+ AbstractStartedContainer,
243
+ GenericContainer
244
+ } from "testcontainers";
269
245
 
270
246
  // src/build-helpers.ts
271
- var import_node_module = require("module");
272
- var import_node_path = __toESM(require("path"));
273
- var import_node_url = require("url");
247
+ import { createRequire } from "module";
248
+ import path from "path";
249
+ import { fileURLToPath, pathToFileURL } from "url";
274
250
  var getThisFileUrl = () => {
275
251
  if (typeof __filename !== "undefined") {
276
- return (0, import_node_url.pathToFileURL)(__filename).href;
252
+ return pathToFileURL(__filename).href;
277
253
  }
278
254
  return (0, eval)("import.meta.url");
279
255
  };
280
- var getThisDir = () => import_node_path.default.dirname((0, import_node_url.fileURLToPath)(getThisFileUrl()));
281
- var getRequireCompat = () => typeof require === "function" ? require : (0, import_node_module.createRequire)(getThisFileUrl());
256
+ var getThisDir = () => path.dirname(fileURLToPath(getThisFileUrl()));
257
+ var getRequireCompat = () => typeof __require === "function" ? __require : createRequire(getThisFileUrl());
282
258
  var resolveNearSelf = (specifier) => {
283
259
  const req = getRequireCompat();
284
260
  return req.resolve(specifier, { paths: [getThisDir()] });
@@ -309,7 +285,7 @@ var TestIapContainer = class {
309
285
  }
310
286
  withTarget(url) {
311
287
  const u = new URL(url);
312
- (0, import_node_assert.default)(
288
+ assert(
313
289
  ["http:", "https:", "ws:", "wss:"].includes(u.protocol),
314
290
  "target must be absolute http(s):// or ws(s)://"
315
291
  );
@@ -322,7 +298,7 @@ var TestIapContainer = class {
322
298
  }
323
299
  withDownstream(url) {
324
300
  const u = new URL(url);
325
- (0, import_node_assert.default)(
301
+ assert(
326
302
  ["http:", "https:"].includes(u.protocol),
327
303
  "downstream must be absolute http(s)://"
328
304
  );
@@ -334,20 +310,20 @@ var TestIapContainer = class {
334
310
  return this;
335
311
  }
336
312
  async start() {
337
- (0, import_node_assert.default)(this.target, "withTarget(...) is required");
313
+ assert(this.target, "withTarget(...) is required");
338
314
  const resolvedMode = this.mode ?? (this.downstream ? "downstream" : "local");
339
315
  if (resolvedMode === "downstream") {
340
- (0, import_node_assert.default)(
316
+ assert(
341
317
  this.downstream,
342
318
  "withDownstream(...) is required when mode=downstream"
343
319
  );
344
320
  }
345
- const distDir = import_node_path2.default.join(getThisDir(), "../dist");
346
- (0, import_node_assert.default)(import_node_fs.default.existsSync(distDir), `dist directory not found: ${distDir}`);
347
- const startMjs = import_node_path2.default.join(distDir, "start.mjs");
348
- const startJs = import_node_path2.default.join(distDir, "start.js");
349
- const hasStartMjs = import_node_fs.default.existsSync(startMjs);
350
- const hasStartJs = import_node_fs.default.existsSync(startJs);
321
+ const distDir = path2.join(getThisDir(), "../dist");
322
+ assert(fs.existsSync(distDir), `dist directory not found: ${distDir}`);
323
+ const startMjs = path2.join(distDir, "start.mjs");
324
+ const startJs = path2.join(distDir, "start.js");
325
+ const hasStartMjs = fs.existsSync(startMjs);
326
+ const hasStartJs = fs.existsSync(startJs);
351
327
  if (!hasStartMjs && !hasStartJs) {
352
328
  throw new Error(`Could not find ${startMjs} or ${startJs}`);
353
329
  }
@@ -358,7 +334,7 @@ var TestIapContainer = class {
358
334
  'Could not resolve "jose" next to @sebspark/test-iap. Ensure "jose" is installed as a dependency in the same project that installs @sebspark/test-iap.'
359
335
  );
360
336
  }
361
- const joseDir = import_node_path2.default.dirname(josePkgPath);
337
+ const joseDir = path2.dirname(josePkgPath);
362
338
  const binds = [
363
339
  { source: distDir, target: "/app/dist" },
364
340
  { source: joseDir, target: "/app/node_modules/jose" }
@@ -371,13 +347,13 @@ var TestIapContainer = class {
371
347
  if (resolvedMode === "downstream" && this.downstream) {
372
348
  env.DOWNSTREAM = this.downstream;
373
349
  }
374
- const gc = new import_testcontainers.GenericContainer(this.baseImage).withWorkingDir("/app").withBindMounts(binds).withExposedPorts(this.port).withEnvironment(env).withCommand(["node", entry]);
350
+ const gc = new GenericContainer(this.baseImage).withWorkingDir("/app").withBindMounts(binds).withExposedPorts(this.port).withEnvironment(env).withCommand(["node", entry]);
375
351
  if (this.network) gc.withNetwork(this.network);
376
352
  const started = await gc.start();
377
353
  return new StartedTestIapContainer(started, this.port);
378
354
  }
379
355
  };
380
- var StartedTestIapContainer = class extends import_testcontainers.AbstractStartedContainer {
356
+ var StartedTestIapContainer = class extends AbstractStartedContainer {
381
357
  constructor(started, internalPort) {
382
358
  super(started);
383
359
  this.internalPort = internalPort;
@@ -386,9 +362,8 @@ var StartedTestIapContainer = class extends import_testcontainers.AbstractStarte
386
362
  return `${this.getHost()}:${this.getMappedPort(this.internalPort)}`;
387
363
  }
388
364
  };
389
- // Annotate the CommonJS export names for ESM import in node:
390
- 0 && (module.exports = {
365
+ export {
391
366
  StartedTestIapContainer,
392
367
  TestIapContainer,
393
368
  createProxyServer
394
- });
369
+ };
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@sebspark/test-iap",
3
- "version": "0.1.5",
3
+ "version": "1.0.1",
4
4
  "license": "Apache-2.0",
5
+ "type": "module",
5
6
  "main": "dist/index.js",
6
- "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
8
8
  "files": [
9
9
  "dist"
10
10
  ],
11
11
  "scripts": {
12
12
  "build": "yarn build:index && yarn build:start",
13
- "build:index": "tsup-node src/index.ts --format esm,cjs --dts",
14
- "build:start": "tsup-node src/start.ts --format esm",
13
+ "build:index": "tsup-node src/index.ts --format esm --target node22 --dts",
14
+ "build:start": "tsup-node src/start.ts --format esm --target node22 --dts",
15
15
  "dev": "tsc --watch --noEmit",
16
16
  "lint": "biome check .",
17
17
  "test": "vitest run --passWithNoTests --coverage",
@@ -20,12 +20,12 @@
20
20
  "typecheck": "vitest --typecheck.only --passWithNoTests"
21
21
  },
22
22
  "dependencies": {
23
- "jose": "^6.1.0",
24
- "testcontainers": "^11.7.2"
23
+ "jose": "6.1.0",
24
+ "testcontainers": "11.7.2"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@sebspark/tsconfig": "*",
28
- "@types/ws": "^8.18.1",
29
- "ws": "^8.18.3"
28
+ "@types/ws": "8.18.1",
29
+ "ws": "8.18.3"
30
30
  }
31
31
  }
package/dist/index.d.mts DELETED
@@ -1,34 +0,0 @@
1
- import http from 'node:http';
2
- import { AbstractStartedContainer, StartedTestContainer, StartedNetwork } from 'testcontainers';
3
-
4
- type Mode = 'local' | 'downstream';
5
- interface ProxyConfig {
6
- target: string;
7
- mode?: Mode;
8
- downstream?: string;
9
- }
10
-
11
- declare const createProxyServer: (config: ProxyConfig) => http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
12
-
13
- declare class TestIapContainer {
14
- private baseImage;
15
- private port;
16
- private target?;
17
- private mode?;
18
- private downstream?;
19
- private network?;
20
- withBaseImage(image: string): this;
21
- withPort(port: number): this;
22
- withTarget(url: string): this;
23
- withMode(mode: Mode): this;
24
- withDownstream(url: string): this;
25
- withNetwork(network: StartedNetwork): this;
26
- start(): Promise<StartedTestIapContainer>;
27
- }
28
- declare class StartedTestIapContainer extends AbstractStartedContainer {
29
- private readonly internalPort;
30
- constructor(started: StartedTestContainer, internalPort: number);
31
- getEndpoint(): string;
32
- }
33
-
34
- export { type Mode, type ProxyConfig, StartedTestIapContainer, TestIapContainer, createProxyServer };
package/dist/index.mjs DELETED
@@ -1,369 +0,0 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/server.ts
9
- import http from "http";
10
- import https from "https";
11
- import net from "net";
12
-
13
- // src/jwt.ts
14
- import { randomUUID } from "crypto";
15
- import { SignJWT } from "jose";
16
-
17
- // src/keys.ts
18
- import {
19
- calculateJwkThumbprint,
20
- exportJWK,
21
- generateKeyPair
22
- } from "jose";
23
- var generateKey = async () => {
24
- const { publicKey, privateKey } = await generateKeyPair("RS256");
25
- const jwk = await exportJWK(publicKey);
26
- jwk.kid = await calculateJwkThumbprint(jwk);
27
- jwk.alg = "RS256";
28
- return { publicKey, privateKey, jwk };
29
- };
30
-
31
- // src/jwt.ts
32
- var _key;
33
- var getKey = async () => {
34
- if (!_key) {
35
- _key = await generateKey();
36
- }
37
- return _key;
38
- };
39
- var defaultClaims = () => ({
40
- jti: randomUUID(),
41
- sub: randomUUID(),
42
- groups: [],
43
- aud: ["SEB"],
44
- sid: randomUUID()
45
- });
46
- var createJwt = async (claims) => {
47
- const payload = { ...defaultClaims(), ...claims };
48
- const hasUser = Object.hasOwn(payload, "user");
49
- const hasPreferred = Object.hasOwn(payload, "preferred_username");
50
- if (hasUser && !hasPreferred && typeof payload.user === "string") {
51
- payload.preferred_username = payload.user;
52
- }
53
- if (hasUser) {
54
- delete payload.user;
55
- }
56
- const key = await getKey();
57
- const { alg, kid } = key.jwk;
58
- return await new SignJWT(payload).setIssuedAt().setNotBefore("0s").setExpirationTime("5m").setProtectedHeader({ alg, kid, typ: "JWT" }).sign(key.privateKey);
59
- };
60
- var getRemoteJwt = async (remoteUrl, claims) => {
61
- const url = new URL(remoteUrl);
62
- for (const [name, val] of Object.entries(claims)) {
63
- url.searchParams.set(name, val);
64
- }
65
- const res = await fetch(url);
66
- const text = await res.text();
67
- if (!res.ok)
68
- throw new Error(`remote jwt fetch failed: ${res.status} ${res.statusText}`);
69
- return text;
70
- };
71
-
72
- // src/utils.ts
73
- var defaultPort = (target) => {
74
- if (target.protocol === "https:" || target.protocol === "wss:") return 443;
75
- return 80;
76
- };
77
- var toHttpBase = (target) => {
78
- if (target.protocol.startsWith("ws")) {
79
- const p = target.protocol === "wss:" ? "https:" : "http:";
80
- return `${p}//${target.host}`;
81
- }
82
- return target.toString();
83
- };
84
- var toWsBase = (target) => {
85
- if (target.protocol.startsWith("http")) {
86
- const p = target.protocol === "https:" ? "wss:" : "ws:";
87
- return `${p}//${target.host}`;
88
- }
89
- return target.toString();
90
- };
91
- var getHeader = (headers, name) => {
92
- const lc = name.toLowerCase();
93
- const key = Object.keys(headers).find((k) => k.toLowerCase() === lc);
94
- return key ? headers[key] : void 0;
95
- };
96
- var hasHeader = (headers, name) => {
97
- const lc = name.toLowerCase();
98
- return Object.keys(headers).some((k) => k.toLowerCase() === lc);
99
- };
100
- var setHeader = (headers, name, value) => {
101
- headers[name.toLowerCase()] = value;
102
- };
103
- var flattenHeaders = (headers) => {
104
- const out = [];
105
- for (const [k, v] of Object.entries(headers)) {
106
- if (v == null) continue;
107
- if (Array.isArray(v)) {
108
- for (const val of v) {
109
- out.push(`${k}: ${val}`);
110
- }
111
- } else {
112
- out.push(`${k}: ${String(v)}`);
113
- }
114
- }
115
- return out;
116
- };
117
- var IntrospectionError = class extends Error {
118
- constructor(header) {
119
- super(`Could not introspect header '${header}'`);
120
- }
121
- };
122
- var parseAuthorizationHeader = (header) => {
123
- try {
124
- const [, access_token] = header.trim().split(/\s+/, 2);
125
- const buffer = Buffer.from(access_token, "base64url");
126
- const json = JSON.parse(buffer.toString("utf8"));
127
- if (!json || typeof json !== "object" || Array.isArray(json)) {
128
- throw new Error("access_token must be base64url encoded JSON object");
129
- }
130
- return json;
131
- } catch {
132
- throw new IntrospectionError(header);
133
- }
134
- };
135
-
136
- // src/introspection.ts
137
- var introspect = async (config, headers) => {
138
- const authorizationHeader = getHeader(headers, "authorization");
139
- if (!authorizationHeader) {
140
- return headers;
141
- }
142
- const claims = parseAuthorizationHeader(authorizationHeader);
143
- const mode = config.mode || (config.downstream ? "downstream" : "local");
144
- const access_token = await (mode === "local" ? createJwt(claims) : getRemoteJwt(config.downstream, claims));
145
- return { ...headers, authorization: `Bearer ${access_token}` };
146
- };
147
-
148
- // src/server.ts
149
- var createProxyServer = (config) => {
150
- if (!config.target)
151
- throw new Error(
152
- "config.target must be set, e.g. http://core:3000 or ws://gateway:4000"
153
- );
154
- const target = new URL(config.target);
155
- const httpClient = target.protocol === "https:" || target.protocol === "wss:" ? https : http;
156
- const server = http.createServer(async (req, res) => {
157
- try {
158
- const upstream = new URL(req.url ?? "/", toHttpBase(target));
159
- const introspected = await introspect(config, req.headers);
160
- if (!introspected.host) introspected.host = upstream.host;
161
- const proxyReq = httpClient.request(
162
- {
163
- protocol: upstream.protocol,
164
- hostname: upstream.hostname,
165
- port: upstream.port || String(defaultPort(target)),
166
- method: req.method,
167
- path: upstream.pathname + upstream.search,
168
- headers: introspected
169
- },
170
- (proxyRes) => {
171
- res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
172
- proxyRes.pipe(res, { end: true });
173
- }
174
- );
175
- proxyReq.on("error", () => {
176
- if (!res.writableEnded) {
177
- res.writeHead(502);
178
- res.end("proxy error");
179
- }
180
- });
181
- req.pipe(proxyReq, { end: true });
182
- } catch (err) {
183
- const payload = {
184
- name: err instanceof Error ? err.name : "Error",
185
- message: err instanceof Error ? err.message : String(err),
186
- stack: err instanceof Error ? err.stack : void 0
187
- };
188
- res.writeHead(500, { "content-type": "application/json" });
189
- res.end(JSON.stringify(payload));
190
- }
191
- });
192
- server.on("upgrade", async (req, socket, head) => {
193
- try {
194
- const introspected = await introspect(config, req.headers);
195
- if (!hasHeader(introspected, "upgrade"))
196
- setHeader(introspected, "upgrade", "websocket");
197
- if (!hasHeader(introspected, "connection"))
198
- setHeader(introspected, "connection", "Upgrade");
199
- setHeader(introspected, "host", target.host);
200
- const port = Number(target.port) || defaultPort(target);
201
- const upstream = net.connect(port, target.hostname, () => {
202
- const wsBase = new URL(req.url ?? "/", toWsBase(target));
203
- const lines = [
204
- `GET ${wsBase.pathname}${wsBase.search} HTTP/1.1`,
205
- `Host: ${target.host}`,
206
- ...flattenHeaders(introspected),
207
- "",
208
- ""
209
- ];
210
- upstream.write(lines.join("\r\n"));
211
- if (head?.length) upstream.write(head);
212
- socket.pipe(upstream).pipe(socket);
213
- });
214
- upstream.on("error", () => socket.destroy());
215
- socket.on("error", () => upstream.destroy());
216
- } catch (err) {
217
- const payload = {
218
- name: err instanceof Error ? err.name : "Error",
219
- message: err instanceof Error ? err.message : String(err),
220
- stack: err instanceof Error ? err.stack : void 0
221
- };
222
- const body = Buffer.from(JSON.stringify(payload));
223
- socket.write(
224
- `HTTP/1.1 500 Internal Server Error
225
- Connection: close
226
- Content-Type: application/json
227
- Content-Length: ${body.length}
228
- `
229
- );
230
- socket.write(body);
231
- socket.destroy();
232
- }
233
- });
234
- return server;
235
- };
236
-
237
- // src/test-iap-container.ts
238
- import assert from "assert";
239
- import fs from "fs";
240
- import path2 from "path";
241
- import {
242
- AbstractStartedContainer,
243
- GenericContainer
244
- } from "testcontainers";
245
-
246
- // src/build-helpers.ts
247
- import { createRequire } from "module";
248
- import path from "path";
249
- import { fileURLToPath, pathToFileURL } from "url";
250
- var getThisFileUrl = () => {
251
- if (typeof __filename !== "undefined") {
252
- return pathToFileURL(__filename).href;
253
- }
254
- return (0, eval)("import.meta.url");
255
- };
256
- var getThisDir = () => path.dirname(fileURLToPath(getThisFileUrl()));
257
- var getRequireCompat = () => typeof __require === "function" ? __require : createRequire(getThisFileUrl());
258
- var resolveNearSelf = (specifier) => {
259
- const req = getRequireCompat();
260
- return req.resolve(specifier, { paths: [getThisDir()] });
261
- };
262
- var tryResolveNearSelf = (specifier) => {
263
- try {
264
- return resolveNearSelf(specifier);
265
- } catch {
266
- return void 0;
267
- }
268
- };
269
-
270
- // src/test-iap-container.ts
271
- var TestIapContainer = class {
272
- baseImage = "node:22-alpine";
273
- port = 3e3;
274
- target;
275
- mode;
276
- downstream;
277
- network;
278
- withBaseImage(image) {
279
- this.baseImage = image;
280
- return this;
281
- }
282
- withPort(port) {
283
- this.port = port;
284
- return this;
285
- }
286
- withTarget(url) {
287
- const u = new URL(url);
288
- assert(
289
- ["http:", "https:", "ws:", "wss:"].includes(u.protocol),
290
- "target must be absolute http(s):// or ws(s)://"
291
- );
292
- this.target = u.toString();
293
- return this;
294
- }
295
- withMode(mode) {
296
- this.mode = mode;
297
- return this;
298
- }
299
- withDownstream(url) {
300
- const u = new URL(url);
301
- assert(
302
- ["http:", "https:"].includes(u.protocol),
303
- "downstream must be absolute http(s)://"
304
- );
305
- this.downstream = u.toString();
306
- return this;
307
- }
308
- withNetwork(network) {
309
- this.network = network;
310
- return this;
311
- }
312
- async start() {
313
- assert(this.target, "withTarget(...) is required");
314
- const resolvedMode = this.mode ?? (this.downstream ? "downstream" : "local");
315
- if (resolvedMode === "downstream") {
316
- assert(
317
- this.downstream,
318
- "withDownstream(...) is required when mode=downstream"
319
- );
320
- }
321
- const distDir = path2.join(getThisDir(), "../dist");
322
- assert(fs.existsSync(distDir), `dist directory not found: ${distDir}`);
323
- const startMjs = path2.join(distDir, "start.mjs");
324
- const startJs = path2.join(distDir, "start.js");
325
- const hasStartMjs = fs.existsSync(startMjs);
326
- const hasStartJs = fs.existsSync(startJs);
327
- if (!hasStartMjs && !hasStartJs) {
328
- throw new Error(`Could not find ${startMjs} or ${startJs}`);
329
- }
330
- const entry = hasStartMjs ? "/app/dist/start.mjs" : "/app/dist/start.js";
331
- const josePkgPath = tryResolveNearSelf("jose/package.json");
332
- if (!josePkgPath) {
333
- throw new Error(
334
- 'Could not resolve "jose" next to @sebspark/test-iap. Ensure "jose" is installed as a dependency in the same project that installs @sebspark/test-iap.'
335
- );
336
- }
337
- const joseDir = path2.dirname(josePkgPath);
338
- const binds = [
339
- { source: distDir, target: "/app/dist" },
340
- { source: joseDir, target: "/app/node_modules/jose" }
341
- ];
342
- const env = {
343
- TARGET: this.target,
344
- MODE: resolvedMode,
345
- PORT: String(this.port)
346
- };
347
- if (resolvedMode === "downstream" && this.downstream) {
348
- env.DOWNSTREAM = this.downstream;
349
- }
350
- const gc = new GenericContainer(this.baseImage).withWorkingDir("/app").withBindMounts(binds).withExposedPorts(this.port).withEnvironment(env).withCommand(["node", entry]);
351
- if (this.network) gc.withNetwork(this.network);
352
- const started = await gc.start();
353
- return new StartedTestIapContainer(started, this.port);
354
- }
355
- };
356
- var StartedTestIapContainer = class extends AbstractStartedContainer {
357
- constructor(started, internalPort) {
358
- super(started);
359
- this.internalPort = internalPort;
360
- }
361
- getEndpoint() {
362
- return `${this.getHost()}:${this.getMappedPort(this.internalPort)}`;
363
- }
364
- };
365
- export {
366
- StartedTestIapContainer,
367
- TestIapContainer,
368
- createProxyServer
369
- };
File without changes