@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/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "@fluxwp/plugin-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Build wp-admin React screens for your WordPress plugin: Vite preset, typed GraphQL codegen, persisted queries, shared runtime.",
5
+ "keywords": [
6
+ "fluxwp",
7
+ "wordpress",
8
+ "typescript",
9
+ "wordpress-plugin",
10
+ "wp-admin",
11
+ "react",
12
+ "vite",
13
+ "vite-plugin",
14
+ "graphql",
15
+ "wpgraphql",
16
+ "codegen",
17
+ "cli",
18
+ "admin-ui"
19
+ ],
20
+ "author": "FluxWP <info@fluxwp.com> (https://fluxwp.com)",
21
+ "type": "module",
22
+ "license": "GPL-2.0-or-later",
23
+ "homepage": "https://github.com/FluxWP/FluxWP/tree/main/packages/plugin-kit#readme",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/FluxWP/FluxWP.git",
27
+ "directory": "packages/plugin-kit"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/FluxWP/FluxWP/issues",
31
+ "email": "info@fluxwp.com"
32
+ },
33
+ "exports": {
34
+ "./vite": {
35
+ "types": "./types/vite.d.ts",
36
+ "default": "./dist/vite.js"
37
+ },
38
+ "./codegen": {
39
+ "types": "./types/codegen.d.ts",
40
+ "default": "./dist/codegen.js"
41
+ },
42
+ "./modules": {
43
+ "types": "./types/modules.d.ts",
44
+ "default": "./dist/modules.js"
45
+ },
46
+ "./runtime-exports.json": "./runtime-exports.json"
47
+ },
48
+ "bin": {
49
+ "flx-kit": "./dist/flx-kit.js"
50
+ },
51
+ "files": [
52
+ "src",
53
+ "types",
54
+ "dist",
55
+ "schema",
56
+ "runtime-exports.json",
57
+ "README.md"
58
+ ],
59
+ "sideEffects": false,
60
+ "dependencies": {
61
+ "@fluxwp/core": "^0.4.6",
62
+ "@fluxwp/graphql": "^0.4.0",
63
+ "@fluxwp/tokens": "^0.4.1",
64
+ "@fluxwp/ui": "^0.3.3",
65
+ "@graphql-codegen/core": "^7.0.0",
66
+ "@graphql-codegen/typescript-operations": "^7.0.1",
67
+ "@vitejs/plugin-react": "^6.1.2",
68
+ "graphql": "^17.1.0",
69
+ "postcss-prefix-selector": "^2.2.1",
70
+ "vite": "^8.3.5",
71
+ "@fluxwp/host": "^0.4.0"
72
+ },
73
+ "peerDependencies": {
74
+ "react": "19.3.0",
75
+ "@tanstack/react-query": "^5.106.1",
76
+ "react-i18next": "^17.1.10"
77
+ },
78
+ "publishConfig": {
79
+ "access": "public",
80
+ "provenance": true
81
+ }
82
+ }
@@ -0,0 +1,316 @@
1
+ {
2
+ "react": [
3
+ "Activity",
4
+ "Children",
5
+ "Component",
6
+ "Fragment",
7
+ "Profiler",
8
+ "PureComponent",
9
+ "StrictMode",
10
+ "Suspense",
11
+ "ViewTransition",
12
+ "act",
13
+ "addTransitionType",
14
+ "cache",
15
+ "cacheSignal",
16
+ "captureOwnerStack",
17
+ "cloneElement",
18
+ "createContext",
19
+ "createElement",
20
+ "createRef",
21
+ "forwardRef",
22
+ "isValidElement",
23
+ "lazy",
24
+ "memo",
25
+ "startTransition",
26
+ "use",
27
+ "useActionState",
28
+ "useCallback",
29
+ "useContext",
30
+ "useDebugValue",
31
+ "useDeferredValue",
32
+ "useEffect",
33
+ "useEffectEvent",
34
+ "useId",
35
+ "useImperativeHandle",
36
+ "useInsertionEffect",
37
+ "useLayoutEffect",
38
+ "useMemo",
39
+ "useOptimistic",
40
+ "useReducer",
41
+ "useRef",
42
+ "useState",
43
+ "useSyncExternalStore",
44
+ "useTransition",
45
+ "version"
46
+ ],
47
+ "react/jsx-runtime": [
48
+ "Fragment",
49
+ "jsx",
50
+ "jsxs"
51
+ ],
52
+ "react-dom": [
53
+ "browser",
54
+ "createPortal",
55
+ "flushSync",
56
+ "preconnect",
57
+ "prefetchDNS",
58
+ "preinit",
59
+ "preinitModule",
60
+ "preload",
61
+ "preloadModule",
62
+ "requestFormReset",
63
+ "unstable_batchedUpdates",
64
+ "useFormState",
65
+ "useFormStatus",
66
+ "version"
67
+ ],
68
+ "react-dom/client": [
69
+ "createRoot",
70
+ "hydrateRoot"
71
+ ],
72
+ "@tanstack/react-query": [
73
+ "CancelledError",
74
+ "FocusManager",
75
+ "HydrationBoundary",
76
+ "InfiniteQueryObserver",
77
+ "IsRestoringProvider",
78
+ "Mutation",
79
+ "MutationCache",
80
+ "MutationObserver",
81
+ "OnlineManager",
82
+ "QueriesObserver",
83
+ "Query",
84
+ "QueryCache",
85
+ "QueryClient",
86
+ "QueryClientContext",
87
+ "QueryClientProvider",
88
+ "QueryErrorResetBoundary",
89
+ "QueryObserver",
90
+ "TimeoutManager",
91
+ "dataTagErrorSymbol",
92
+ "dataTagSymbol",
93
+ "defaultScheduler",
94
+ "defaultShouldDehydrateMutation",
95
+ "defaultShouldDehydrateQuery",
96
+ "dehydrate",
97
+ "dehydrateQuery",
98
+ "environmentManager",
99
+ "experimental_streamedQuery",
100
+ "focusManager",
101
+ "hashKey",
102
+ "hydrate",
103
+ "infiniteQueryOptions",
104
+ "isCancelledError",
105
+ "isServer",
106
+ "keepPreviousData",
107
+ "matchMutation",
108
+ "matchQuery",
109
+ "mutationOptions",
110
+ "noop",
111
+ "notifyManager",
112
+ "onlineManager",
113
+ "partialMatchKey",
114
+ "queryOptions",
115
+ "replaceEqualDeep",
116
+ "shouldThrowError",
117
+ "skipToken",
118
+ "timeoutManager",
119
+ "unsetMarker",
120
+ "useInfiniteQuery",
121
+ "useIsFetching",
122
+ "useIsMutating",
123
+ "useIsRestoring",
124
+ "useMutation",
125
+ "useMutationState",
126
+ "usePrefetchInfiniteQuery",
127
+ "usePrefetchQuery",
128
+ "useQueries",
129
+ "useQuery",
130
+ "useQueryClient",
131
+ "useQueryErrorResetBoundary",
132
+ "useSuspenseInfiniteQuery",
133
+ "useSuspenseQueries",
134
+ "useSuspenseQuery"
135
+ ],
136
+ "i18next": [
137
+ "$PluralBrand",
138
+ "$SelectorKeyBrand",
139
+ "changeLanguage",
140
+ "createInstance",
141
+ "dir",
142
+ "exists",
143
+ "getFixedT",
144
+ "hasLoadedNamespace",
145
+ "init",
146
+ "isSafeLanguageCode",
147
+ "keyFromSelector",
148
+ "loadLanguages",
149
+ "loadNamespaces",
150
+ "loadResources",
151
+ "reloadResources",
152
+ "setDefaultNamespace",
153
+ "t",
154
+ "use"
155
+ ],
156
+ "react-i18next": [
157
+ "I18nContext",
158
+ "I18nextProvider",
159
+ "IcuTrans",
160
+ "IcuTransWithoutContext",
161
+ "Trans",
162
+ "TransWithoutContext",
163
+ "Translation",
164
+ "composeInitialProps",
165
+ "getDefaults",
166
+ "getI18n",
167
+ "getInitialProps",
168
+ "initReactI18next",
169
+ "nodesToString",
170
+ "setDefaults",
171
+ "setI18n",
172
+ "useSSR",
173
+ "useTranslation",
174
+ "withSSR",
175
+ "withTranslation"
176
+ ],
177
+ "@fluxwp/core": [
178
+ "ApiError",
179
+ "AppPasswordError",
180
+ "DEMO_SITE",
181
+ "DiscoveryError",
182
+ "OAuthError",
183
+ "VERSION",
184
+ "accountId",
185
+ "accountIdFromRouteKey",
186
+ "accountRouteKey",
187
+ "accountsStore",
188
+ "activeAccount",
189
+ "adminPath",
190
+ "appPasswordUrl",
191
+ "arrangeCards",
192
+ "authorizeUrl",
193
+ "bagisReview",
194
+ "basicToken",
195
+ "brand",
196
+ "buildUrl",
197
+ "cagri",
198
+ "canDeleteForEveryone",
199
+ "chatMatches",
200
+ "clearTokens",
201
+ "clientFor",
202
+ "createClient",
203
+ "createI18n",
204
+ "createPkce",
205
+ "decodeEntities",
206
+ "discoverSite",
207
+ "dropClient",
208
+ "enhanceClient",
209
+ "flxapp",
210
+ "flxc",
211
+ "flxg",
212
+ "fromTokenResponse",
213
+ "getDemoLocale",
214
+ "gorev",
215
+ "htmlToText",
216
+ "isDeletedMessage",
217
+ "issuerMatches",
218
+ "layoutStore",
219
+ "loadTokens",
220
+ "locales",
221
+ "loginApiKey",
222
+ "loginAppPassword",
223
+ "loginDemo",
224
+ "loginOAuth",
225
+ "loginOtp",
226
+ "loginWithOAuth",
227
+ "memoryStore",
228
+ "mergeLayout",
229
+ "mergeMessages",
230
+ "moveItem",
231
+ "newerVersion",
232
+ "normalizeLocale",
233
+ "normalizeSiteUrl",
234
+ "oauthClientId",
235
+ "otpStart",
236
+ "otpVerify",
237
+ "parseAccountId",
238
+ "pkceChallenge",
239
+ "platform",
240
+ "randomString",
241
+ "refreshTokens",
242
+ "requestAppPassword",
243
+ "resources",
244
+ "restBase",
245
+ "revokeToken",
246
+ "saveTokens",
247
+ "setBrand",
248
+ "setClientEnhancer",
249
+ "setDemoLocale",
250
+ "setPlatform",
251
+ "siteBase",
252
+ "siteBasePath",
253
+ "sortChats",
254
+ "stripAngles",
255
+ "stripTags",
256
+ "trimEnd",
257
+ "trimStart"
258
+ ],
259
+ "@fluxwp/tokens": [
260
+ "alpha",
261
+ "cleanColors",
262
+ "contrast",
263
+ "font",
264
+ "luminance",
265
+ "nativeTheme",
266
+ "onColor",
267
+ "palette",
268
+ "radius",
269
+ "space",
270
+ "themeColors",
271
+ "themeFromConfig",
272
+ "toCssVars"
273
+ ],
274
+ "@fluxwp/ui": [
275
+ "Avatar",
276
+ "Check",
277
+ "DateCalendar",
278
+ "DatePicker",
279
+ "Empty",
280
+ "Icon",
281
+ "Loading",
282
+ "MenuIcon",
283
+ "Modal",
284
+ "formatDate",
285
+ "openSanitizedLink",
286
+ "parseDate",
287
+ "sanitizeHtml",
288
+ "useOverlay"
289
+ ],
290
+ "@fluxwp/graphql": [
291
+ "FlxGraphQLError",
292
+ "GRAPHQL_PATH",
293
+ "createGraphQLClient",
294
+ "flxStoreGet",
295
+ "flxStoreKey",
296
+ "flxStoreMarkStale",
297
+ "flxStoreSet",
298
+ "isFlxGraphQLError",
299
+ "payloadErrors",
300
+ "stableVariables"
301
+ ],
302
+ "@fluxwp/graphql/react": [
303
+ "FlxGraphQLProvider",
304
+ "flxQueryKey",
305
+ "useFlxCan",
306
+ "useFlxMutation",
307
+ "useFlxQuery",
308
+ "useFlxViewer",
309
+ "useGraphQL"
310
+ ],
311
+ "@fluxwp/host": [
312
+ "ModuleHostProvider",
313
+ "useHost",
314
+ "useModuleApi"
315
+ ]
316
+ }
package/src/codegen.ts ADDED
@@ -0,0 +1,117 @@
1
+ // Operations of a plugin outside the monorepo → typed operations + its persisted query manifest, against
2
+ // FluxWP's schema (@fluxwp/graphql schema/full.graphql) plus the plugin's own schema part.
3
+ //
4
+ // <plugin>/graphql/schema.graphql the plugin's types and fields (`flx-kit schema-split`), optional
5
+ // <plugin>/graphql/operations/*.graphql its operations, one per file, names Flx…
6
+ // → <plugin>/graphql/persisted-queries.json register with the flx_gql_persisted_manifests filter (committed)
7
+ // → <out>/types.ts, <out>/operations.ts import { FlxAcmeOrders } from './generated/operations'
8
+ //
9
+ // Same rules and output as the monorepo's packages/graphql/scripts/generate.ts (lib.ts is shared).
10
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
11
+ import { basename, dirname, join, relative, resolve } from 'node:path';
12
+ import { buildSchema, parse } from 'graphql';
13
+ import { codegen as gqlCodegen } from '@graphql-codegen/core';
14
+ import * as typescriptOperations from '@graphql-codegen/typescript-operations';
15
+ import { collectOperations, manifests, operationsModule, type SourceFile } from '../../graphql/scripts/lib';
16
+ import { assembleSdl, CORE_PART } from '../../graphql/scripts/parts';
17
+
18
+ export interface CodegenOptions {
19
+ /** Plugin folder (its slug is the folder name). */
20
+ plugin: string;
21
+ /** Folder for types.ts and operations.ts (default <plugin>/screens/generated). */
22
+ out?: string;
23
+ /** FluxWP schema (default: @fluxwp/graphql's schema/full.graphql). */
24
+ schema?: string;
25
+ /** Write nothing; return the manifest paths that are out of date. */
26
+ check?: boolean;
27
+ }
28
+
29
+ export interface CodegenResult {
30
+ operations: number;
31
+ written: string[];
32
+ stale: string[];
33
+ }
34
+
35
+ const HEADER = '// Generated by @fluxwp/plugin-kit (flx-kit codegen). Do not edit.\n';
36
+
37
+ function graphqlFiles(dir: string): string[] {
38
+ if (!existsSync(dir)) return [];
39
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
40
+ const p = join(dir, e.name);
41
+ if (e.isDirectory()) return graphqlFiles(p);
42
+ return e.isFile() && e.name.endsWith('.graphql') ? [p] : [];
43
+ });
44
+ }
45
+
46
+ /** The FluxWP schema a plugin compiles against: an explicit file, else the one @fluxwp/graphql ships. */
47
+ export function defaultSchemaPath(from: string): string {
48
+ for (let dir = resolve(from); ; dir = dirname(dir)) {
49
+ const p = join(dir, 'node_modules/@fluxwp/graphql/schema/full.graphql');
50
+ if (existsSync(p)) return p;
51
+ if (dirname(dir) === dir) break;
52
+ }
53
+ throw new Error('FluxWP schema not found: install @fluxwp/graphql or pass --schema <file>.');
54
+ }
55
+
56
+ export async function codegen(o: CodegenOptions): Promise<CodegenResult> {
57
+ const plugin = resolve(o.plugin);
58
+ const slug = basename(plugin);
59
+ const out = resolve(o.out ?? join(plugin, 'screens/generated'));
60
+ const parts = [{ path: CORE_PART, body: readFileSync(o.schema ?? defaultSchemaPath(plugin), 'utf8') }];
61
+ const own = join(plugin, 'graphql/schema.graphql');
62
+ if (existsSync(own)) parts.push({ path: `plugins/${slug}/graphql/schema.graphql`, body: readFileSync(own, 'utf8') });
63
+ const sdl = assembleSdl(parts);
64
+ const sources: SourceFile[] = graphqlFiles(join(plugin, 'graphql/operations'))
65
+ .sort()
66
+ .map((path) => ({ plugin: slug, path: relative(plugin, path), body: readFileSync(path, 'utf8') }));
67
+ const ops = collectOperations(buildSchema(sdl), sources);
68
+
69
+ const types = await gqlCodegen({
70
+ filename: 'types.ts',
71
+ schema: parse(sdl),
72
+ documents: ops.map((op) => ({ location: op.path, document: parse(op.document) })),
73
+ plugins: [{ typescriptOperations: {} }],
74
+ pluginMap: { typescriptOperations },
75
+ config: {
76
+ onlyOperationTypes: true,
77
+ enumsAsTypes: true,
78
+ useTypeImports: true,
79
+ dedupeOperationSuffix: true,
80
+ avoidOptionals: { field: true, inputValue: false, object: true, defaultValue: false },
81
+ maybeValue: 'T | null',
82
+ inputMaybeValue: 'T | null | undefined',
83
+ strictScalars: true,
84
+ scalars: { ID: 'string', FlxJSON: 'unknown' },
85
+ defaultScalarType: 'unknown',
86
+ skipTypename: false,
87
+ nonOptionalTypename: false,
88
+ },
89
+ });
90
+ const opsTs = operationsModule(ops)
91
+ .replace(/^\/\/ Generated by .*\n/, HEADER)
92
+ .replace("import type { FlxOperation } from '../operation';", "import type { FlxOperation } from '@fluxwp/graphql';");
93
+
94
+ const files = new Map<string, string>([
95
+ [join(out, 'types.ts'), HEADER + '/* eslint-disable */\n' + types],
96
+ [join(out, 'operations.ts'), opsTs],
97
+ ]);
98
+ const manifest = manifests(ops).get(slug);
99
+ const manifestPath = join(plugin, 'graphql/persisted-queries.json');
100
+ const result: CodegenResult = { operations: ops.length, written: [], stale: [] };
101
+ if (manifest) {
102
+ const cur = existsSync(manifestPath) ? readFileSync(manifestPath, 'utf8') : null;
103
+ if (cur !== manifest) {
104
+ if (o.check) result.stale.push(manifestPath);
105
+ else files.set(manifestPath, manifest);
106
+ }
107
+ } else if (existsSync(manifestPath)) {
108
+ result.stale.push(manifestPath);
109
+ }
110
+ for (const [path, body] of files) {
111
+ if (existsSync(path) && readFileSync(path, 'utf8') === body) continue;
112
+ mkdirSync(dirname(path), { recursive: true });
113
+ writeFileSync(path, body);
114
+ result.written.push(path);
115
+ }
116
+ return result;
117
+ }
package/src/css.d.ts ADDED
@@ -0,0 +1 @@
1
+ declare module '*.css';
package/src/modules.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Module specifiers the shared runtime (Flux GraphQL) provides to plugin bundles. Same list and order as
3
+ * `modules` in apps/wp-embed/src/runtime.tsx (scripts/runtime-exports.ts checks it). A plugin imports these
4
+ * and only these from React, React Query, i18next and the open @fluxwp packages; `@fluxwp/host` is
5
+ * useHost / useModuleApi / ModuleHost.
6
+ */
7
+ export const RUNTIME_MODULES = [
8
+ 'react',
9
+ 'react/jsx-runtime',
10
+ 'react-dom',
11
+ 'react-dom/client',
12
+ '@tanstack/react-query',
13
+ 'i18next',
14
+ 'react-i18next',
15
+ '@fluxwp/core',
16
+ '@fluxwp/tokens',
17
+ '@fluxwp/ui',
18
+ '@fluxwp/graphql',
19
+ '@fluxwp/graphql/react',
20
+ '@fluxwp/host',
21
+ ] as const;
22
+
23
+ export type RuntimeModule = (typeof RUNTIME_MODULES)[number];
package/src/vite.ts ADDED
@@ -0,0 +1,150 @@
1
+ // Vite preset for a plugin's wp-admin screens (docs: packages/plugin-kit/README.md).
2
+ //
3
+ // // vite.config.ts in the plugin (or its repository root)
4
+ // import { fluxScreens } from '@fluxwp/plugin-kit/vite';
5
+ // export default fluxScreens({ entry: 'screens/index.ts', outDir: 'plugins/acme-orders/assets/flux' });
6
+ //
7
+ // The entry exports `screens` (flx_admin_screen module id → lazy loader) and may export `resources`
8
+ // (lang → namespace → keys). The build:
9
+ // - leaves React, React Query, i18next and the open @fluxwp packages out: imports of those read
10
+ // globalThis.FluxRuntime.modules (Flux GraphQL's shared runtime, loaded once per page);
11
+ // - writes flux-screens.js (registers the screens), flux-screens-<name>-<hash>.js chunks, flux-screens.css
12
+ // (scoped to .flux-root like the runtime) and chunks.json {"mode":"screens"} that Flux GraphQL reads.
13
+ import { readFileSync, readdirSync, writeFileSync, existsSync, rmSync } from 'node:fs';
14
+ import { dirname, join, resolve } from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { defineConfig, type Plugin, type UserConfig } from 'vite';
17
+ import react from '@vitejs/plugin-react';
18
+ import prefixer from 'postcss-prefix-selector';
19
+ import { RUNTIME_MODULES } from './modules';
20
+
21
+ const kit = resolve(dirname(fileURLToPath(import.meta.url)), '..');
22
+ const EXPORTS = JSON.parse(readFileSync(join(kit, 'runtime-exports.json'), 'utf8')) as Record<string, string[]>;
23
+ const SHIM = '\0flux-runtime:';
24
+ const ENTRY = '\0flux-screens-entry';
25
+ /** Runtime API the bundle needs (apps/wp-embed/src/runtime.tsx RUNTIME_API). */
26
+ export const RUNTIME_API = 1;
27
+
28
+ export interface FluxScreensOptions {
29
+ /** Module exporting `screens` (and optionally `resources`). Relative to the Vite root. */
30
+ entry: string;
31
+ /** Where the bundle goes: the plugin's assets/flux/ folder. Emptied of old flux-screens* files. */
32
+ outDir: string;
33
+ /** Extra Vite config merged over the preset. */
34
+ vite?: UserConfig;
35
+ }
36
+
37
+ /** Specifier → runtime module key ('@fluxwp/modules' is the host part, the only part a plugin may use). */
38
+ function runtimeKey(id: string): string | null {
39
+ if (id === '@fluxwp/modules' || id === '@fluxwp/modules/src/host') return '@fluxwp/host';
40
+ return (RUNTIME_MODULES as readonly string[]).includes(id) ? id : null;
41
+ }
42
+
43
+ function shim(key: string): string {
44
+ const names = EXPORTS[key] ?? [];
45
+ const lines = [
46
+ `const rt = globalThis.FluxRuntime;`,
47
+ `if (!rt || rt.api < ${RUNTIME_API}) throw new Error('Flux GraphQL runtime (api ${RUNTIME_API}) is not loaded: update Flux GraphQL.');`,
48
+ `const m = rt.modules[${JSON.stringify(key)}];`,
49
+ `export default (m && 'default' in m) ? m.default : m;`,
50
+ ...names.map((n) => `export const ${n} = m.${n};`),
51
+ ];
52
+ return lines.join('\n');
53
+ }
54
+
55
+ /** Resolves runtime modules to shims, refuses other @fluxwp packages (they are not in the runtime). */
56
+ function runtimeModules(): Plugin {
57
+ return {
58
+ name: 'flux-runtime-modules',
59
+ enforce: 'pre',
60
+ resolveId(id) {
61
+ const key = runtimeKey(id);
62
+ if (key) return SHIM + key;
63
+ // The runtime already carries @fluxwp/ui's stylesheet.
64
+ if (id.startsWith('@fluxwp/') && id.endsWith('.css')) return SHIM + 'css';
65
+ if (id.startsWith('@fluxwp/') && !id.startsWith('@fluxwp/plugin-kit')) {
66
+ this.error(`${id} is not part of the Flux runtime. Plugins may import: ${RUNTIME_MODULES.join(', ')}.`);
67
+ }
68
+ return null;
69
+ },
70
+ load(id) {
71
+ if (id === SHIM + 'css') return 'export {};';
72
+ if (id.startsWith(SHIM)) return shim(id.slice(SHIM.length));
73
+ return null;
74
+ },
75
+ };
76
+ }
77
+
78
+ /** The bundle entry: register the screens with the runtime. */
79
+ function entryModule(entry: string): Plugin {
80
+ return {
81
+ name: 'flux-screens-entry',
82
+ resolveId: (id) => (id === ENTRY ? ENTRY : null),
83
+ load(id) {
84
+ if (id !== ENTRY) return null;
85
+ const target = JSON.stringify(resolve(entry));
86
+ return [
87
+ `import * as mod from ${target};`,
88
+ `const rt = globalThis.FluxRuntime;`,
89
+ `if (!rt || rt.api < ${RUNTIME_API}) throw new Error('Flux GraphQL runtime (api ${RUNTIME_API}) is not loaded: update Flux GraphQL.');`,
90
+ `rt.register(mod.screens, { resources: mod.resources });`,
91
+ `export const screens = mod.screens;`,
92
+ ].join('\n');
93
+ },
94
+ };
95
+ }
96
+
97
+ /** chunks.json beside the bundle: {"mode":"screens","entry":"flux-screens.js","files":[…]}. */
98
+ function manifest(outDir: string): Plugin {
99
+ return {
100
+ name: 'flux-screens-manifest',
101
+ apply: 'build',
102
+ closeBundle() {
103
+ const files = readdirSync(outDir).filter((f) => /^flux-screens.*\.(js|css)$/.test(f)).sort();
104
+ const json = { mode: 'screens', api: RUNTIME_API, entry: 'flux-screens.js', files };
105
+ writeFileSync(join(outDir, 'chunks.json'), JSON.stringify(json, null, 2) + '\n');
106
+ },
107
+ };
108
+ }
109
+
110
+ /** Same scoping as apps/wp-embed: every rule under .flux-root, so wp-admin styles do not mix. */
111
+ function scopeCss(prefix: string, selector: string, prefixed: string): string {
112
+ const state = /^((?:html|body)(?:\.[\w-]+)+)(?=$|[\s>+~,*])(.*)$/.exec(selector);
113
+ if (state) return state[2]!.trim() ? `${state[1]} ${prefix} ${state[2]!.trim()}` : `${state[1]} ${prefix}`;
114
+ if (/^(html|body|:root|#root)\b/.test(selector)) return selector.replace(/^(html|body|:root|#root)(\.[\w-]+)*/, prefix);
115
+ if (selector.startsWith('.flux-root')) return selector;
116
+ if (selector === '*' || selector.startsWith('*')) return `${prefix} ${selector}, ${prefix}`;
117
+ return prefixed;
118
+ }
119
+
120
+ export function fluxScreens(o: FluxScreensOptions): UserConfig {
121
+ const outDir = resolve(o.outDir);
122
+ if (existsSync(outDir)) {
123
+ for (const f of readdirSync(outDir)) if (/^flux-screens.*\.(js|css)$/.test(f) || f === 'chunks.json') rmSync(join(outDir, f));
124
+ }
125
+ const base = defineConfig({
126
+ plugins: [runtimeModules(), entryModule(o.entry), react(), manifest(outDir)],
127
+ define: { 'process.env.NODE_ENV': '"production"' },
128
+ css: { postcss: { plugins: [prefixer({ prefix: '.flux-root', transform: scopeCss })] } },
129
+ base: './',
130
+ build: {
131
+ outDir,
132
+ emptyOutDir: false,
133
+ cssCodeSplit: false,
134
+ modulePreload: false,
135
+ assetsInlineLimit: 100_000,
136
+ target: 'es2020',
137
+ rollupOptions: {
138
+ input: ENTRY,
139
+ preserveEntrySignatures: 'strict',
140
+ output: {
141
+ format: 'es',
142
+ entryFileNames: 'flux-screens.js',
143
+ chunkFileNames: 'flux-screens-[name]-[hash].js',
144
+ assetFileNames: 'flux-screens[extname]',
145
+ },
146
+ },
147
+ },
148
+ });
149
+ return o.vite ? { ...base, ...o.vite, build: { ...base.build, ...o.vite.build } } : base;
150
+ }