velora-plugin 0.9.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.
Files changed (41) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +22 -0
  3. package/dist/build-federation-bundle.d.ts +29 -0
  4. package/dist/build-federation-bundle.js +93 -0
  5. package/dist/build.d.ts +41 -0
  6. package/dist/build.js +123 -0
  7. package/dist/bundle-server-manifest.d.ts +27 -0
  8. package/dist/bundle-server-manifest.js +93 -0
  9. package/dist/checks/audit.d.ts +2 -0
  10. package/dist/checks/audit.js +50 -0
  11. package/dist/checks/bundle-size.d.ts +3 -0
  12. package/dist/checks/bundle-size.js +21 -0
  13. package/dist/checks/db-compat.d.ts +3 -0
  14. package/dist/checks/db-compat.js +15 -0
  15. package/dist/checks/manifest.d.ts +3 -0
  16. package/dist/checks/manifest.js +12 -0
  17. package/dist/checks/shared-deps.d.ts +3 -0
  18. package/dist/checks/shared-deps.js +31 -0
  19. package/dist/checks/typescript.d.ts +2 -0
  20. package/dist/checks/typescript.js +34 -0
  21. package/dist/checks/views.d.ts +3 -0
  22. package/dist/checks/views.js +63 -0
  23. package/dist/copy-sample-content.d.ts +39 -0
  24. package/dist/copy-sample-content.js +57 -0
  25. package/dist/index.d.ts +12 -0
  26. package/dist/index.js +159 -0
  27. package/dist/load-manifest.d.ts +18 -0
  28. package/dist/load-manifest.js +49 -0
  29. package/dist/pack-starter.d.ts +48 -0
  30. package/dist/pack-starter.js +118 -0
  31. package/dist/pack.d.ts +12 -0
  32. package/dist/pack.js +26 -0
  33. package/dist/publish.d.ts +24 -0
  34. package/dist/publish.js +48 -0
  35. package/dist/types.d.ts +11 -0
  36. package/dist/types.js +1 -0
  37. package/dist/validate.d.ts +5 -0
  38. package/dist/validate.js +49 -0
  39. package/dist/write-manifest-json.d.ts +7 -0
  40. package/dist/write-manifest-json.js +72 -0
  41. package/package.json +54 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # velora-plugin
