@constructive-io/playwright-test 0.2.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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # @constructive-io/playwright-test
2
+
3
+ Constructive Playwright Testing with HTTP server support for end-to-end testing.
4
+
5
+ This package extends `@constructive-io/graphql-test` to provide an actual HTTP server for Playwright and other E2E testing frameworks. It creates isolated test databases and starts a GraphQL server that bypasses domain routing, making it perfect for integration testing.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @constructive-io/playwright-test
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Basic Usage
16
+
17
+ ```typescript
18
+ import { getConnectionsWithServer, seed } from '@constructive-io/playwright-test';
19
+
20
+ describe('E2E Tests', () => {
21
+ let teardown: () => Promise<void>;
22
+ let serverUrl: string;
23
+
24
+ beforeAll(async () => {
25
+ const connections = await getConnectionsWithServer({
26
+ schemas: ['public', 'app_public'],
27
+ authRole: 'anonymous'
28
+ }, [seed.pgpm({ extensions: ['my-extension'] })]);
29
+
30
+ teardown = connections.teardown;
31
+ serverUrl = connections.server.graphqlUrl;
32
+ });
33
+
34
+ afterAll(async () => {
35
+ await teardown();
36
+ });
37
+
38
+ it('should work with Playwright', async () => {
39
+ // Use serverUrl in your Playwright tests
40
+ // e.g., await page.goto(serverUrl);
41
+ });
42
+ });
43
+ ```
44
+
45
+ ### With Playwright
46
+
47
+ ```typescript
48
+ import { test, expect } from '@playwright/test';
49
+ import { getConnectionsWithServer } from '@constructive-io/playwright-test';
50
+
51
+ let connections: Awaited<ReturnType<typeof getConnectionsWithServer>>;
52
+
53
+ test.beforeAll(async () => {
54
+ connections = await getConnectionsWithServer({
55
+ schemas: ['services_public', 'app_public'],
56
+ authRole: 'anonymous',
57
+ server: {
58
+ port: 5555,
59
+ host: 'localhost'
60
+ }
61
+ });
62
+ });
63
+
64
+ test.afterAll(async () => {
65
+ await connections.teardown();
66
+ });
67
+
68
+ test('GraphQL API is accessible', async ({ page }) => {
69
+ const response = await page.request.post(connections.server.graphqlUrl, {
70
+ data: {
71
+ query: '{ __typename }'
72
+ }
73
+ });
74
+ expect(response.ok()).toBeTruthy();
75
+ });
76
+ ```
77
+
78
+ ### Direct Query Access
79
+
80
+ You can also execute GraphQL queries directly without going through HTTP:
81
+
82
+ ```typescript
83
+ const { query, server, teardown } = await getConnectionsWithServer({
84
+ schemas: ['public'],
85
+ authRole: 'anonymous'
86
+ });
87
+
88
+ // Direct query (bypasses HTTP)
89
+ const result = await query(`
90
+ query {
91
+ allUsers {
92
+ nodes {
93
+ id
94
+ name
95
+ }
96
+ }
97
+ }
98
+ `);
99
+
100
+ // HTTP endpoint for Playwright
101
+ console.log(server.graphqlUrl); // http://localhost:5555/graphql
102
+ ```
103
+
104
+ ## API
105
+
106
+ ### getConnectionsWithServer(input, seedAdapters?)
107
+
108
+ Creates database connections and starts an HTTP server for testing.
109
+
110
+ **Parameters:**
111
+ - `input.schemas` - Array of PostgreSQL schemas to expose
112
+ - `input.authRole` - Default authentication role (e.g., 'anonymous', 'authenticated')
113
+ - `input.server.port` - Port to run the server on (defaults to random available port)
114
+ - `input.server.host` - Host to bind to (defaults to 'localhost')
115
+ - `input.graphile` - Optional Graphile configuration overrides
116
+ - `seedAdapters` - Optional array of seed adapters for database setup
117
+
118
+ **Returns:**
119
+ - `pg` - PostgreSQL client for direct database access
120
+ - `db` - Database client for test operations
121
+ - `server` - Server info including `url`, `graphqlUrl`, `port`, `host`, and `stop()`
122
+ - `query` - GraphQL query function (positional API)
123
+ - `teardown` - Cleanup function to stop server and drop test database
124
+
125
+ ### getConnectionsWithServerObject(input, seedAdapters?)
126
+
127
+ Same as `getConnectionsWithServer` but uses object-based query API.
128
+
129
+ ### getConnectionsWithServerUnwrapped(input, seedAdapters?)
130
+
131
+ Same as `getConnectionsWithServer` but throws on GraphQL errors instead of returning them.
132
+
133
+ ### createTestServer(opts, serverOpts?)
134
+
135
+ Low-level function to create just the HTTP server without database setup.
136
+
137
+ ## How It Works
138
+
139
+ 1. Creates an isolated test database using `pgsql-test`
140
+ 2. Starts an Express server with Constructive GraphQL middleware
141
+ 3. Configures `enableServicesApi: false` to bypass domain/subdomain routing
142
+ 4. Exposes the specified schemas directly via the GraphQL endpoint
143
+ 5. Returns the server URL for Playwright to connect to
144
+ 6. Provides a teardown function that stops the server and cleans up the database
145
+
146
+ ## Configuration
147
+
148
+ The server is configured with `enableServicesApi: false`, which means:
149
+ - No domain/subdomain routing is required
150
+ - Schemas are exposed directly based on the `schemas` parameter
151
+ - Perfect for isolated testing without complex domain setup
152
+
153
+ ---
154
+
155
+ ## Education and Tutorials
156
+
157
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
158
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
159
+
160
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
161
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
162
+
163
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
164
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
165
+
166
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
167
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
168
+
169
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
170
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
171
+
172
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
173
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
174
+
175
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
176
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
177
+
178
+ ## Related Constructive Tooling
179
+
180
+ ### 📦 Package Management
181
+
182
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
183
+
184
+ ### 🧪 Testing
185
+
186
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
187
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
188
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
189
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
190
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
191
+
192
+ ### 🧠 Parsing & AST
193
+
194
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
195
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
196
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
197
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
198
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
199
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
200
+
201
+ ## Credits
202
+
203
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
204
+
205
+ ## Disclaimer
206
+
207
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
208
+
209
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
@@ -0,0 +1,122 @@
1
+ import { getConnections as getPgConnections } from 'pgsql-test';
2
+ import { getEnvOptions } from '@constructive-io/graphql-env';
3
+ import { GraphQLTest } from '@constructive-io/graphql-test';
4
+ import { createTestServer } from './server';
5
+ /**
6
+ * Core unwrapping utility - throws on GraphQL errors
7
+ */
8
+ const unwrap = (res) => {
9
+ if (res.errors?.length) {
10
+ throw new Error(JSON.stringify(res.errors, null, 2));
11
+ }
12
+ if (!res.data) {
13
+ throw new Error('No data returned from GraphQL query');
14
+ }
15
+ return res.data;
16
+ };
17
+ /**
18
+ * Base connection setup with HTTP server - shared across all variants
19
+ */
20
+ const createConnectionsWithServerBase = async (input, seedAdapters) => {
21
+ // Get database connections using pgsql-test
22
+ const conn = await getPgConnections(input, seedAdapters);
23
+ const { pg, db, teardown: dbTeardown } = conn;
24
+ // Set up GraphQL test context for direct queries
25
+ const gqlContext = GraphQLTest(input, conn);
26
+ await gqlContext.setup();
27
+ // Build options for the HTTP server with enableServicesApi: false
28
+ const serverOpts = getEnvOptions({
29
+ pg: pg.config,
30
+ api: {
31
+ enableServicesApi: false,
32
+ exposedSchemas: input.schemas,
33
+ defaultDatabaseId: 'test-database',
34
+ ...(input.authRole && { anonRole: input.authRole, roleName: input.authRole })
35
+ },
36
+ graphile: input.graphile
37
+ });
38
+ // Start the HTTP server
39
+ const server = await createTestServer(serverOpts, input.server);
40
+ // Combined teardown function
41
+ const teardown = async () => {
42
+ await server.stop();
43
+ await gqlContext.teardown();
44
+ await dbTeardown();
45
+ };
46
+ // Query functions
47
+ const baseQuery = (opts) => gqlContext.query(opts);
48
+ const baseQueryPositional = (query, variables, commit, reqOptions) => gqlContext.query({ query, variables, commit, reqOptions });
49
+ return {
50
+ pg,
51
+ db,
52
+ server,
53
+ teardown,
54
+ baseQuery,
55
+ baseQueryPositional
56
+ };
57
+ };
58
+ /**
59
+ * Creates connections with an HTTP server for Playwright testing (positional API)
60
+ *
61
+ * This is the main entry point for Playwright tests. It:
62
+ * 1. Creates an isolated test database
63
+ * 2. Starts an HTTP server with the GraphQL API
64
+ * 3. Returns the server URL for Playwright to connect to
65
+ * 4. Provides a teardown function to clean up everything
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * const { server, teardown } = await getConnectionsWithServer({
70
+ * schemas: ['public', 'app_public'],
71
+ * authRole: 'anonymous'
72
+ * });
73
+ *
74
+ * // Use server.graphqlUrl in Playwright tests
75
+ * await page.goto(server.url);
76
+ *
77
+ * // Clean up after tests
78
+ * await teardown();
79
+ * ```
80
+ */
81
+ export const getConnectionsWithServer = async (input, seedAdapters) => {
82
+ const { pg, db, server, teardown, baseQueryPositional } = await createConnectionsWithServerBase(input, seedAdapters);
83
+ return {
84
+ pg,
85
+ db,
86
+ server,
87
+ teardown,
88
+ query: baseQueryPositional
89
+ };
90
+ };
91
+ /**
92
+ * Creates connections with an HTTP server for Playwright testing (object API)
93
+ *
94
+ * Same as getConnectionsWithServer but uses object-based query API.
95
+ */
96
+ export const getConnectionsWithServerObject = async (input, seedAdapters) => {
97
+ const { pg, db, server, teardown, baseQuery } = await createConnectionsWithServerBase(input, seedAdapters);
98
+ return {
99
+ pg,
100
+ db,
101
+ server,
102
+ teardown,
103
+ query: baseQuery
104
+ };
105
+ };
106
+ /**
107
+ * Creates connections with an HTTP server and unwrapped query responses
108
+ *
109
+ * Same as getConnectionsWithServer but throws on GraphQL errors instead of
110
+ * returning them in the response.
111
+ */
112
+ export const getConnectionsWithServerUnwrapped = async (input, seedAdapters) => {
113
+ const { pg, db, server, teardown, baseQueryPositional } = await createConnectionsWithServerBase(input, seedAdapters);
114
+ const query = async (query, variables, commit, reqOptions) => unwrap(await baseQueryPositional(query, variables, commit, reqOptions));
115
+ return {
116
+ pg,
117
+ db,
118
+ server,
119
+ teardown,
120
+ query
121
+ };
122
+ };
package/esm/index.js ADDED
@@ -0,0 +1,8 @@
1
+ // Export our types
2
+ export * from './types';
3
+ // Export server utilities
4
+ export { createTestServer, getTestPool } from './server';
5
+ // Export connection functions with server support
6
+ export { getConnectionsWithServer, getConnectionsWithServerObject, getConnectionsWithServerUnwrapped } from './get-connections';
7
+ // Re-export seed and snapshot utilities from pgsql-test
8
+ export { seed, snapshot } from 'pgsql-test';
package/esm/server.js ADDED
@@ -0,0 +1,77 @@
1
+ import { createApiMiddleware, createAuthenticateMiddleware, cors, graphile } from '@constructive-io/graphql-server';
2
+ import express from 'express';
3
+ import { createServer } from 'http';
4
+ import { getPgPool } from 'pg-cache';
5
+ /**
6
+ * Find an available port starting from the given port
7
+ */
8
+ const findAvailablePort = async (startPort) => {
9
+ return new Promise((resolve, reject) => {
10
+ const server = createServer();
11
+ server.listen(startPort, () => {
12
+ const address = server.address();
13
+ const port = typeof address === 'object' && address ? address.port : startPort;
14
+ server.close(() => resolve(port));
15
+ });
16
+ server.on('error', (err) => {
17
+ if (err.code === 'EADDRINUSE') {
18
+ resolve(findAvailablePort(startPort + 1));
19
+ }
20
+ else {
21
+ reject(err);
22
+ }
23
+ });
24
+ });
25
+ };
26
+ /**
27
+ * Create a test server for Playwright testing
28
+ *
29
+ * This creates an Express server with the Constructive GraphQL middleware
30
+ * configured with enableServicesApi: false to bypass domain routing.
31
+ */
32
+ export const createTestServer = async (opts, serverOpts = {}) => {
33
+ const host = serverOpts.host ?? 'localhost';
34
+ const requestedPort = serverOpts.port ?? 0;
35
+ const port = requestedPort === 0 ? await findAvailablePort(5555) : requestedPort;
36
+ const app = express();
37
+ // Create middleware with enableServicesApi: false to bypass domain routing
38
+ const api = createApiMiddleware(opts);
39
+ const authenticate = createAuthenticateMiddleware(opts);
40
+ // Basic middleware setup
41
+ app.use(cors('*'));
42
+ app.use(api);
43
+ app.use(authenticate);
44
+ app.use(graphile(opts));
45
+ // Create HTTP server
46
+ const httpServer = await new Promise((resolve, reject) => {
47
+ const server = app.listen(port, host, () => {
48
+ resolve(server);
49
+ });
50
+ server.on('error', reject);
51
+ });
52
+ const actualPort = httpServer.address().port;
53
+ const stop = async () => {
54
+ return new Promise((resolve, reject) => {
55
+ httpServer.close((err) => {
56
+ if (err)
57
+ reject(err);
58
+ else
59
+ resolve();
60
+ });
61
+ });
62
+ };
63
+ return {
64
+ httpServer,
65
+ url: `http://${host}:${actualPort}`,
66
+ graphqlUrl: `http://${host}:${actualPort}/graphql`,
67
+ port: actualPort,
68
+ host,
69
+ stop
70
+ };
71
+ };
72
+ /**
73
+ * Get the PostgreSQL pool for the test server
74
+ */
75
+ export const getTestPool = (opts) => {
76
+ return getPgPool(opts.pg);
77
+ };
package/esm/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,42 @@
1
+ import type { GetConnectionOpts } from 'pgsql-test';
2
+ import type { SeedAdapter } from 'pgsql-test/seed/types';
3
+ import type { GetConnectionsWithServerInput, GetConnectionsWithServerResult, GetConnectionsWithServerObjectResult } from './types';
4
+ /**
5
+ * Creates connections with an HTTP server for Playwright testing (positional API)
6
+ *
7
+ * This is the main entry point for Playwright tests. It:
8
+ * 1. Creates an isolated test database
9
+ * 2. Starts an HTTP server with the GraphQL API
10
+ * 3. Returns the server URL for Playwright to connect to
11
+ * 4. Provides a teardown function to clean up everything
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const { server, teardown } = await getConnectionsWithServer({
16
+ * schemas: ['public', 'app_public'],
17
+ * authRole: 'anonymous'
18
+ * });
19
+ *
20
+ * // Use server.graphqlUrl in Playwright tests
21
+ * await page.goto(server.url);
22
+ *
23
+ * // Clean up after tests
24
+ * await teardown();
25
+ * ```
26
+ */
27
+ export declare const getConnectionsWithServer: (input: GetConnectionsWithServerInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<GetConnectionsWithServerResult>;
28
+ /**
29
+ * Creates connections with an HTTP server for Playwright testing (object API)
30
+ *
31
+ * Same as getConnectionsWithServer but uses object-based query API.
32
+ */
33
+ export declare const getConnectionsWithServerObject: (input: GetConnectionsWithServerInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<GetConnectionsWithServerObjectResult>;
34
+ /**
35
+ * Creates connections with an HTTP server and unwrapped query responses
36
+ *
37
+ * Same as getConnectionsWithServer but throws on GraphQL errors instead of
38
+ * returning them in the response.
39
+ */
40
+ export declare const getConnectionsWithServerUnwrapped: (input: GetConnectionsWithServerInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<Omit<GetConnectionsWithServerResult, "query"> & {
41
+ query: (query: any, variables?: any, commit?: boolean, reqOptions?: any) => Promise<any>;
42
+ }>;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getConnectionsWithServerUnwrapped = exports.getConnectionsWithServerObject = exports.getConnectionsWithServer = void 0;
4
+ const pgsql_test_1 = require("pgsql-test");
5
+ const graphql_env_1 = require("@constructive-io/graphql-env");
6
+ const graphql_test_1 = require("@constructive-io/graphql-test");
7
+ const server_1 = require("./server");
8
+ /**
9
+ * Core unwrapping utility - throws on GraphQL errors
10
+ */
11
+ const unwrap = (res) => {
12
+ if (res.errors?.length) {
13
+ throw new Error(JSON.stringify(res.errors, null, 2));
14
+ }
15
+ if (!res.data) {
16
+ throw new Error('No data returned from GraphQL query');
17
+ }
18
+ return res.data;
19
+ };
20
+ /**
21
+ * Base connection setup with HTTP server - shared across all variants
22
+ */
23
+ const createConnectionsWithServerBase = async (input, seedAdapters) => {
24
+ // Get database connections using pgsql-test
25
+ const conn = await (0, pgsql_test_1.getConnections)(input, seedAdapters);
26
+ const { pg, db, teardown: dbTeardown } = conn;
27
+ // Set up GraphQL test context for direct queries
28
+ const gqlContext = (0, graphql_test_1.GraphQLTest)(input, conn);
29
+ await gqlContext.setup();
30
+ // Build options for the HTTP server with enableServicesApi: false
31
+ const serverOpts = (0, graphql_env_1.getEnvOptions)({
32
+ pg: pg.config,
33
+ api: {
34
+ enableServicesApi: false,
35
+ exposedSchemas: input.schemas,
36
+ defaultDatabaseId: 'test-database',
37
+ ...(input.authRole && { anonRole: input.authRole, roleName: input.authRole })
38
+ },
39
+ graphile: input.graphile
40
+ });
41
+ // Start the HTTP server
42
+ const server = await (0, server_1.createTestServer)(serverOpts, input.server);
43
+ // Combined teardown function
44
+ const teardown = async () => {
45
+ await server.stop();
46
+ await gqlContext.teardown();
47
+ await dbTeardown();
48
+ };
49
+ // Query functions
50
+ const baseQuery = (opts) => gqlContext.query(opts);
51
+ const baseQueryPositional = (query, variables, commit, reqOptions) => gqlContext.query({ query, variables, commit, reqOptions });
52
+ return {
53
+ pg,
54
+ db,
55
+ server,
56
+ teardown,
57
+ baseQuery,
58
+ baseQueryPositional
59
+ };
60
+ };
61
+ /**
62
+ * Creates connections with an HTTP server for Playwright testing (positional API)
63
+ *
64
+ * This is the main entry point for Playwright tests. It:
65
+ * 1. Creates an isolated test database
66
+ * 2. Starts an HTTP server with the GraphQL API
67
+ * 3. Returns the server URL for Playwright to connect to
68
+ * 4. Provides a teardown function to clean up everything
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * const { server, teardown } = await getConnectionsWithServer({
73
+ * schemas: ['public', 'app_public'],
74
+ * authRole: 'anonymous'
75
+ * });
76
+ *
77
+ * // Use server.graphqlUrl in Playwright tests
78
+ * await page.goto(server.url);
79
+ *
80
+ * // Clean up after tests
81
+ * await teardown();
82
+ * ```
83
+ */
84
+ const getConnectionsWithServer = async (input, seedAdapters) => {
85
+ const { pg, db, server, teardown, baseQueryPositional } = await createConnectionsWithServerBase(input, seedAdapters);
86
+ return {
87
+ pg,
88
+ db,
89
+ server,
90
+ teardown,
91
+ query: baseQueryPositional
92
+ };
93
+ };
94
+ exports.getConnectionsWithServer = getConnectionsWithServer;
95
+ /**
96
+ * Creates connections with an HTTP server for Playwright testing (object API)
97
+ *
98
+ * Same as getConnectionsWithServer but uses object-based query API.
99
+ */
100
+ const getConnectionsWithServerObject = async (input, seedAdapters) => {
101
+ const { pg, db, server, teardown, baseQuery } = await createConnectionsWithServerBase(input, seedAdapters);
102
+ return {
103
+ pg,
104
+ db,
105
+ server,
106
+ teardown,
107
+ query: baseQuery
108
+ };
109
+ };
110
+ exports.getConnectionsWithServerObject = getConnectionsWithServerObject;
111
+ /**
112
+ * Creates connections with an HTTP server and unwrapped query responses
113
+ *
114
+ * Same as getConnectionsWithServer but throws on GraphQL errors instead of
115
+ * returning them in the response.
116
+ */
117
+ const getConnectionsWithServerUnwrapped = async (input, seedAdapters) => {
118
+ const { pg, db, server, teardown, baseQueryPositional } = await createConnectionsWithServerBase(input, seedAdapters);
119
+ const query = async (query, variables, commit, reqOptions) => unwrap(await baseQueryPositional(query, variables, commit, reqOptions));
120
+ return {
121
+ pg,
122
+ db,
123
+ server,
124
+ teardown,
125
+ query
126
+ };
127
+ };
128
+ exports.getConnectionsWithServerUnwrapped = getConnectionsWithServerUnwrapped;
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { type GraphQLQueryOptions, type GraphQLTestContext, type GetConnectionsInput, type GraphQLResponse, type GraphQLQueryFn, type GraphQLQueryFnObj, type GraphQLQueryUnwrappedFn, type GraphQLQueryUnwrappedFnObj, } from '@constructive-io/graphql-test';
2
+ export * from './types';
3
+ export { createTestServer, getTestPool } from './server';
4
+ export { getConnectionsWithServer, getConnectionsWithServerObject, getConnectionsWithServerUnwrapped } from './get-connections';
5
+ export { seed, snapshot } from 'pgsql-test';
package/index.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.snapshot = exports.seed = exports.getConnectionsWithServerUnwrapped = exports.getConnectionsWithServerObject = exports.getConnectionsWithServer = exports.getTestPool = exports.createTestServer = void 0;
18
+ // Export our types
19
+ __exportStar(require("./types"), exports);
20
+ // Export server utilities
21
+ var server_1 = require("./server");
22
+ Object.defineProperty(exports, "createTestServer", { enumerable: true, get: function () { return server_1.createTestServer; } });
23
+ Object.defineProperty(exports, "getTestPool", { enumerable: true, get: function () { return server_1.getTestPool; } });
24
+ // Export connection functions with server support
25
+ var get_connections_1 = require("./get-connections");
26
+ Object.defineProperty(exports, "getConnectionsWithServer", { enumerable: true, get: function () { return get_connections_1.getConnectionsWithServer; } });
27
+ Object.defineProperty(exports, "getConnectionsWithServerObject", { enumerable: true, get: function () { return get_connections_1.getConnectionsWithServerObject; } });
28
+ Object.defineProperty(exports, "getConnectionsWithServerUnwrapped", { enumerable: true, get: function () { return get_connections_1.getConnectionsWithServerUnwrapped; } });
29
+ // Re-export seed and snapshot utilities from pgsql-test
30
+ var pgsql_test_1 = require("pgsql-test");
31
+ Object.defineProperty(exports, "seed", { enumerable: true, get: function () { return pgsql_test_1.seed; } });
32
+ Object.defineProperty(exports, "snapshot", { enumerable: true, get: function () { return pgsql_test_1.snapshot; } });
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@constructive-io/playwright-test",
3
+ "version": "0.2.0",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "Constructive Playwright Testing with HTTP server support",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/constructive",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/constructive"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/constructive/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "playwright test",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "devDependencies": {
32
+ "@playwright/test": "^1.57.0",
33
+ "@types/express": "^5.0.6",
34
+ "@types/pg": "^8.16.0",
35
+ "makage": "^0.1.10"
36
+ },
37
+ "dependencies": {
38
+ "@constructive-io/graphql-env": "^2.8.19",
39
+ "@constructive-io/graphql-server": "^2.16.0",
40
+ "@constructive-io/graphql-test": "^2.13.15",
41
+ "@constructive-io/graphql-types": "^2.12.13",
42
+ "@pgpmjs/types": "^2.14.1",
43
+ "express": "^5.2.1",
44
+ "graphile-test": "^2.13.14",
45
+ "pg": "^8.16.3",
46
+ "pg-cache": "^1.6.15",
47
+ "pgsql-test": "^2.24.13"
48
+ },
49
+ "keywords": [
50
+ "testing",
51
+ "playwright",
52
+ "graphql",
53
+ "graphile",
54
+ "constructive",
55
+ "e2e",
56
+ "integration"
57
+ ],
58
+ "gitHead": "049ab1b8c49c5711ede9a47c8e8dbb7bbbdf5a1f"
59
+ }
package/server.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { PgpmOptions } from '@pgpmjs/types';
2
+ import { Pool } from 'pg';
3
+ import type { ServerInfo, PlaywrightServerOptions } from './types';
4
+ /**
5
+ * Create a test server for Playwright testing
6
+ *
7
+ * This creates an Express server with the Constructive GraphQL middleware
8
+ * configured with enableServicesApi: false to bypass domain routing.
9
+ */
10
+ export declare const createTestServer: (opts: PgpmOptions, serverOpts?: PlaywrightServerOptions) => Promise<ServerInfo>;
11
+ /**
12
+ * Get the PostgreSQL pool for the test server
13
+ */
14
+ export declare const getTestPool: (opts: PgpmOptions) => Pool;
package/server.js ADDED
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getTestPool = exports.createTestServer = void 0;
7
+ const graphql_server_1 = require("@constructive-io/graphql-server");
8
+ const express_1 = __importDefault(require("express"));
9
+ const http_1 = require("http");
10
+ const pg_cache_1 = require("pg-cache");
11
+ /**
12
+ * Find an available port starting from the given port
13
+ */
14
+ const findAvailablePort = async (startPort) => {
15
+ return new Promise((resolve, reject) => {
16
+ const server = (0, http_1.createServer)();
17
+ server.listen(startPort, () => {
18
+ const address = server.address();
19
+ const port = typeof address === 'object' && address ? address.port : startPort;
20
+ server.close(() => resolve(port));
21
+ });
22
+ server.on('error', (err) => {
23
+ if (err.code === 'EADDRINUSE') {
24
+ resolve(findAvailablePort(startPort + 1));
25
+ }
26
+ else {
27
+ reject(err);
28
+ }
29
+ });
30
+ });
31
+ };
32
+ /**
33
+ * Create a test server for Playwright testing
34
+ *
35
+ * This creates an Express server with the Constructive GraphQL middleware
36
+ * configured with enableServicesApi: false to bypass domain routing.
37
+ */
38
+ const createTestServer = async (opts, serverOpts = {}) => {
39
+ const host = serverOpts.host ?? 'localhost';
40
+ const requestedPort = serverOpts.port ?? 0;
41
+ const port = requestedPort === 0 ? await findAvailablePort(5555) : requestedPort;
42
+ const app = (0, express_1.default)();
43
+ // Create middleware with enableServicesApi: false to bypass domain routing
44
+ const api = (0, graphql_server_1.createApiMiddleware)(opts);
45
+ const authenticate = (0, graphql_server_1.createAuthenticateMiddleware)(opts);
46
+ // Basic middleware setup
47
+ app.use((0, graphql_server_1.cors)('*'));
48
+ app.use(api);
49
+ app.use(authenticate);
50
+ app.use((0, graphql_server_1.graphile)(opts));
51
+ // Create HTTP server
52
+ const httpServer = await new Promise((resolve, reject) => {
53
+ const server = app.listen(port, host, () => {
54
+ resolve(server);
55
+ });
56
+ server.on('error', reject);
57
+ });
58
+ const actualPort = httpServer.address().port;
59
+ const stop = async () => {
60
+ return new Promise((resolve, reject) => {
61
+ httpServer.close((err) => {
62
+ if (err)
63
+ reject(err);
64
+ else
65
+ resolve();
66
+ });
67
+ });
68
+ };
69
+ return {
70
+ httpServer,
71
+ url: `http://${host}:${actualPort}`,
72
+ graphqlUrl: `http://${host}:${actualPort}/graphql`,
73
+ port: actualPort,
74
+ host,
75
+ stop
76
+ };
77
+ };
78
+ exports.createTestServer = createTestServer;
79
+ /**
80
+ * Get the PostgreSQL pool for the test server
81
+ */
82
+ const getTestPool = (opts) => {
83
+ return (0, pg_cache_1.getPgPool)(opts.pg);
84
+ };
85
+ exports.getTestPool = getTestPool;
package/types.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ import type { Server } from 'http';
2
+ import type { PgTestClient } from 'pgsql-test/test-client';
3
+ import type { GetConnectionsInput, GraphQLQueryFn, GraphQLQueryFnObj } from '@constructive-io/graphql-test';
4
+ /**
5
+ * Options for creating a Playwright test server
6
+ */
7
+ export interface PlaywrightServerOptions {
8
+ /** Port to run the server on (defaults to random available port) */
9
+ port?: number;
10
+ /** Host to bind the server to (defaults to localhost) */
11
+ host?: string;
12
+ }
13
+ /**
14
+ * Input options for getConnectionsWithServer
15
+ */
16
+ export interface GetConnectionsWithServerInput extends GetConnectionsInput {
17
+ /** Server configuration options */
18
+ server?: PlaywrightServerOptions;
19
+ }
20
+ /**
21
+ * Server information returned by getConnectionsWithServer
22
+ */
23
+ export interface ServerInfo {
24
+ /** The HTTP server instance */
25
+ httpServer: Server;
26
+ /** The base URL of the server (e.g., http://localhost:5555) */
27
+ url: string;
28
+ /** The GraphQL endpoint URL (e.g., http://localhost:5555/graphql) */
29
+ graphqlUrl: string;
30
+ /** The port the server is running on */
31
+ port: number;
32
+ /** The host the server is bound to */
33
+ host: string;
34
+ /** Stop the server */
35
+ stop: () => Promise<void>;
36
+ }
37
+ /**
38
+ * Result from getConnectionsWithServer
39
+ */
40
+ export interface GetConnectionsWithServerResult {
41
+ /** PostgreSQL client for direct database access */
42
+ pg: PgTestClient;
43
+ /** Database client for test operations */
44
+ db: PgTestClient;
45
+ /** Server information including URL and stop function */
46
+ server: ServerInfo;
47
+ /** GraphQL query function (positional API) */
48
+ query: GraphQLQueryFn;
49
+ /** Teardown function to clean up database and server */
50
+ teardown: () => Promise<void>;
51
+ }
52
+ /**
53
+ * Result from getConnectionsWithServerObject (object-based query API)
54
+ */
55
+ export interface GetConnectionsWithServerObjectResult {
56
+ /** PostgreSQL client for direct database access */
57
+ pg: PgTestClient;
58
+ /** Database client for test operations */
59
+ db: PgTestClient;
60
+ /** Server information including URL and stop function */
61
+ server: ServerInfo;
62
+ /** GraphQL query function (object API) */
63
+ query: GraphQLQueryFnObj;
64
+ /** Teardown function to clean up database and server */
65
+ teardown: () => Promise<void>;
66
+ }
package/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });