@fluxwp/plugin-kit 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # @fluxwp/plugin-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@fluxwp/plugin-kit)](https://www.npmjs.com/package/@fluxwp/plugin-kit)
4
+ [![license](https://img.shields.io/npm/l/@fluxwp/plugin-kit)](#license)
5
+
6
+ **Build wp-admin screens for your WordPress plugin in React and TypeScript**, with typed GraphQL
7
+ (WPGraphQL) queries, persisted queries and server-side preloaded data. Your screens open inside the same
8
+ fast single-page admin shell as the [FluxWP](https://fluxwp.com) plugins: no page reload between screens,
9
+ light / dark theme, translations.
10
+
11
+ - **Tiny bundles.** React, React Query, i18next and the FluxWP UI kit come from a shared runtime that the
12
+ Flux GraphQL plugin loads once per page. A plugin screen is usually a few KB.
13
+ - **End-to-end types.** `flx-kit codegen` turns your `.graphql` operations into TypeScript types and
14
+ ready-to-use operation constants, checked against the site's schema.
15
+ - **Fast first paint.** PHP preloads the first query, so the screen renders without a spinner.
16
+ - **Vite preset.** `fluxScreens()` does the wiring: runtime imports, scoped CSS, code splitting.
17
+
18
+ Needs the **Flux GraphQL** plugin (`flx-graphql` 0.5 or newer) on the WordPress site.
19
+
20
+ ## Install
21
+
22
+ ```sh
23
+ npm i -D @fluxwp/plugin-kit react @tanstack/react-query react-i18next typescript vite
24
+ # or: bun add -d … / pnpm add -D …
25
+ ```
26
+
27
+ ## Project layout
28
+
29
+ ```
30
+ my-plugin/
31
+ my-plugin.php registers the screen and the persisted queries (below)
32
+ graphql/operations/FlxMyOrders.graphql
33
+ graphql/schema.graphql your own GraphQL types, if the plugin registers any
34
+ screens/index.ts export const screens = { 'my-orders': () => import('./Orders') }
35
+ vite.config.ts
36
+ ```
37
+
38
+ ```ts
39
+ // vite.config.ts
40
+ import { fluxScreens } from '@fluxwp/plugin-kit/vite';
41
+
42
+ export default fluxScreens({ entry: 'my-plugin/screens/index.ts', outDir: 'my-plugin/assets/flux' });
43
+ ```
44
+
45
+ ```graphql
46
+ # my-plugin/graphql/operations/FlxMyOrders.graphql
47
+ query FlxMyOrders {
48
+ viewer { name }
49
+ }
50
+ ```
51
+
52
+ ```sh
53
+ npx flx-kit codegen my-plugin # → screens/generated/{types,operations}.ts + graphql/persisted-queries.json
54
+ npx vite build # → assets/flux/flux-screens.js (+ chunks, css, chunks.json)
55
+ ```
56
+
57
+ ## A screen
58
+
59
+ ```tsx
60
+ // my-plugin/screens/Orders.tsx
61
+ import { useMemo } from 'react';
62
+ import { useTranslation } from 'react-i18next';
63
+ import { createGraphQLClient } from '@fluxwp/graphql';
64
+ import { FlxGraphQLProvider, useFlxQuery } from '@fluxwp/graphql/react';
65
+ import { useHost } from '@fluxwp/host';
66
+ import { Loading } from '@fluxwp/ui';
67
+ import { FlxMyOrders } from './generated/operations';
68
+
69
+ export default function Orders() {
70
+ const host = useHost();
71
+ const client = useMemo(() => createGraphQLClient({ api: host.client }), [host.client]);
72
+ return (
73
+ <FlxGraphQLProvider client={client} scope={host.scope}>
74
+ <Hello />
75
+ </FlxGraphQLProvider>
76
+ );
77
+ }
78
+
79
+ function Hello() {
80
+ const { t } = useTranslation('my');
81
+ const q = useFlxQuery(FlxMyOrders, {}); // q.data is typed from the schema
82
+ if (!q.data) return <Loading />;
83
+ return <h1>{t('hello', { name: q.data.viewer?.name })}</h1>;
84
+ }
85
+ ```
86
+
87
+ `screens/index.ts` may also export `resources` (`{ en: { my: { hello: 'Hello {{name}}' } }, tr: { … } }`)
88
+ for i18next.
89
+
90
+ ## PHP side
91
+
92
+ ```php
93
+ add_filter( 'flx_gql_persisted_manifests', function ( $m ) {
94
+ $m['my-plugin'] = __DIR__ . '/graphql/persisted-queries.json';
95
+ return $m;
96
+ } );
97
+
98
+ add_action( 'admin_menu', function () {
99
+ add_menu_page( 'Orders', 'Orders', 'read', 'my-orders', function () {
100
+ if ( function_exists( 'flx_admin_screen_render' ) && flx_admin_screen_render() ) {
101
+ return;
102
+ }
103
+ echo 'This screen needs the Flux GraphQL plugin.';
104
+ } );
105
+ if ( function_exists( 'flx_admin_screen' ) ) {
106
+ flx_admin_screen( 'my-orders', array(
107
+ 'module' => 'my-orders',
108
+ 'assets_dir' => __DIR__ . '/assets/flux/',
109
+ 'assets_url' => plugin_dir_url( __FILE__ ) . 'assets/flux/',
110
+ 'preload' => array( array( 'FlxMyOrders' ) ), // first data ships with the page
111
+ ) );
112
+ }
113
+ }, 20 );
114
+ ```
115
+
116
+ ### Your own GraphQL types
117
+
118
+ Register them in PHP with the Flux GraphQL kit (`flx_gql_type`, `flx_gql_query`, `flx_gql_mutation` on
119
+ `flx_gql_register`; every field declares a capability). To type-check your screens against them, export the
120
+ schema of a site with your plugin active and keep your part in the plugin:
121
+
122
+ ```sh
123
+ wp flx-gql schema --output=schema.graphql --owners=owners.json
124
+ npx flx-kit schema-split schema.graphql owners.json my-plugin # → my-plugin/graphql/schema.graphql
125
+ ```
126
+
127
+ ## CLI
128
+
129
+ | Command | Does |
130
+ |---|---|
131
+ | `flx-kit codegen <plugin-dir> [--check]` | Types, operation constants and `persisted-queries.json` for the plugin's operations (`--check`: fail if out of date, for CI) |
132
+ | `flx-kit schema-split <schema> <owners> <plugin-dir>` | Writes the plugin's own part of a site schema |
133
+
134
+ ## Rules
135
+
136
+ - Import only what the runtime provides: `react`, `react/jsx-runtime`, `react-dom`, `react-dom/client`,
137
+ `@tanstack/react-query`, `i18next`, `react-i18next`, `@fluxwp/core`, `@fluxwp/tokens`, `@fluxwp/ui`,
138
+ `@fluxwp/graphql`, `@fluxwp/graphql/react`, `@fluxwp/host`. Anything else is bundled with your screens;
139
+ other `@fluxwp/*` imports fail the build.
140
+ - Operation names start with `Flx` (`FlxMyOrders`), one operation per file. Prefix screen ids with your
141
+ plugin (`acme-orders`).
142
+ - Your CSS is scoped under `.flux-root`; the `@fluxwp/ui` styles are already on the page.
143
+
144
+ Complete example plugin:
145
+ [`example/acme-hello`](https://github.com/FluxWP/FluxWP/tree/main/packages/plugin-kit/example/acme-hello).
146
+
147
+ ## The FluxWP packages
148
+
149
+ | Package | What it is |
150
+ |---|---|
151
+ | [`@fluxwp/plugin-kit`](https://www.npmjs.com/package/@fluxwp/plugin-kit) | Build wp-admin React screens for your own WordPress plugin (Vite preset + `flx-kit` codegen) |
152
+ | [`@fluxwp/graphql`](https://www.npmjs.com/package/@fluxwp/graphql) | Typed GraphQL client and React hooks for Flux GraphQL (WPGraphQL) |
153
+ | [`@fluxwp/host`](https://www.npmjs.com/package/@fluxwp/host) | Host context of a screen: site client, user, locale |
154
+ | [`@fluxwp/ui`](https://www.npmjs.com/package/@fluxwp/ui) | React UI kit of FluxWP screens: Check, DatePicker, Modal, Icon … |
155
+ | [`@fluxwp/core`](https://www.npmjs.com/package/@fluxwp/core) | WordPress REST client, sign-in (OAuth PKCE, app passwords), accounts, i18n |
156
+ | [`@fluxwp/tokens`](https://www.npmjs.com/package/@fluxwp/tokens) | Design tokens: colours, spacing, radius, type, light / dark |
157
+
158
+ [FluxWP](https://fluxwp.com) is an open-source, all-in-one WordPress suite (donations, forms, e-commerce,
159
+ CRM, e-mail, AI, SEO) with a desktop and mobile app. Source:
160
+ [github.com/FluxWP/FluxWP](https://github.com/FluxWP/FluxWP). Questions and ideas: info@fluxwp.com.
161
+
162
+ ## License
163
+
164
+ GPL-2.0-or-later
@@ -0,0 +1,264 @@
1
+ // packages/plugin-kit/src/codegen.ts
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join, relative, resolve } from "node:path";
4
+ import { buildSchema, parse as parse3 } from "graphql";
5
+ import { codegen as gqlCodegen } from "@graphql-codegen/core";
6
+ import * as typescriptOperations from "@graphql-codegen/typescript-operations";
7
+
8
+ // packages/graphql/scripts/lib.ts
9
+ import { createHash } from "node:crypto";
10
+ import {
11
+ Kind,
12
+ parse,
13
+ print,
14
+ validate,
15
+ visit
16
+ } from "graphql";
17
+
18
+ class GenerateError extends Error {
19
+ }
20
+ var NAME = /^Flx[A-Z][A-Za-z0-9]*$/;
21
+ function collectOperations(schema, files) {
22
+ const problems = [];
23
+ const byPlugin = new Map;
24
+ for (const f of files) {
25
+ let doc;
26
+ try {
27
+ doc = parse(f.body, { noLocation: false });
28
+ } catch (e) {
29
+ problems.push(`${f.path}: ${e.message}`);
30
+ continue;
31
+ }
32
+ const entry = byPlugin.get(f.plugin) ?? { ops: [], frags: new Map };
33
+ byPlugin.set(f.plugin, entry);
34
+ for (const def of doc.definitions) {
35
+ if (def.kind === Kind.OPERATION_DEFINITION) {
36
+ if (def.operation === "subscription")
37
+ problems.push(`${f.path}: subscriptions are not supported`);
38
+ else
39
+ entry.ops.push({ node: def, path: f.path });
40
+ } else if (def.kind === Kind.FRAGMENT_DEFINITION) {
41
+ if (entry.frags.has(def.name.value))
42
+ problems.push(`${f.path}: fragment ${def.name.value} is defined twice in ${f.plugin}`);
43
+ entry.frags.set(def.name.value, def);
44
+ } else {
45
+ problems.push(`${f.path}: only operations and fragments belong in operation files`);
46
+ }
47
+ }
48
+ }
49
+ const seen = new Map;
50
+ const out = [];
51
+ for (const [plugin, { ops, frags }] of byPlugin) {
52
+ for (const { node, path } of ops) {
53
+ const name = node.name?.value;
54
+ if (!name) {
55
+ problems.push(`${path}: every operation needs a name`);
56
+ continue;
57
+ }
58
+ if (!NAME.test(name))
59
+ problems.push(`${path}: operation ${name} must be PascalCase and start with "Flx"`);
60
+ const other = seen.get(name);
61
+ if (other)
62
+ problems.push(`${path}: operation ${name} is also defined in ${other}`);
63
+ seen.set(name, path);
64
+ const used = new Map;
65
+ const walk = (n) => visit(n, {
66
+ FragmentSpread(s) {
67
+ const name = s.name.value;
68
+ if (used.has(name))
69
+ return;
70
+ const frag = frags.get(name);
71
+ if (!frag) {
72
+ problems.push(`${path}: fragment ${name} is not defined in ${plugin}`);
73
+ return;
74
+ }
75
+ used.set(name, frag);
76
+ walk(frag);
77
+ }
78
+ });
79
+ walk(node);
80
+ const doc = {
81
+ kind: Kind.DOCUMENT,
82
+ definitions: [node, ...[...used.values()].sort((a, b) => a.name.value.localeCompare(b.name.value))]
83
+ };
84
+ for (const err of validate(schema, doc))
85
+ problems.push(`${path}: ${err.message}`);
86
+ const printed = print(stripLocations(doc));
87
+ out.push({ plugin, name, kind: node.operation, document: printed, id: sha256(printed), path });
88
+ }
89
+ }
90
+ if (problems.length)
91
+ throw new GenerateError(problems.join(`
92
+ `));
93
+ return out.sort((a, b) => a.name.localeCompare(b.name));
94
+ }
95
+ function stripLocations(doc) {
96
+ return JSON.parse(JSON.stringify(doc, (k, v) => k === "loc" ? undefined : v));
97
+ }
98
+ var sha256 = (s) => createHash("sha256").update(s).digest("hex");
99
+ function manifests(ops) {
100
+ const by = new Map;
101
+ for (const op of ops) {
102
+ const m = by.get(op.plugin) ?? {};
103
+ m[op.id] = op.document;
104
+ by.set(op.plugin, m);
105
+ }
106
+ const out = new Map;
107
+ for (const [plugin, m] of by) {
108
+ const sorted = Object.fromEntries(Object.entries(m).sort(([a], [b]) => a.localeCompare(b)));
109
+ out.set(plugin, JSON.stringify(sorted, null, 2) + `
110
+ `);
111
+ }
112
+ return out;
113
+ }
114
+ var HEADER = "// Generated by packages/graphql/scripts/generate.ts. Do not edit; run `bun run --filter @fluxwp/graphql generate`.\n";
115
+ function typeNames(op) {
116
+ const suffix = op.kind === "query" ? "Query" : "Mutation";
117
+ const base = op.name.endsWith(suffix) ? op.name : op.name + suffix;
118
+ return { result: base, variables: base + "Variables" };
119
+ }
120
+ function operationsModule(ops) {
121
+ const lines = [HEADER, "import type { FlxOperation } from '../operation';"];
122
+ if (ops.length)
123
+ lines.push("import type * as T from './types';");
124
+ lines.push("");
125
+ for (const op of ops) {
126
+ const t = typeNames(op);
127
+ lines.push(`/** ${op.kind} ${op.name} (${op.plugin}, ${op.path}) */`, `export const ${op.name}: FlxOperation<T.${t.result}, T.${t.variables}> = {`, ` id: '${op.id}',`, ` name: '${op.name}',`, ` kind: '${op.kind}',`, ` plugin: '${op.plugin}',`, ` document: ${JSON.stringify(op.document)},`, "};", "");
128
+ }
129
+ if (!ops.length)
130
+ lines.push("export {};", "");
131
+ return lines.join(`
132
+ `);
133
+ }
134
+
135
+ // packages/graphql/scripts/parts.ts
136
+ import {
137
+ buildASTSchema,
138
+ concatAST,
139
+ getNamedType,
140
+ isInputObjectType,
141
+ isInterfaceType,
142
+ isObjectType,
143
+ isUnionType,
144
+ Kind as Kind2,
145
+ lexicographicSortSchema,
146
+ parse as parse2,
147
+ print as print2,
148
+ printSchema
149
+ } from "graphql";
150
+ var CORE_PART = "packages/graphql/schema/core.graphql";
151
+ function partOrder(a, b) {
152
+ if (a === b)
153
+ return 0;
154
+ if (a === CORE_PART)
155
+ return -1;
156
+ if (b === CORE_PART)
157
+ return 1;
158
+ return a < b ? -1 : 1;
159
+ }
160
+ function assembleSchema(parts) {
161
+ if (!parts.length)
162
+ throw new Error("no schema parts found");
163
+ const docs = [...parts].sort((a, b) => partOrder(a.path, b.path)).map((p) => {
164
+ try {
165
+ return parse2(p.body, { noLocation: true });
166
+ } catch (e) {
167
+ throw new Error(`${p.path}: ${e.message}`);
168
+ }
169
+ });
170
+ return lexicographicSortSchema(buildASTSchema(concatAST(docs)));
171
+ }
172
+ function assembleSdl(parts) {
173
+ return printSchema(assembleSchema(parts)) + `
174
+ `;
175
+ }
176
+
177
+ // packages/plugin-kit/src/codegen.ts
178
+ var HEADER2 = `// Generated by @fluxwp/plugin-kit (flx-kit codegen). Do not edit.
179
+ `;
180
+ function graphqlFiles(dir) {
181
+ if (!existsSync(dir))
182
+ return [];
183
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
184
+ const p = join(dir, e.name);
185
+ if (e.isDirectory())
186
+ return graphqlFiles(p);
187
+ return e.isFile() && e.name.endsWith(".graphql") ? [p] : [];
188
+ });
189
+ }
190
+ function defaultSchemaPath(from) {
191
+ for (let dir = resolve(from);; dir = dirname(dir)) {
192
+ const p = join(dir, "node_modules/@fluxwp/graphql/schema/full.graphql");
193
+ if (existsSync(p))
194
+ return p;
195
+ if (dirname(dir) === dir)
196
+ break;
197
+ }
198
+ throw new Error("FluxWP schema not found: install @fluxwp/graphql or pass --schema <file>.");
199
+ }
200
+ async function codegen(o) {
201
+ const plugin = resolve(o.plugin);
202
+ const slug = basename(plugin);
203
+ const out = resolve(o.out ?? join(plugin, "screens/generated"));
204
+ const parts = [{ path: CORE_PART, body: readFileSync(o.schema ?? defaultSchemaPath(plugin), "utf8") }];
205
+ const own = join(plugin, "graphql/schema.graphql");
206
+ if (existsSync(own))
207
+ parts.push({ path: `plugins/${slug}/graphql/schema.graphql`, body: readFileSync(own, "utf8") });
208
+ const sdl = assembleSdl(parts);
209
+ const sources = graphqlFiles(join(plugin, "graphql/operations")).sort().map((path) => ({ plugin: slug, path: relative(plugin, path), body: readFileSync(path, "utf8") }));
210
+ const ops = collectOperations(buildSchema(sdl), sources);
211
+ const types = await gqlCodegen({
212
+ filename: "types.ts",
213
+ schema: parse3(sdl),
214
+ documents: ops.map((op) => ({ location: op.path, document: parse3(op.document) })),
215
+ plugins: [{ typescriptOperations: {} }],
216
+ pluginMap: { typescriptOperations },
217
+ config: {
218
+ onlyOperationTypes: true,
219
+ enumsAsTypes: true,
220
+ useTypeImports: true,
221
+ dedupeOperationSuffix: true,
222
+ avoidOptionals: { field: true, inputValue: false, object: true, defaultValue: false },
223
+ maybeValue: "T | null",
224
+ inputMaybeValue: "T | null | undefined",
225
+ strictScalars: true,
226
+ scalars: { ID: "string", FlxJSON: "unknown" },
227
+ defaultScalarType: "unknown",
228
+ skipTypename: false,
229
+ nonOptionalTypename: false
230
+ }
231
+ });
232
+ const opsTs = operationsModule(ops).replace(/^\/\/ Generated by .*\n/, HEADER2).replace("import type { FlxOperation } from '../operation';", "import type { FlxOperation } from '@fluxwp/graphql';");
233
+ const files = new Map([
234
+ [join(out, "types.ts"), HEADER2 + `/* eslint-disable */
235
+ ` + types],
236
+ [join(out, "operations.ts"), opsTs]
237
+ ]);
238
+ const manifest = manifests(ops).get(slug);
239
+ const manifestPath = join(plugin, "graphql/persisted-queries.json");
240
+ const result = { operations: ops.length, written: [], stale: [] };
241
+ if (manifest) {
242
+ const cur = existsSync(manifestPath) ? readFileSync(manifestPath, "utf8") : null;
243
+ if (cur !== manifest) {
244
+ if (o.check)
245
+ result.stale.push(manifestPath);
246
+ else
247
+ files.set(manifestPath, manifest);
248
+ }
249
+ } else if (existsSync(manifestPath)) {
250
+ result.stale.push(manifestPath);
251
+ }
252
+ for (const [path, body] of files) {
253
+ if (existsSync(path) && readFileSync(path, "utf8") === body)
254
+ continue;
255
+ mkdirSync(dirname(path), { recursive: true });
256
+ writeFileSync(path, body);
257
+ result.written.push(path);
258
+ }
259
+ return result;
260
+ }
261
+ export {
262
+ codegen,
263
+ defaultSchemaPath
264
+ };