@constructive-io/graphql-explorer 2.10.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/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,89 @@
1
+ # @constructive-io/graphql-explorer
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/@constructive-io/graphql-explorer"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=packages%2Fexplorer%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ ---
16
+
17
+ ## Education and Tutorials
18
+
19
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
20
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
21
+
22
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
23
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
24
+
25
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
26
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
27
+
28
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
29
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
30
+
31
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
32
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
33
+
34
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
35
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
36
+
37
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
38
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
39
+
40
+ ## Related Constructive Tooling
41
+
42
+ ### 🧪 Testing
43
+
44
+ * [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.
45
+ * [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.
46
+ * [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.
47
+ * [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.
48
+
49
+ ### 🧠 Parsing & AST
50
+
51
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
52
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
53
+ * [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.
54
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
55
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
56
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
57
+ * [pg-ast](https://www.npmjs.com/package/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
58
+
59
+ ### 🚀 API & Dev Tools
60
+
61
+ * [@constructive-io/graphql-server](https://github.com/constructive-io/constructive/tree/main/graphql/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
62
+ * [@constructive-io/graphql-explorer](https://github.com/constructive-io/constructive/tree/main/graphql/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
63
+
64
+ ### 🔁 Streaming & Uploads
65
+
66
+ * [etag-hash](https://github.com/constructive-io/constructive/tree/main/streaming/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
67
+ * [etag-stream](https://github.com/constructive-io/constructive/tree/main/streaming/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
68
+ * [uuid-hash](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
69
+ * [uuid-stream](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
70
+ * [@constructive-io/s3-streamer](https://github.com/constructive-io/constructive/tree/main/streaming/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
71
+ * [@constructive-io/upload-names](https://github.com/constructive-io/constructive/tree/main/streaming/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
72
+
73
+ ### 🧰 CLI & Codegen
74
+
75
+ * [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.
76
+ * [@constructive-io/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing Constructive projects—supports database scaffolding, migrations, seeding, code generation, and automation.
77
+ * [@constructive-io/graphql-codegen](https://github.com/constructive-io/constructive/tree/main/graphql/codegen): **✨ GraphQL code generation** (types, operations, SDK) from schema/endpoint introspection.
78
+ * [@constructive-io/query-builder](https://github.com/constructive-io/constructive/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
79
+ * [@constructive-io/graphql-query](https://github.com/constructive-io/constructive/tree/main/graphql/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
80
+
81
+ ## Credits
82
+
83
+ **🛠 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).**
84
+
85
+ ## Disclaimer
86
+
87
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
88
+
89
+ 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.
package/esm/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './server';
package/esm/render.js ADDED
@@ -0,0 +1,73 @@
1
+ export const printHtml = ({ title, children, rootUrl }) => {
2
+ return `
3
+ <!DOCTYPE html>
4
+ <html lang="en">
5
+ <head>
6
+ <meta charset="UTF-8" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
8
+ <title>${title}</title>
9
+ <script src="https://cdn.tailwindcss.com"></script>
10
+ <style>
11
+ .text-brand {
12
+ color: #01a1ff;
13
+ }
14
+ .text-brand:hover {
15
+ text-decoration: underline;
16
+ }
17
+ h1.text-brand:hover {
18
+ text-decoration: none;
19
+ }
20
+ </style>
21
+ </head>
22
+ <body class="bg-gray-50 text-gray-900 font-sans p-6 text-sm leading-tight">
23
+ <div class="max-w-4xl mx-auto space-y-4">
24
+ <header class="flex items-center space-x-2">
25
+ <a href="${rootUrl}" class="shrink-0 w-6 h-6 sm:w-8 sm:h-8" aria-label="Home">
26
+ <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64.95 61.24">
27
+ <path d="M16.36 43.47a14.56 14.56 0 01-8.79 0A11.16 11.16 0 011 38.34a8.83 8.83 0 01-.45-1A8.09 8.09 0 01.76 31a10.08 10.08 0 013.68-4.17 6.23 6.23 0 01-.24-.65A8.17 8.17 0 014.68 20a10.47 10.47 0 014.53-4.53 13.25 13.25 0 012.12-.9 12.35 12.35 0 012.5-7.45A17.35 17.35 0 0122.7 1a22.38 22.38 0 0113.48 0 17.07 17.07 0 019.42 6.9 18.75 18.75 0 019.8.4 14 14 0 018.29 6.46 10.17 10.17 0 01.78 1.83 10 10 0 01-.59 7.56 13.05 13.05 0 01-5.64 5.64A17.05 17.05 0 0155.4 31l-39 12.45zM64.92 36q-1.05 4.48-10.54 7.63l-.36.12L15 56.22a9.87 9.87 0 01-1.91.41C6.88 57.55 2.16 54.78 0 51.24a8.2 8.2 0 00.56 3.2 7.45 7.45 0 00.45 1 11.09 11.09 0 006.56 5.13 14.64 14.64 0 008.79 0l39-12.45a17.07 17.07 0 002.84-1.2 13 13 0 005.64-5.63 10.19 10.19 0 001-5.27zm0-8.59q-1.05 4.49-10.54 7.64l-.36.12L15 47.64a9.84 9.84 0 01-1.91.4C6.88 49 2.16 46.19 0 42.65a8.28 8.28 0 00.56 3.21 8.83 8.83 0 00.45 1A11.16 11.16 0 007.57 52a14.64 14.64 0 008.79 0l39-12.45a17.05 17.05 0 002.84-1.19 13.05 13.05 0 005.64-5.64 10.17 10.17 0 001-5.27zM9 39.13a10.11 10.11 0 006 0l39-12.45a12.25 12.25 0 002.06-.87 8.52 8.52 0 003.7-3.62 5.52 5.52 0 00.37-4.19 6.6 6.6 0 00-.46-1A9.57 9.57 0 0054 12.68a14.17 14.17 0 00-8.48 0l-.16.05-.2.07-2 .69-.84-2c-.07-.16-.12-.27-.14-.33l-.18-.27a12.26 12.26 0 00-7.2-5.51 17.85 17.85 0 00-10.73 0 12.81 12.81 0 00-6.56 4.44 7.58 7.58 0 00-1.47 6l.45 2.29-2.31.4c-.27 0-.5.09-.68.13s-.46.12-.66.19a8.31 8.31 0 00-1.47.62A5.88 5.88 0 008.78 22a3.71 3.71 0 00-.24 2.79 3.77 3.77 0 00.31.7c.07.13.15.26.24.4.1.14.19.27.29.39l2 2.44-3 1.13a9.92 9.92 0 00-.94.44 5.79 5.79 0 00-2.59 2.57 3.57 3.57 0 00-.1 2.83 4.9 4.9 0 00.22.48 6.69 6.69 0 003.92 3z" fill="#01a1ff"/></svg>
28
+ </a>
29
+ <h1 class="text-xl font-semibold text-brand">${title}</h1>
30
+ </header>
31
+ <main class="overflow-auto max-h-[90vh]">
32
+ ${children}
33
+ </main>
34
+ </div>
35
+ </body>
36
+ </html>
37
+ `.trim();
38
+ };
39
+ export const printDatabases = ({ databases, req, port }) => {
40
+ const rootUrl = `${req.protocol}://${req.hostname}:${port}`;
41
+ const links = databases
42
+ .map((d) => {
43
+ const url = `${req.protocol}://${d.datname}.${req.hostname}:${port}`;
44
+ return `<a href="${url}" class="text-brand hover:underline block">${d.datname}</a>`;
45
+ })
46
+ .join('');
47
+ return printHtml({
48
+ title: 'Databases',
49
+ rootUrl,
50
+ children: `
51
+ <hr class="border-gray-300 mb-2" />
52
+ ${links}
53
+ `
54
+ });
55
+ };
56
+ export const printSchemas = ({ dbName, schemas, req, hostname, port }) => {
57
+ const rootUrl = `${req.protocol}://${hostname}:${port}`;
58
+ const links = schemas
59
+ .map((d) => {
60
+ const url = `${req.protocol}://${d.table_schema}.${req.hostname}:${port}/graphiql`;
61
+ return `<a href="${url}" class="text-brand hover:underline block">${d.table_schema}</a>`;
62
+ })
63
+ .join('');
64
+ return printHtml({
65
+ title: `Schemas in ${dbName}`,
66
+ rootUrl,
67
+ children: `
68
+ <a href="${rootUrl}" class="text-xs text-brand hover:underline mb-2 inline-block">&larr; Back to root</a>
69
+ <hr class="border-gray-300 mb-2" />
70
+ ${links}
71
+ `
72
+ });
73
+ };
@@ -0,0 +1,53 @@
1
+ import Streamer from '@constructive-io/s3-streamer';
2
+ import uploadNames from '@constructive-io/upload-names';
3
+ export class UploadHandler {
4
+ options;
5
+ streamer;
6
+ constructor(options) {
7
+ this.options = options;
8
+ this.streamer = new Streamer({
9
+ defaultBucket: options.bucketName,
10
+ awsRegion: options.awsRegion,
11
+ awsSecretKey: options.awsSecretKey,
12
+ awsAccessKey: options.awsAccessKey,
13
+ minioEndpoint: options.minioEndpoint
14
+ });
15
+ }
16
+ async handleUpload(upload, _args, _context, info) {
17
+ const { uploadPlugin: { tags, type } } = info;
18
+ const readStream = upload.createReadStream();
19
+ const { filename, mimetype } = upload;
20
+ const rand = Math.random().toString(36).substring(2, 7) +
21
+ Math.random().toString(36).substring(2, 7);
22
+ const key = rand + '-' + uploadNames(filename);
23
+ const result = await this.streamer.upload({
24
+ readStream,
25
+ filename,
26
+ key,
27
+ bucket: this.options.bucketName
28
+ });
29
+ const url = result.upload.Location;
30
+ const { contentType, magic: { charset } } = result;
31
+ const typ = type || tags.type;
32
+ const mim = tags.mime
33
+ ? tags.mime.trim().split(',').map((a) => a.trim())
34
+ : typ === 'image'
35
+ ? ['image/jpg', 'image/jpeg', 'image/png', 'image/svg+xml']
36
+ : [];
37
+ if (mim.length && !mim.includes(contentType)) {
38
+ throw new Error(`UPLOAD_MIMETYPE ${mim.join(',')}`);
39
+ }
40
+ switch (typ) {
41
+ case 'image':
42
+ case 'upload':
43
+ return {
44
+ filename,
45
+ mime: contentType,
46
+ url
47
+ };
48
+ case 'attachment':
49
+ default:
50
+ return url;
51
+ }
52
+ }
53
+ }
package/esm/run.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { getEnvOptions } from '@constructive-io/graphql-env';
3
+ import { GraphQLExplorer as server } from './server';
4
+ server(getEnvOptions());
package/esm/server.js ADDED
@@ -0,0 +1,159 @@
1
+ import { getEnvOptions } from '@constructive-io/graphql-env';
2
+ import { cors, healthz, poweredBy } from '@pgpmjs/server-utils';
3
+ import { middleware as parseDomains } from '@constructive-io/url-domains';
4
+ import express from 'express';
5
+ import { graphileCache } from 'graphile-cache';
6
+ import graphqlUpload from 'graphql-upload';
7
+ // Scalar
8
+ import { getPgPool } from 'pg-cache';
9
+ import { getPgEnvOptions } from 'pg-env';
10
+ import { postgraphile } from 'postgraphile';
11
+ import { printDatabases, printSchemas } from './render';
12
+ import { getGraphileSettings } from './settings';
13
+ export const GraphQLExplorer = (rawOpts = {}) => {
14
+ const opts = getEnvOptions(rawOpts);
15
+ const { pg, server } = opts;
16
+ const getGraphileInstanceObj = (dbname, schemaname) => {
17
+ const key = `${dbname}.${schemaname}`;
18
+ if (graphileCache.has(key)) {
19
+ return graphileCache.get(key);
20
+ }
21
+ const settings = {
22
+ ...getGraphileSettings({
23
+ ...opts,
24
+ graphile: { schema: schemaname },
25
+ }),
26
+ graphqlRoute: '/graphql',
27
+ graphiqlRoute: '/graphiql',
28
+ };
29
+ const pgPool = getPgPool(getPgEnvOptions({
30
+ ...opts.pg,
31
+ database: dbname,
32
+ }));
33
+ const handler = postgraphile(pgPool, schemaname, settings);
34
+ const obj = {
35
+ pgPool,
36
+ pgPoolKey: dbname,
37
+ handler,
38
+ };
39
+ graphileCache.set(key, obj);
40
+ return obj;
41
+ };
42
+ const app = express();
43
+ healthz(app);
44
+ cors(app, server.origin);
45
+ app.use(parseDomains());
46
+ app.use(poweredBy('constructive'));
47
+ app.use(graphqlUpload.graphqlUploadExpress());
48
+ app.use(async (req, res, next) => {
49
+ if (req.urlDomains?.subdomains.length === 1) {
50
+ const [dbName] = req.urlDomains.subdomains;
51
+ try {
52
+ const pgPool = getPgPool(getPgEnvOptions({
53
+ ...opts.pg,
54
+ database: dbName,
55
+ }));
56
+ const results = await pgPool.query(`
57
+ SELECT s.nspname AS table_schema
58
+ FROM pg_catalog.pg_namespace s
59
+ WHERE s.nspname !~ '^pg_' AND s.nspname NOT IN ('information_schema');
60
+ `);
61
+ res.send(printSchemas({
62
+ dbName,
63
+ schemas: results.rows,
64
+ req,
65
+ hostname: server.host,
66
+ port: server.port,
67
+ }));
68
+ return;
69
+ }
70
+ catch (e) {
71
+ if (e.message?.match(/does not exist/)) {
72
+ res.status(404).send('DB Not found');
73
+ return;
74
+ }
75
+ console.error(e);
76
+ res.status(500).send('Something happened...');
77
+ return;
78
+ }
79
+ }
80
+ return next();
81
+ });
82
+ app.use(async (req, res, next) => {
83
+ if (req.urlDomains?.subdomains.length === 2) {
84
+ const [, dbName] = req.urlDomains.subdomains;
85
+ try {
86
+ const pgPool = getPgPool(getPgEnvOptions({
87
+ ...opts.pg,
88
+ database: dbName,
89
+ }));
90
+ await pgPool.query('SELECT 1;');
91
+ }
92
+ catch (e) {
93
+ if (e.message?.match(/does not exist/)) {
94
+ res.status(404).send('DB Not found');
95
+ return;
96
+ }
97
+ console.error(e);
98
+ res.status(500).send('Something happened...');
99
+ return;
100
+ }
101
+ }
102
+ return next();
103
+ });
104
+ app.use(async (req, res, next) => {
105
+ if (req.urlDomains?.subdomains.length === 2) {
106
+ const [schemaName, dbName] = req.urlDomains.subdomains;
107
+ try {
108
+ const { handler } = getGraphileInstanceObj(dbName, schemaName);
109
+ handler(req, res, next);
110
+ return;
111
+ }
112
+ catch (e) {
113
+ res.status(500).send(e.message);
114
+ return;
115
+ }
116
+ }
117
+ return next();
118
+ });
119
+ app.use(async (req, res, next) => {
120
+ if (req.urlDomains?.subdomains.length === 2 && req.url === '/flush') {
121
+ const [schemaName, dbName] = req.urlDomains.subdomains;
122
+ const key = `${dbName}.${schemaName}`;
123
+ graphileCache.delete(key);
124
+ res.status(200).send('OK');
125
+ return;
126
+ }
127
+ return next();
128
+ });
129
+ app.use(async (req, res, next) => {
130
+ if (req.urlDomains?.subdomains.length === 0) {
131
+ try {
132
+ const rootPgPool = getPgPool(getPgEnvOptions({
133
+ ...opts.pg,
134
+ database: opts.pg.user, // is this to get postgres?
135
+ }));
136
+ const results = await rootPgPool.query(`
137
+ SELECT * FROM pg_catalog.pg_database
138
+ WHERE datistemplate = FALSE AND datname != 'postgres' AND datname !~ '^pg_'
139
+ `);
140
+ res.send(printDatabases({ databases: results.rows, req, port: server.port }));
141
+ return;
142
+ }
143
+ catch (e) {
144
+ if (e.message?.match(/does not exist/)) {
145
+ res.status(404).send('DB Not found');
146
+ return;
147
+ }
148
+ console.error(e);
149
+ res.status(500).send('Something happened...');
150
+ return;
151
+ }
152
+ }
153
+ return next();
154
+ });
155
+ app.listen(server.port, server.host, () => {
156
+ console.log(`app listening at http://${server.host}:${server.port}`);
157
+ });
158
+ return app;
159
+ };
@@ -0,0 +1,10 @@
1
+ import { getEnvOptions } from '@constructive-io/graphql-env';
2
+ import { getGraphileSettings as getSettings } from 'graphile-settings';
3
+ export const getGraphileSettings = (rawOpts) => {
4
+ const opts = getEnvOptions(rawOpts);
5
+ const baseOptions = getSettings(opts);
6
+ baseOptions.pgSettings = async function pgSettings(_req) {
7
+ return { role: opts.pg?.user ?? 'postgres' };
8
+ };
9
+ return baseOptions;
10
+ };
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './server';
package/index.js ADDED
@@ -0,0 +1,17 @@
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
+ __exportStar(require("./server"), exports);
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@constructive-io/graphql-explorer",
3
+ "version": "2.10.5",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "Constructive GraphQL Explorer",
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
+ "bin": {
23
+ "explorer": "./run.js"
24
+ },
25
+ "scripts": {
26
+ "clean": "makage clean",
27
+ "prepack": "npm run build",
28
+ "build": "makage build",
29
+ "build:dev": "makage build --dev",
30
+ "dev": "ts-node src/run.ts",
31
+ "dev:watch": "nodemon --watch src --ext ts --exec ts-node src/run.ts",
32
+ "lint": "eslint . --fix",
33
+ "test": "jest --passWithNoTests",
34
+ "test:watch": "jest --watch"
35
+ },
36
+ "dependencies": {
37
+ "@constructive-io/graphql-env": "^2.8.4",
38
+ "@constructive-io/graphql-types": "^2.12.4",
39
+ "@constructive-io/s3-streamer": "^2.8.5",
40
+ "@constructive-io/upload-names": "^2.3.3",
41
+ "@constructive-io/url-domains": "^2.3.4",
42
+ "@pgpmjs/server-utils": "^2.8.6",
43
+ "@pgpmjs/types": "^2.12.4",
44
+ "express": "^5.1.0",
45
+ "graphile-build": "^4.14.1",
46
+ "graphile-cache": "^1.6.6",
47
+ "graphile-settings": "^2.9.5",
48
+ "graphql": "15.10.1",
49
+ "graphql-upload": "^13.0.0",
50
+ "pg-cache": "^1.6.6",
51
+ "pg-env": "^1.2.3",
52
+ "postgraphile": "^4.14.1"
53
+ },
54
+ "devDependencies": {
55
+ "@types/express": "^5.0.6",
56
+ "@types/graphql-upload": "^8.0.12",
57
+ "makage": "^0.1.8",
58
+ "nodemon": "^3.1.10",
59
+ "ts-node": "^10.9.2"
60
+ },
61
+ "keywords": [
62
+ "graphql",
63
+ "explorer",
64
+ "ui",
65
+ "constructive",
66
+ "interface"
67
+ ],
68
+ "gitHead": "22cfe32e994e26a6490e04e28bab26d1e7e6345c"
69
+ }
package/render.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { Request } from 'express';
2
+ interface Database {
3
+ datname: string;
4
+ }
5
+ interface Schema {
6
+ table_schema: string;
7
+ }
8
+ interface PrintDatabasesParams {
9
+ databases: Database[];
10
+ req: Request;
11
+ port: number;
12
+ }
13
+ interface PrintSchemasParams {
14
+ dbName: string;
15
+ schemas: Schema[];
16
+ req: Request;
17
+ hostname: string;
18
+ port: number;
19
+ }
20
+ interface PrintHtmlParams {
21
+ title: string;
22
+ children: string;
23
+ rootUrl: string;
24
+ }
25
+ export declare const printHtml: ({ title, children, rootUrl }: PrintHtmlParams) => string;
26
+ export declare const printDatabases: ({ databases, req, port }: PrintDatabasesParams) => string;
27
+ export declare const printSchemas: ({ dbName, schemas, req, hostname, port }: PrintSchemasParams) => string;
28
+ export {};
package/render.js ADDED
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.printSchemas = exports.printDatabases = exports.printHtml = void 0;
4
+ const printHtml = ({ title, children, rootUrl }) => {
5
+ return `
6
+ <!DOCTYPE html>
7
+ <html lang="en">
8
+ <head>
9
+ <meta charset="UTF-8" />
10
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
11
+ <title>${title}</title>
12
+ <script src="https://cdn.tailwindcss.com"></script>
13
+ <style>
14
+ .text-brand {
15
+ color: #01a1ff;
16
+ }
17
+ .text-brand:hover {
18
+ text-decoration: underline;
19
+ }
20
+ h1.text-brand:hover {
21
+ text-decoration: none;
22
+ }
23
+ </style>
24
+ </head>
25
+ <body class="bg-gray-50 text-gray-900 font-sans p-6 text-sm leading-tight">
26
+ <div class="max-w-4xl mx-auto space-y-4">
27
+ <header class="flex items-center space-x-2">
28
+ <a href="${rootUrl}" class="shrink-0 w-6 h-6 sm:w-8 sm:h-8" aria-label="Home">
29
+ <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64.95 61.24">
30
+ <path d="M16.36 43.47a14.56 14.56 0 01-8.79 0A11.16 11.16 0 011 38.34a8.83 8.83 0 01-.45-1A8.09 8.09 0 01.76 31a10.08 10.08 0 013.68-4.17 6.23 6.23 0 01-.24-.65A8.17 8.17 0 014.68 20a10.47 10.47 0 014.53-4.53 13.25 13.25 0 012.12-.9 12.35 12.35 0 012.5-7.45A17.35 17.35 0 0122.7 1a22.38 22.38 0 0113.48 0 17.07 17.07 0 019.42 6.9 18.75 18.75 0 019.8.4 14 14 0 018.29 6.46 10.17 10.17 0 01.78 1.83 10 10 0 01-.59 7.56 13.05 13.05 0 01-5.64 5.64A17.05 17.05 0 0155.4 31l-39 12.45zM64.92 36q-1.05 4.48-10.54 7.63l-.36.12L15 56.22a9.87 9.87 0 01-1.91.41C6.88 57.55 2.16 54.78 0 51.24a8.2 8.2 0 00.56 3.2 7.45 7.45 0 00.45 1 11.09 11.09 0 006.56 5.13 14.64 14.64 0 008.79 0l39-12.45a17.07 17.07 0 002.84-1.2 13 13 0 005.64-5.63 10.19 10.19 0 001-5.27zm0-8.59q-1.05 4.49-10.54 7.64l-.36.12L15 47.64a9.84 9.84 0 01-1.91.4C6.88 49 2.16 46.19 0 42.65a8.28 8.28 0 00.56 3.21 8.83 8.83 0 00.45 1A11.16 11.16 0 007.57 52a14.64 14.64 0 008.79 0l39-12.45a17.05 17.05 0 002.84-1.19 13.05 13.05 0 005.64-5.64 10.17 10.17 0 001-5.27zM9 39.13a10.11 10.11 0 006 0l39-12.45a12.25 12.25 0 002.06-.87 8.52 8.52 0 003.7-3.62 5.52 5.52 0 00.37-4.19 6.6 6.6 0 00-.46-1A9.57 9.57 0 0054 12.68a14.17 14.17 0 00-8.48 0l-.16.05-.2.07-2 .69-.84-2c-.07-.16-.12-.27-.14-.33l-.18-.27a12.26 12.26 0 00-7.2-5.51 17.85 17.85 0 00-10.73 0 12.81 12.81 0 00-6.56 4.44 7.58 7.58 0 00-1.47 6l.45 2.29-2.31.4c-.27 0-.5.09-.68.13s-.46.12-.66.19a8.31 8.31 0 00-1.47.62A5.88 5.88 0 008.78 22a3.71 3.71 0 00-.24 2.79 3.77 3.77 0 00.31.7c.07.13.15.26.24.4.1.14.19.27.29.39l2 2.44-3 1.13a9.92 9.92 0 00-.94.44 5.79 5.79 0 00-2.59 2.57 3.57 3.57 0 00-.1 2.83 4.9 4.9 0 00.22.48 6.69 6.69 0 003.92 3z" fill="#01a1ff"/></svg>
31
+ </a>
32
+ <h1 class="text-xl font-semibold text-brand">${title}</h1>
33
+ </header>
34
+ <main class="overflow-auto max-h-[90vh]">
35
+ ${children}
36
+ </main>
37
+ </div>
38
+ </body>
39
+ </html>
40
+ `.trim();
41
+ };
42
+ exports.printHtml = printHtml;
43
+ const printDatabases = ({ databases, req, port }) => {
44
+ const rootUrl = `${req.protocol}://${req.hostname}:${port}`;
45
+ const links = databases
46
+ .map((d) => {
47
+ const url = `${req.protocol}://${d.datname}.${req.hostname}:${port}`;
48
+ return `<a href="${url}" class="text-brand hover:underline block">${d.datname}</a>`;
49
+ })
50
+ .join('');
51
+ return (0, exports.printHtml)({
52
+ title: 'Databases',
53
+ rootUrl,
54
+ children: `
55
+ <hr class="border-gray-300 mb-2" />
56
+ ${links}
57
+ `
58
+ });
59
+ };
60
+ exports.printDatabases = printDatabases;
61
+ const printSchemas = ({ dbName, schemas, req, hostname, port }) => {
62
+ const rootUrl = `${req.protocol}://${hostname}:${port}`;
63
+ const links = schemas
64
+ .map((d) => {
65
+ const url = `${req.protocol}://${d.table_schema}.${req.hostname}:${port}/graphiql`;
66
+ return `<a href="${url}" class="text-brand hover:underline block">${d.table_schema}</a>`;
67
+ })
68
+ .join('');
69
+ return (0, exports.printHtml)({
70
+ title: `Schemas in ${dbName}`,
71
+ rootUrl,
72
+ children: `
73
+ <a href="${rootUrl}" class="text-xs text-brand hover:underline mb-2 inline-block">&larr; Back to root</a>
74
+ <hr class="border-gray-300 mb-2" />
75
+ ${links}
76
+ `
77
+ });
78
+ };
79
+ exports.printSchemas = printSchemas;
@@ -0,0 +1,29 @@
1
+ import type { GraphQLResolveInfo } from 'graphql';
2
+ interface UploaderOptions {
3
+ bucketName: string;
4
+ awsRegion: string;
5
+ awsSecretKey: string;
6
+ awsAccessKey: string;
7
+ minioEndpoint?: string;
8
+ }
9
+ interface Upload {
10
+ createReadStream: () => NodeJS.ReadableStream;
11
+ filename: string;
12
+ mimetype: string;
13
+ encoding: string;
14
+ }
15
+ interface UploadPluginInfo {
16
+ tags: {
17
+ [key: string]: any;
18
+ };
19
+ type: string;
20
+ }
21
+ export declare class UploadHandler {
22
+ private options;
23
+ private streamer;
24
+ constructor(options: UploaderOptions);
25
+ handleUpload(upload: Upload, _args: any, _context: any, info: GraphQLResolveInfo & {
26
+ uploadPlugin: UploadPluginInfo;
27
+ }): Promise<any>;
28
+ }
29
+ export {};
@@ -0,0 +1,60 @@
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.UploadHandler = void 0;
7
+ const s3_streamer_1 = __importDefault(require("@constructive-io/s3-streamer"));
8
+ const upload_names_1 = __importDefault(require("@constructive-io/upload-names"));
9
+ class UploadHandler {
10
+ options;
11
+ streamer;
12
+ constructor(options) {
13
+ this.options = options;
14
+ this.streamer = new s3_streamer_1.default({
15
+ defaultBucket: options.bucketName,
16
+ awsRegion: options.awsRegion,
17
+ awsSecretKey: options.awsSecretKey,
18
+ awsAccessKey: options.awsAccessKey,
19
+ minioEndpoint: options.minioEndpoint
20
+ });
21
+ }
22
+ async handleUpload(upload, _args, _context, info) {
23
+ const { uploadPlugin: { tags, type } } = info;
24
+ const readStream = upload.createReadStream();
25
+ const { filename, mimetype } = upload;
26
+ const rand = Math.random().toString(36).substring(2, 7) +
27
+ Math.random().toString(36).substring(2, 7);
28
+ const key = rand + '-' + (0, upload_names_1.default)(filename);
29
+ const result = await this.streamer.upload({
30
+ readStream,
31
+ filename,
32
+ key,
33
+ bucket: this.options.bucketName
34
+ });
35
+ const url = result.upload.Location;
36
+ const { contentType, magic: { charset } } = result;
37
+ const typ = type || tags.type;
38
+ const mim = tags.mime
39
+ ? tags.mime.trim().split(',').map((a) => a.trim())
40
+ : typ === 'image'
41
+ ? ['image/jpg', 'image/jpeg', 'image/png', 'image/svg+xml']
42
+ : [];
43
+ if (mim.length && !mim.includes(contentType)) {
44
+ throw new Error(`UPLOAD_MIMETYPE ${mim.join(',')}`);
45
+ }
46
+ switch (typ) {
47
+ case 'image':
48
+ case 'upload':
49
+ return {
50
+ filename,
51
+ mime: contentType,
52
+ url
53
+ };
54
+ case 'attachment':
55
+ default:
56
+ return url;
57
+ }
58
+ }
59
+ }
60
+ exports.UploadHandler = UploadHandler;
package/run.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/run.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const graphql_env_1 = require("@constructive-io/graphql-env");
5
+ const server_1 = require("./server");
6
+ (0, server_1.GraphQLExplorer)((0, graphql_env_1.getEnvOptions)());
package/server.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { PgpmOptions } from '@pgpmjs/types';
2
+ import { Express } from 'express';
3
+ export declare const GraphQLExplorer: (rawOpts?: PgpmOptions) => Express;
package/server.js ADDED
@@ -0,0 +1,166 @@
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.GraphQLExplorer = void 0;
7
+ const graphql_env_1 = require("@constructive-io/graphql-env");
8
+ const server_utils_1 = require("@pgpmjs/server-utils");
9
+ const url_domains_1 = require("@constructive-io/url-domains");
10
+ const express_1 = __importDefault(require("express"));
11
+ const graphile_cache_1 = require("graphile-cache");
12
+ const graphql_upload_1 = __importDefault(require("graphql-upload"));
13
+ // Scalar
14
+ const pg_cache_1 = require("pg-cache");
15
+ const pg_env_1 = require("pg-env");
16
+ const postgraphile_1 = require("postgraphile");
17
+ const render_1 = require("./render");
18
+ const settings_1 = require("./settings");
19
+ const GraphQLExplorer = (rawOpts = {}) => {
20
+ const opts = (0, graphql_env_1.getEnvOptions)(rawOpts);
21
+ const { pg, server } = opts;
22
+ const getGraphileInstanceObj = (dbname, schemaname) => {
23
+ const key = `${dbname}.${schemaname}`;
24
+ if (graphile_cache_1.graphileCache.has(key)) {
25
+ return graphile_cache_1.graphileCache.get(key);
26
+ }
27
+ const settings = {
28
+ ...(0, settings_1.getGraphileSettings)({
29
+ ...opts,
30
+ graphile: { schema: schemaname },
31
+ }),
32
+ graphqlRoute: '/graphql',
33
+ graphiqlRoute: '/graphiql',
34
+ };
35
+ const pgPool = (0, pg_cache_1.getPgPool)((0, pg_env_1.getPgEnvOptions)({
36
+ ...opts.pg,
37
+ database: dbname,
38
+ }));
39
+ const handler = (0, postgraphile_1.postgraphile)(pgPool, schemaname, settings);
40
+ const obj = {
41
+ pgPool,
42
+ pgPoolKey: dbname,
43
+ handler,
44
+ };
45
+ graphile_cache_1.graphileCache.set(key, obj);
46
+ return obj;
47
+ };
48
+ const app = (0, express_1.default)();
49
+ (0, server_utils_1.healthz)(app);
50
+ (0, server_utils_1.cors)(app, server.origin);
51
+ app.use((0, url_domains_1.middleware)());
52
+ app.use((0, server_utils_1.poweredBy)('constructive'));
53
+ app.use(graphql_upload_1.default.graphqlUploadExpress());
54
+ app.use(async (req, res, next) => {
55
+ if (req.urlDomains?.subdomains.length === 1) {
56
+ const [dbName] = req.urlDomains.subdomains;
57
+ try {
58
+ const pgPool = (0, pg_cache_1.getPgPool)((0, pg_env_1.getPgEnvOptions)({
59
+ ...opts.pg,
60
+ database: dbName,
61
+ }));
62
+ const results = await pgPool.query(`
63
+ SELECT s.nspname AS table_schema
64
+ FROM pg_catalog.pg_namespace s
65
+ WHERE s.nspname !~ '^pg_' AND s.nspname NOT IN ('information_schema');
66
+ `);
67
+ res.send((0, render_1.printSchemas)({
68
+ dbName,
69
+ schemas: results.rows,
70
+ req,
71
+ hostname: server.host,
72
+ port: server.port,
73
+ }));
74
+ return;
75
+ }
76
+ catch (e) {
77
+ if (e.message?.match(/does not exist/)) {
78
+ res.status(404).send('DB Not found');
79
+ return;
80
+ }
81
+ console.error(e);
82
+ res.status(500).send('Something happened...');
83
+ return;
84
+ }
85
+ }
86
+ return next();
87
+ });
88
+ app.use(async (req, res, next) => {
89
+ if (req.urlDomains?.subdomains.length === 2) {
90
+ const [, dbName] = req.urlDomains.subdomains;
91
+ try {
92
+ const pgPool = (0, pg_cache_1.getPgPool)((0, pg_env_1.getPgEnvOptions)({
93
+ ...opts.pg,
94
+ database: dbName,
95
+ }));
96
+ await pgPool.query('SELECT 1;');
97
+ }
98
+ catch (e) {
99
+ if (e.message?.match(/does not exist/)) {
100
+ res.status(404).send('DB Not found');
101
+ return;
102
+ }
103
+ console.error(e);
104
+ res.status(500).send('Something happened...');
105
+ return;
106
+ }
107
+ }
108
+ return next();
109
+ });
110
+ app.use(async (req, res, next) => {
111
+ if (req.urlDomains?.subdomains.length === 2) {
112
+ const [schemaName, dbName] = req.urlDomains.subdomains;
113
+ try {
114
+ const { handler } = getGraphileInstanceObj(dbName, schemaName);
115
+ handler(req, res, next);
116
+ return;
117
+ }
118
+ catch (e) {
119
+ res.status(500).send(e.message);
120
+ return;
121
+ }
122
+ }
123
+ return next();
124
+ });
125
+ app.use(async (req, res, next) => {
126
+ if (req.urlDomains?.subdomains.length === 2 && req.url === '/flush') {
127
+ const [schemaName, dbName] = req.urlDomains.subdomains;
128
+ const key = `${dbName}.${schemaName}`;
129
+ graphile_cache_1.graphileCache.delete(key);
130
+ res.status(200).send('OK');
131
+ return;
132
+ }
133
+ return next();
134
+ });
135
+ app.use(async (req, res, next) => {
136
+ if (req.urlDomains?.subdomains.length === 0) {
137
+ try {
138
+ const rootPgPool = (0, pg_cache_1.getPgPool)((0, pg_env_1.getPgEnvOptions)({
139
+ ...opts.pg,
140
+ database: opts.pg.user, // is this to get postgres?
141
+ }));
142
+ const results = await rootPgPool.query(`
143
+ SELECT * FROM pg_catalog.pg_database
144
+ WHERE datistemplate = FALSE AND datname != 'postgres' AND datname !~ '^pg_'
145
+ `);
146
+ res.send((0, render_1.printDatabases)({ databases: results.rows, req, port: server.port }));
147
+ return;
148
+ }
149
+ catch (e) {
150
+ if (e.message?.match(/does not exist/)) {
151
+ res.status(404).send('DB Not found');
152
+ return;
153
+ }
154
+ console.error(e);
155
+ res.status(500).send('Something happened...');
156
+ return;
157
+ }
158
+ }
159
+ return next();
160
+ });
161
+ app.listen(server.port, server.host, () => {
162
+ console.log(`app listening at http://${server.host}:${server.port}`);
163
+ });
164
+ return app;
165
+ };
166
+ exports.GraphQLExplorer = GraphQLExplorer;
package/settings.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { ConstructiveOptions } from '@constructive-io/graphql-types';
2
+ import { PostGraphileOptions } from 'postgraphile';
3
+ export declare const getGraphileSettings: (rawOpts: ConstructiveOptions) => PostGraphileOptions;
package/settings.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getGraphileSettings = void 0;
4
+ const graphql_env_1 = require("@constructive-io/graphql-env");
5
+ const graphile_settings_1 = require("graphile-settings");
6
+ const getGraphileSettings = (rawOpts) => {
7
+ const opts = (0, graphql_env_1.getEnvOptions)(rawOpts);
8
+ const baseOptions = (0, graphile_settings_1.getGraphileSettings)(opts);
9
+ baseOptions.pgSettings = async function pgSettings(_req) {
10
+ return { role: opts.pg?.user ?? 'postgres' };
11
+ };
12
+ return baseOptions;
13
+ };
14
+ exports.getGraphileSettings = getGraphileSettings;