2
+
3
+ The CLI for building, validating, packing, and publishing Velora plugins.
4
+ Validates a plugin's manifest, required views, TypeScript compilation,
5
+ bundle size, and Module Federation shared-dependency setup before it can
6
+ be packed into a tarball or submitted to the marketplace.
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ npm install --save-dev velora-plugin
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```sh
17
+ npx velora-plugin validate
18
+ npx velora-plugin build
19
+ npx velora-plugin pack
20
+ ```
21
+
22
+ Part of [Velora](https://github.com/velora-cms/velora). Apache-2.0.
@@ -0,0 +1,29 @@
1
+ export interface FederationBuildResult {
2
+ outDir: string;
3
+ remoteEntryPath: string | null;
4
+ buildError?: string;
5
+ }
6
+ /**
7
+ * Builds a plugin's Module Federation bundle into an isolated temp
8
+ * directory, for measurement only (bundle size, shared-deps checks) —
9
+ * never the plugin's own dist/. Caller must call cleanupFederationBuild.
10
+ *
11
+ * NOT safe to call concurrently within one process — see
12
+ * runFederationBuild's process-global mutation. Callers must await one
13
+ * call to completion before starting another.
14
+ */
15
+ export declare function buildFederationBundle(pluginDir: string): Promise<FederationBuildResult>;
16
+ export declare function cleanupFederationBuild(result: FederationBuildResult): void;
17
+ /**
18
+ * Runs the same real Vite Module Federation build as
19
+ * buildFederationBundle, but into a PERMANENT, caller-supplied `outDir`
20
+ * — no temp directory, no cleanup. Used by `velora-plugin build`
21
+ * (Session 81) to produce the real, distributable remoteEntry.js.
22
+ *
23
+ * NOT safe to call concurrently within one process, for the same reason
24
+ * as buildFederationBundle.
25
+ */
26
+ export declare function buildFederationBundleTo(pluginDir: string, outDir: string): Promise<{
27
+ remoteEntryPath: string | null;
28
+ buildError?: string;
29
+ }>;
@@ -0,0 +1,93 @@
1
+ import { mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { build } from "vite";
5
+ /**
6
+ * Shared core: runs a real Vite Module Federation build for
7
+ * `absolutePluginDir` into `outDir` (already resolved, already
8
+ * existing), applying both real @module-federation/vite workarounds
9
+ * this session discovered (cwd-relative `exposes` resolution,
10
+ * `isTestEnv()` bailout under Vitest). NOT safe to call concurrently —
11
+ * see the two public wrappers' own docs.
12
+ */
13
+ async function runFederationBuild(absolutePluginDir, outDir) {
14
+ const previousCwd = process.cwd();
15
+ const previousNoTestEnvCheck = process.env.MFE_VITE_NO_TEST_ENV_CHECK;
16
+ try {
17
+ // @module-federation/vite resolves each `exposes` entry (e.g. "./src/plugin.tsx")
18
+ // relative to process.cwd() when generating its virtual remoteEntry module —
19
+ // not relative to Vite's `root`/`configFile` options. Without matching cwd to
20
+ // pluginDir, the build fails with "Could not resolve './src/plugin.tsx'" for
21
+ // every scaffolded/first-party plugin (both use relative exposes paths).
22
+ process.chdir(absolutePluginDir);
23
+ // @module-federation/vite's federation() plugin factory has a built-in
24
+ // isTestEnv() bailout — `if (NODE_ENV === "test" || VITEST != null ||
25
+ // JEST_WORKER_ID != null) return [];` — that silently drops itself from the
26
+ // plugin list with no error, so the build quietly falls back to a plain
27
+ // index.html build with no remoteEntry.js. Both this package's own test
28
+ // suite (Vitest) and a real `velora-plugin build` CLI invocation run this
29
+ // function, so the escape hatch is applied unconditionally — it's a no-op
30
+ // outside a test runner, since VITEST/NODE_ENV=test are never set there.
31
+ process.env.MFE_VITE_NO_TEST_ENV_CHECK = "true";
32
+ await build({
33
+ root: absolutePluginDir,
34
+ configFile: join(absolutePluginDir, "vite.config.ts"),
35
+ logLevel: "silent",
36
+ build: { outDir, emptyOutDir: true },
37
+ });
38
+ }
39
+ catch (error) {
40
+ return { remoteEntryPath: null, buildError: error instanceof Error ? error.message : String(error) };
41
+ }
42
+ finally {
43
+ process.chdir(previousCwd);
44
+ if (previousNoTestEnvCheck === undefined) {
45
+ delete process.env.MFE_VITE_NO_TEST_ENV_CHECK;
46
+ }
47
+ else {
48
+ process.env.MFE_VITE_NO_TEST_ENV_CHECK = previousNoTestEnvCheck;
49
+ }
50
+ }
51
+ const remoteEntryName = readdirSync(outDir).find((file) => /^remoteEntry.*\.js$/.test(file));
52
+ return { remoteEntryPath: remoteEntryName ? join(outDir, remoteEntryName) : null };
53
+ }
54
+ /**
55
+ * Builds a plugin's Module Federation bundle into an isolated temp
56
+ * directory, for measurement only (bundle size, shared-deps checks) —
57
+ * never the plugin's own dist/. Caller must call cleanupFederationBuild.
58
+ *
59
+ * NOT safe to call concurrently within one process — see
60
+ * runFederationBuild's process-global mutation. Callers must await one
61
+ * call to completion before starting another.
62
+ */
63
+ export async function buildFederationBundle(pluginDir) {
64
+ const absolutePluginDir = resolve(pluginDir);
65
+ const outDir = mkdtempSync(join(tmpdir(), "velora-plugin-validate-"));
66
+ const result = await runFederationBuild(absolutePluginDir, outDir);
67
+ return { outDir, ...result };
68
+ }
69
+ export function cleanupFederationBuild(result) {
70
+ rmSync(result.outDir, { recursive: true, force: true });
71
+ }
72
+ /**
73
+ * Runs the same real Vite Module Federation build as
74
+ * buildFederationBundle, but into a PERMANENT, caller-supplied `outDir`
75
+ * — no temp directory, no cleanup. Used by `velora-plugin build`
76
+ * (Session 81) to produce the real, distributable remoteEntry.js.
77
+ *
78
+ * NOT safe to call concurrently within one process, for the same reason
79
+ * as buildFederationBundle.
80
+ */
81
+ export async function buildFederationBundleTo(pluginDir, outDir) {
82
+ const absolutePluginDir = resolve(pluginDir);
83
+ // Vite resolves a relative build.outDir against `root` (absolutePluginDir
84
+ // above), not against the process's original cwd — if a caller passes a
85
+ // relative outDir (e.g. "plugins/google-maps/velora-package" from a CLI
86
+ // invoked with a relative pluginDir), the build silently doubles the path
87
+ // (".../plugins/google-maps/plugins/google-maps/velora-package"). Resolve
88
+ // once, up front, so this function is correct regardless of what shape of
89
+ // path a caller passes in.
90
+ const absoluteOutDir = resolve(outDir);
91
+ mkdirSync(absoluteOutDir, { recursive: true });
92
+ return runFederationBuild(absolutePluginDir, absoluteOutDir);
93
+ }
@@ -0,0 +1,41 @@
1
+ import type { FederationBuildResult } from "./build-federation-bundle.js";
2
+ import type { ValidationResult } from "./types.js";
3
+ export declare class BuildValidationError extends Error {
4
+ readonly validation: ValidationResult;
5
+ constructor(message: string, validation: ValidationResult);
6
+ }
7
+ export declare class BuildFederationError extends Error {
8
+ constructor(message: string);
9
+ }
10
+ /**
11
+ * Throws BuildFederationError if the federation build did not produce a
12
+ * remoteEntryPath (equivalently, buildError is set). No-op otherwise.
13
+ * Extracted as a standalone, pure function so the check-and-throw logic can
14
+ * be unit-tested directly without needing to force a real Vite failure at
15
+ * exactly the right pipeline stage.
16
+ */
17
+ export declare function assertFederationBuildSucceeded(result: Pick<FederationBuildResult, "remoteEntryPath" | "buildError">, pluginDir: string): void;
18
+ export interface BuildResult {
19
+ pluginDir: string;
20
+ outDir: string;
21
+ validation: ValidationResult;
22
+ }
23
+ /**
24
+ * Runs validate() first (Session 80) — a plugin that doesn't pass never
25
+ * gets packaged. On success, produces the full distributable package:
26
+ * remoteEntry.js + assets (a real Vite Module Federation build into the
27
+ * permanent outDir), server/plugin.js (a self-contained Vite SSR bundle —
28
+ * live functions intact, zero bare import specifiers, importable from any
29
+ * directory on any machine (Session 121)), and manifest.json (a redacted,
30
+ * JSON-safe summary for marketplace listing).
31
+ *
32
+ * Ordering note: the federation build MUST run before the server-manifest
33
+ * bundle, not after. buildFederationBundleTo runs Vite with
34
+ * `emptyOutDir: true` against the shared outDir — if bundleServerManifest
35
+ * had already written outDir/server/plugin.js, Vite's empty-out-dir step
36
+ * would delete it along with everything else in outDir before laying down
37
+ * remoteEntry.js. Bundling the server manifest and writing manifest.json
38
+ * only ever *add* files to outDir after the Vite build has already run, so
39
+ * neither is at risk of being clobbered by it.
40
+ */
41
+ export declare function buildPlugin(pluginDir: string, outDir?: string): Promise<BuildResult>;
package/dist/build.js ADDED
@@ -0,0 +1,123 @@
1
+ import { mkdirSync, rmSync } from "node:fs";
2
+ import { join, resolve, sep } from "node:path";
3
+ import { buildFederationBundleTo } from "./build-federation-bundle.js";
4
+ import { bundleServerManifest } from "./bundle-server-manifest.js";
5
+ import { copySampleContentIfPresent } from "./copy-sample-content.js";
6
+ import { loadManifest } from "./load-manifest.js";
7
+ import { packStarterIfPresent } from "./pack-starter.js";
8
+ import { validatePlugin } from "./validate.js";
9
+ import { writeManifestJson } from "./write-manifest-json.js";
10
+ import { hasClientBundle } from "@velora-cms/plugin-sdk/manifest";
11
+ export class BuildValidationError extends Error {
12
+ validation;
13
+ constructor(message, validation) {
14
+ super(message);
15
+ this.validation = validation;
16
+ this.name = "BuildValidationError";
17
+ }
18
+ }
19
+ export class BuildFederationError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = "BuildFederationError";
23
+ }
24
+ }
25
+ /**
26
+ * Throws BuildFederationError if the federation build did not produce a
27
+ * remoteEntryPath (equivalently, buildError is set). No-op otherwise.
28
+ * Extracted as a standalone, pure function so the check-and-throw logic can
29
+ * be unit-tested directly without needing to force a real Vite failure at
30
+ * exactly the right pipeline stage.
31
+ */
32
+ export function assertFederationBuildSucceeded(result, pluginDir) {
33
+ if (!result.remoteEntryPath) {
34
+ throw new BuildFederationError(`Vite Module Federation build failed for ${pluginDir}: ${result.buildError}`);
35
+ }
36
+ }
37
+ /**
38
+ * Runs validate() first (Session 80) — a plugin that doesn't pass never
39
+ * gets packaged. On success, produces the full distributable package:
40
+ * remoteEntry.js + assets (a real Vite Module Federation build into the
41
+ * permanent outDir), server/plugin.js (a self-contained Vite SSR bundle —
42
+ * live functions intact, zero bare import specifiers, importable from any
43
+ * directory on any machine (Session 121)), and manifest.json (a redacted,
44
+ * JSON-safe summary for marketplace listing).
45
+ *
46
+ * Ordering note: the federation build MUST run before the server-manifest
47
+ * bundle, not after. buildFederationBundleTo runs Vite with
48
+ * `emptyOutDir: true` against the shared outDir — if bundleServerManifest
49
+ * had already written outDir/server/plugin.js, Vite's empty-out-dir step
50
+ * would delete it along with everything else in outDir before laying down
51
+ * remoteEntry.js. Bundling the server manifest and writing manifest.json
52
+ * only ever *add* files to outDir after the Vite build has already run, so
53
+ * neither is at risk of being clobbered by it.
54
+ */
55
+ export async function buildPlugin(pluginDir, outDir) {
56
+ const validation = await validatePlugin(pluginDir);
57
+ if (!validation.passed) {
58
+ throw new BuildValidationError(`validate failed for ${pluginDir} — see validation.checks for details`, validation);
59
+ }
60
+ // Resolved to absolute here (not left to buildFederationBundleTo alone)
61
+ // so BuildResult.outDir is always absolute and consistent for callers
62
+ // (CLI output, bundleServerManifest's outDir arg) regardless of whether
63
+ // pluginDir/outDir were passed in as relative paths.
64
+ const resolvedOutDir = resolve(outDir ?? join(pluginDir, "velora-package"));
65
+ const manifestResult = await loadManifest(pluginDir);
66
+ if (!manifestResult.ok) {
67
+ // Should be unreachable — validate() already asserts manifest validity
68
+ // above — but never silently package an invalid manifest if it somehow
69
+ // diverges (e.g. a source edit between the two loads). The `validation`
70
+ // object above reflects the earlier, passing validate() run, so it's
71
+ // spread with `passed: false` overridden here — a synthetic failed
72
+ // result, since the divergence discovered here never actually ran
73
+ // through validatePlugin()'s checks.
74
+ throw new BuildValidationError(`manifest became invalid between validate and build for ${pluginDir}`, {
75
+ ...validation,
76
+ passed: false,
77
+ });
78
+ }
79
+ if (hasClientBundle(manifestResult.manifest.type)) {
80
+ const federationBuild = await buildFederationBundleTo(pluginDir, resolvedOutDir);
81
+ assertFederationBuildSucceeded(federationBuild, pluginDir);
82
+ }
83
+ else {
84
+ // Client-bearing builds get this guard for free from Vite itself —
85
+ // it refuses an outDir that IS or CONTAINS the project root. The
86
+ // view-less branch below does its own recursive delete instead of
87
+ // calling Vite, so it needs the equivalent guard here: without it,
88
+ // `velora-plugin build --out .` run from inside a theme plugin's own
89
+ // directory resolves resolvedOutDir === pluginDir, and the rmSync
90
+ // below would recursively delete the plugin's own source tree before
91
+ // bundleServerManifest ever runs.
92
+ const resolvedPluginDir = resolve(pluginDir);
93
+ if (resolvedOutDir === resolvedPluginDir || resolvedPluginDir.startsWith(resolvedOutDir + sep)) {
94
+ throw new Error(`Refusing to build ${pluginDir}: outDir "${resolvedOutDir}" is the plugin's own source directory ` +
95
+ `(or an ancestor of it) — building here would delete the plugin's sources. Choose an outDir outside "${resolvedPluginDir}".`);
96
+ }
97
+ // The federation build is also what empties outDir (Vite's
98
+ // emptyOutDir) — without it a previous build's files would survive
99
+ // into this package. Replace-not-merge, same rule as storePackage.
100
+ rmSync(resolvedOutDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 });
101
+ mkdirSync(resolvedOutDir, { recursive: true });
102
+ }
103
+ await bundleServerManifest(pluginDir, join(resolvedOutDir, "server"));
104
+ writeManifestJson(manifestResult.manifest, resolvedOutDir);
105
+ // S148: packs <pluginDir>/starter/ into <outDir>/starter.tar.gz when
106
+ // present. Runs last, same reasoning as bundleServerManifest/
107
+ // writeManifestJson above — it only ever *adds* a file to outDir, never
108
+ // at risk from (and never at risk of clobbering) the federation build's
109
+ // emptyOutDir step. packPlugin (pack.ts) tars the whole outDir as-is, so
110
+ // the archive rides inside the plugin artifact for free — no change
111
+ // needed there.
112
+ await packStarterIfPresent(pluginDir, resolvedOutDir, manifestResult.manifest);
113
+ // S149: copies <pluginDir>/sample-content.json into outDir when present
114
+ // — the seed tree a template ships (Post/Author/... sample nodes), read
115
+ // back host-side by apps/server/src/plugins/seed-template-content.ts
116
+ // AFTER install() returns (onInstall has no minted ids and no content
117
+ // API to create nodes with). Same legality product and same "only ever
118
+ // adds a file" ordering safety as packStarterIfPresent immediately
119
+ // above — a plain synchronous copy, never at risk from (or of
120
+ // clobbering) the federation build's emptyOutDir step.
121
+ copySampleContentIfPresent(pluginDir, resolvedOutDir, manifestResult.manifest);
122
+ return { pluginDir, outDir: resolvedOutDir, validation };
123
+ }
@@ -0,0 +1,27 @@
1
+ export declare class BundleServerManifestError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ /**
5
+ * Bundles a plugin's manifest entry (src/plugin.ts(x) plus everything it
6
+ * transitively imports — INCLUDING react, react/jsx-runtime and
7
+ * @velora-cms/plugin-sdk) into one self-contained, Node-importable ESM file
8
+ * at <outDir>/plugin.js. Replaces Session 81's tsc-emit
9
+ * compileServerManifest: the emitted file kept bare import specifiers,
10
+ * which plain `import()` can only resolve by walking ancestor
11
+ * node_modules — true inside this monorepo, false on a real server (the
12
+ * S81 gap, reproduced concretely in S83 with a poisoned ancestor
13
+ * node_modules). A bundle resolves nothing at import time, so the same
14
+ * package installs anywhere.
15
+ *
16
+ * Bundling react into a SERVER-side artifact is safe by design: the
17
+ * server validates the manifest (Zod needs the live function references),
18
+ * persists it, and invokes hooks/apiRoutes handlers — it never renders
19
+ * views. The browser keeps loading views via remoteEntry.js with the
20
+ * host's Module Federation shared singletons; this file never reaches it.
21
+ *
22
+ * Deliberately configFile: false — the plugin's own vite.config.ts is
23
+ * the BROWSER-side federation build and must not leak in here. No
24
+ * process.chdir() (the buildFederationBundle concurrency caveat does not
25
+ * spread to this function); all paths resolved absolute up front.
26
+ */
27
+ export declare function bundleServerManifest(pluginDir: string, outDir: string): Promise<string>;
@@ -0,0 +1,93 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { build } from "vite";
4
+ import { resolveManifestEntry } from "./load-manifest.js";
5
+ export class BundleServerManifestError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "BundleServerManifestError";
9
+ }
10
+ }
11
+ /**
12
+ * Bundles a plugin's manifest entry (src/plugin.ts(x) plus everything it
13
+ * transitively imports — INCLUDING react, react/jsx-runtime and
14
+ * @velora-cms/plugin-sdk) into one self-contained, Node-importable ESM file
15
+ * at <outDir>/plugin.js. Replaces Session 81's tsc-emit
16
+ * compileServerManifest: the emitted file kept bare import specifiers,
17
+ * which plain `import()` can only resolve by walking ancestor
18
+ * node_modules — true inside this monorepo, false on a real server (the
19
+ * S81 gap, reproduced concretely in S83 with a poisoned ancestor
20
+ * node_modules). A bundle resolves nothing at import time, so the same
21
+ * package installs anywhere.
22
+ *
23
+ * Bundling react into a SERVER-side artifact is safe by design: the
24
+ * server validates the manifest (Zod needs the live function references),
25
+ * persists it, and invokes hooks/apiRoutes handlers — it never renders
26
+ * views. The browser keeps loading views via remoteEntry.js with the
27
+ * host's Module Federation shared singletons; this file never reaches it.
28
+ *
29
+ * Deliberately configFile: false — the plugin's own vite.config.ts is
30
+ * the BROWSER-side federation build and must not leak in here. No
31
+ * process.chdir() (the buildFederationBundle concurrency caveat does not
32
+ * spread to this function); all paths resolved absolute up front.
33
+ */
34
+ export async function bundleServerManifest(pluginDir, outDir) {
35
+ const absolutePluginDir = resolve(pluginDir);
36
+ const absoluteOutDir = resolve(outDir);
37
+ let entryPath;
38
+ try {
39
+ entryPath = resolveManifestEntry(absolutePluginDir);
40
+ }
41
+ catch (error) {
42
+ throw new BundleServerManifestError(error instanceof Error ? error.message : String(error));
43
+ }
44
+ mkdirSync(absoluteOutDir, { recursive: true });
45
+ try {
46
+ await build({
47
+ root: absolutePluginDir,
48
+ configFile: false,
49
+ logLevel: "silent",
50
+ // Bundle EVERYTHING — this is the whole point. Only node: builtins
51
+ // stay external (also enforced via rollupOptions.external below).
52
+ ssr: { noExternal: true },
53
+ build: {
54
+ ssr: entryPath,
55
+ outDir: absoluteOutDir,
56
+ emptyOutDir: false,
57
+ // Unminified: the artifact is a server-side module a human may
58
+ // need to read while debugging an install, and the specifier
59
+ // scan in this module's tests relies on plain import syntax.
60
+ minify: false,
61
+ rollupOptions: {
62
+ external: /^node:/,
63
+ output: { entryFileNames: "plugin.js", format: "es", inlineDynamicImports: true },
64
+ },
65
+ },
66
+ });
67
+ }
68
+ catch (error) {
69
+ throw new BundleServerManifestError(`failed to bundle server manifest for ${absolutePluginDir}: ${error instanceof Error ? error.message : String(error)}`);
70
+ }
71
+ const bundlePath = join(absoluteOutDir, "plugin.js");
72
+ if (!existsSync(bundlePath)) {
73
+ throw new BundleServerManifestError(`bundled output missing expected entry ${bundlePath}`);
74
+ }
75
+ // Node picks a module format per file by walking UP from that file
76
+ // looking for the nearest package.json and reading its "type" field —
77
+ // ancestor directories, not just the immediate one. plugin.js itself has
78
+ // no extension marker (it stays "plugin.js", not "plugin.mjs" —
79
+ // resolveBuiltManifestPath's path is fixed), so without a package.json
80
+ // right here, format detection keeps walking past this outDir to
81
+ // whatever package.json happens to sit above wherever the package gets
82
+ // extracted on a real server — usually none, which makes Node default to
83
+ // CommonJS and fail parsing this ESM bundle with "Unexpected token
84
+ // 'export'". A package.json written into THIS SAME directory always
85
+ // wins (nearest match beats any ancestor), so the package is
86
+ // self-describing no matter where it's extracted. vitest's module runner
87
+ // (vite-node) always executes as ESM regardless of this marker, so the
88
+ // in-repo test suite alone can never catch its absence — only a plain
89
+ // Node child-process import (see bundle-server-manifest.test.ts) exposes
90
+ // the production failure this fixes.
91
+ writeFileSync(join(absoluteOutDir, "package.json"), '{"type":"module"}\n');
92
+ return bundlePath;
93
+ }
@@ -0,0 +1,2 @@
1
+ import type { CheckResult } from "../types.js";
2
+ export declare function checkNpmAudit(pluginDir: string): CheckResult;