@uniweb/build 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,210 @@
1
+ # @uniweb/build
2
+
3
+ Foundation build tooling for the Uniweb Component Web Platform.
4
+
5
+ ## Overview
6
+
7
+ This package provides build utilities for creating Uniweb Foundations—React component libraries that define the vocabulary and rendering logic for content-driven websites.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @uniweb/build --save-dev
13
+ ```
14
+
15
+ ## Features
16
+
17
+ - **Component Discovery** - Automatically discovers components from `src/components/*/meta.js`
18
+ - **Entry Generation** - Generates the foundation entry point with all exports
19
+ - **Schema Building** - Creates `schema.json` with full component metadata for editors
20
+ - **Image Processing** - Converts preview images to WebP format with dimension extraction
21
+ - **Vite Plugin** - Integrates seamlessly with Vite builds
22
+
23
+ ## Usage
24
+
25
+ ### Vite Plugin
26
+
27
+ Add the foundation plugin to your `vite.config.js`:
28
+
29
+ ```js
30
+ import { defineConfig } from 'vite'
31
+ import react from '@vitejs/plugin-react'
32
+ import { foundationPlugin } from '@uniweb/build'
33
+
34
+ export default defineConfig({
35
+ plugins: [
36
+ react(),
37
+ foundationPlugin()
38
+ ],
39
+ build: {
40
+ lib: {
41
+ entry: 'src/_entry.generated.js',
42
+ formats: ['es'],
43
+ fileName: 'foundation'
44
+ },
45
+ rollupOptions: {
46
+ external: ['react', 'react-dom', 'react/jsx-runtime']
47
+ }
48
+ }
49
+ })
50
+ ```
51
+
52
+ ### Programmatic API
53
+
54
+ ```js
55
+ import {
56
+ discoverComponents,
57
+ buildSchema,
58
+ generateEntryPoint,
59
+ processAllPreviews
60
+ } from '@uniweb/build'
61
+
62
+ // Discover components in a foundation
63
+ const components = await discoverComponents('./src')
64
+ // => { Hero: { title: 'Hero Banner', ... }, Features: { ... } }
65
+
66
+ // Build complete schema
67
+ const schema = await buildSchema('./src')
68
+ // => { _self: { name: 'My Foundation' }, Hero: {...}, Features: {...} }
69
+
70
+ // Generate entry point
71
+ await generateEntryPoint('./src', './src/_entry.generated.js')
72
+
73
+ // Process preview images
74
+ const { schema: withImages, totalImages } = await processAllPreviews(
75
+ './src',
76
+ './dist',
77
+ schema,
78
+ true // production mode - converts to webp
79
+ )
80
+ ```
81
+
82
+ ## Foundation Structure
83
+
84
+ Foundations use a folder-based component structure:
85
+
86
+ ```
87
+ src/
88
+ ├── meta.js # Foundation-level metadata
89
+ ├── index.css # Global styles (Tailwind)
90
+ ├── components/
91
+ │ └── Hero/
92
+ │ ├── index.jsx # Component implementation
93
+ │ ├── meta.js # Component metadata
94
+ │ └── previews/ # Preset preview images
95
+ │ └── default.png
96
+ ```
97
+
98
+ ### Component Meta File
99
+
100
+ ```js
101
+ // src/components/Hero/meta.js
102
+ export default {
103
+ title: 'Hero Banner',
104
+ description: 'A prominent header section',
105
+ category: 'Headers',
106
+
107
+ elements: {
108
+ title: { label: 'Headline', required: true },
109
+ subtitle: { label: 'Subtitle' },
110
+ },
111
+
112
+ properties: {
113
+ alignment: {
114
+ type: 'select',
115
+ label: 'Text Alignment',
116
+ options: [
117
+ { value: 'center', label: 'Center' },
118
+ { value: 'left', label: 'Left' },
119
+ ],
120
+ default: 'center',
121
+ },
122
+ },
123
+
124
+ presets: {
125
+ default: { label: 'Default', properties: {} },
126
+ dark: { label: 'Dark Theme', properties: { theme: 'dark' } },
127
+ },
128
+ }
129
+ ```
130
+
131
+ ### Foundation Meta File
132
+
133
+ ```js
134
+ // src/meta.js
135
+ export default {
136
+ name: 'My Foundation',
137
+ description: 'Components for marketing websites',
138
+
139
+ // Runtime props available to all components
140
+ props: {
141
+ themeToggleEnabled: true,
142
+ },
143
+
144
+ // Foundation-wide style configuration
145
+ styleFields: [
146
+ {
147
+ id: 'primary-color',
148
+ type: 'color',
149
+ label: 'Primary Color',
150
+ default: '#3b82f6',
151
+ },
152
+ ],
153
+ }
154
+ ```
155
+
156
+ ## Build Output
157
+
158
+ After building, your foundation will contain:
159
+
160
+ ```
161
+ dist/
162
+ ├── foundation.js # Bundled components (~6KB typical)
163
+ ├── foundation.js.map # Source map
164
+ ├── schema.json # Full metadata for editors
165
+ └── assets/
166
+ └── Hero/
167
+ └── default.webp # Processed preview images
168
+ ```
169
+
170
+ ## API Reference
171
+
172
+ ### Schema Functions
173
+
174
+ | Function | Description |
175
+ |----------|-------------|
176
+ | `discoverComponents(srcDir)` | Discover all exposed components |
177
+ | `loadComponentMeta(componentDir)` | Load meta file for a component |
178
+ | `loadFoundationMeta(srcDir)` | Load foundation-level meta |
179
+ | `buildSchema(srcDir)` | Build complete schema object |
180
+ | `buildRuntimeConfig(srcDir)` | Build minimal runtime config |
181
+
182
+ ### Entry Generation
183
+
184
+ | Function | Description |
185
+ |----------|-------------|
186
+ | `generateEntryPoint(srcDir, outputPath)` | Generate foundation entry file |
187
+
188
+ ### Image Processing
189
+
190
+ | Function | Description |
191
+ |----------|-------------|
192
+ | `processComponentPreviews(componentDir, name, outputDir, isProduction)` | Process one component's previews |
193
+ | `processAllPreviews(srcDir, outputDir, schema, isProduction)` | Process all preview images |
194
+
195
+ ### Vite Plugins
196
+
197
+ | Plugin | Description |
198
+ |--------|-------------|
199
+ | `foundationPlugin(options)` | Combined dev + build plugin |
200
+ | `foundationBuildPlugin(options)` | Build-only plugin |
201
+ | `foundationDevPlugin(options)` | Dev-only plugin with HMR |
202
+
203
+ ## Related Packages
204
+
205
+ - [`uniweb`](https://github.com/uniweb/cli) - CLI for creating Uniweb projects
206
+ - [`@uniweb/runtime`](https://github.com/uniweb/runtime) - Runtime loader for sites
207
+
208
+ ## License
209
+
210
+ Apache 2.0
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@uniweb/build",
3
+ "version": "0.1.0",
4
+ "description": "Foundation build tooling for the Uniweb Component Web Platform",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.js",
8
+ "./schema": "./src/schema.js",
9
+ "./images": "./src/images.js",
10
+ "./generate-entry": "./src/generate-entry.js",
11
+ "./vite-plugin": "./src/vite-foundation-plugin.js"
12
+ },
13
+ "files": [
14
+ "src"
15
+ ],
16
+ "keywords": [
17
+ "uniweb",
18
+ "foundation",
19
+ "build",
20
+ "vite",
21
+ "components"
22
+ ],
23
+ "author": "Proximify",
24
+ "license": "Apache-2.0",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/uniweb/build.git"
28
+ },
29
+ "homepage": "https://github.com/uniweb/build#readme",
30
+ "bugs": {
31
+ "url": "https://github.com/uniweb/build/issues"
32
+ },
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "dependencies": {
37
+ "sharp": "^0.33.2"
38
+ },
39
+ "peerDependencies": {
40
+ "vite": "^5.0.0 || ^6.0.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "vite": {
44
+ "optional": true
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Foundation Entry Point Generator
3
+ *
4
+ * Auto-generates the foundation entry point based on discovered components.
5
+ * The generated file exports components and runtime configuration.
6
+ */
7
+
8
+ import { writeFile, mkdir } from 'node:fs/promises'
9
+ import { existsSync } from 'node:fs'
10
+ import { join, dirname } from 'node:path'
11
+ import {
12
+ discoverComponents,
13
+ loadFoundationMeta,
14
+ extractRuntimeConfig,
15
+ } from './schema.js'
16
+
17
+ /**
18
+ * Generate the entry point source code
19
+ */
20
+ function generateEntrySource(componentNames, runtimeConfig, options = {}) {
21
+ const { includeCss = true, cssPath = './index.css', componentExtensions = {} } = options
22
+
23
+ const imports = []
24
+ const exports = []
25
+
26
+ // CSS import
27
+ if (includeCss) {
28
+ imports.push(`import '${cssPath}'`)
29
+ }
30
+
31
+ // Component imports (use detected extension or default to .js)
32
+ for (const name of componentNames) {
33
+ const ext = componentExtensions[name] || 'js'
34
+ imports.push(`import ${name} from './components/${name}/index.${ext}'`)
35
+ }
36
+
37
+ // Build components object
38
+ const componentsObj = `const components = {\n ${componentNames.join(',\n ')},\n}`
39
+
40
+ // Runtime config (serialized)
41
+ const configStr = JSON.stringify(runtimeConfig, null, 2)
42
+ .split('\n')
43
+ .map((line, i) => (i === 0 ? line : ' ' + line))
44
+ .join('\n')
45
+
46
+ const runtimeConfigBlock = `
47
+ // Runtime configuration (extracted from meta files)
48
+ // Only includes properties needed at render time
49
+ const runtimeConfig = ${configStr}`
50
+
51
+ // Export functions
52
+ const exportFunctions = `
53
+ /**
54
+ * Get a component by name
55
+ */
56
+ export function getComponent(name) {
57
+ return components[name]
58
+ }
59
+
60
+ /**
61
+ * List all available component names
62
+ */
63
+ export function listComponents() {
64
+ return Object.keys(components)
65
+ }
66
+
67
+ /**
68
+ * Get runtime config for a specific component
69
+ * Returns input schema and other render-time properties
70
+ */
71
+ export function getComponentConfig(name) {
72
+ return runtimeConfig.components[name] || {}
73
+ }
74
+
75
+ /**
76
+ * Get foundation-level runtime config
77
+ */
78
+ export function getFoundationConfig() {
79
+ return runtimeConfig.foundation
80
+ }
81
+
82
+ /**
83
+ * Get all component schemas (for compatibility)
84
+ * Note: Full schemas are in schema.json, this only returns runtime-relevant config
85
+ */
86
+ export function getAllSchemas() {
87
+ const schemas = {}
88
+ for (const name of Object.keys(components)) {
89
+ if (components[name].schema) {
90
+ schemas[name] = components[name].schema
91
+ }
92
+ }
93
+ return schemas
94
+ }
95
+
96
+ /**
97
+ * Get schema for a specific component (for compatibility)
98
+ */
99
+ export function getSchema(name) {
100
+ return components[name]?.schema
101
+ }`
102
+
103
+ // Named exports for direct imports
104
+ const namedExports = componentNames.length > 0
105
+ ? `\n// Named exports for direct imports\nexport { ${componentNames.join(', ')} }`
106
+ : ''
107
+
108
+ return `// Auto-generated foundation entry point
109
+ // DO NOT EDIT - This file is regenerated during build
110
+
111
+ ${imports.join('\n')}
112
+
113
+ ${componentsObj}
114
+ ${runtimeConfigBlock}
115
+ ${exportFunctions}
116
+ ${namedExports}
117
+ `
118
+ }
119
+
120
+ /**
121
+ * Detect the index file extension for a component
122
+ */
123
+ function detectComponentExtension(srcDir, componentName) {
124
+ const basePath = join(srcDir, 'components', componentName)
125
+ for (const ext of ['jsx', 'tsx', 'js', 'ts']) {
126
+ if (existsSync(join(basePath, `index.${ext}`))) {
127
+ return ext
128
+ }
129
+ }
130
+ return 'js' // default
131
+ }
132
+
133
+ /**
134
+ * Generate the foundation entry point file
135
+ */
136
+ export async function generateEntryPoint(srcDir, outputPath = null) {
137
+ // Discover components
138
+ const components = await discoverComponents(srcDir)
139
+ const componentNames = Object.keys(components).sort()
140
+
141
+ if (componentNames.length === 0) {
142
+ console.warn('Warning: No exposed components found')
143
+ }
144
+
145
+ // Detect extensions for each component
146
+ const componentExtensions = {}
147
+ for (const name of componentNames) {
148
+ componentExtensions[name] = detectComponentExtension(srcDir, name)
149
+ }
150
+
151
+ // Load foundation meta and build runtime config
152
+ const foundationMeta = await loadFoundationMeta(srcDir)
153
+
154
+ const runtimeConfig = {
155
+ foundation: extractRuntimeConfig(foundationMeta),
156
+ components: {},
157
+ }
158
+
159
+ for (const [name, meta] of Object.entries(components)) {
160
+ const config = extractRuntimeConfig(meta)
161
+ if (Object.keys(config).length > 0) {
162
+ runtimeConfig.components[name] = config
163
+ }
164
+ }
165
+
166
+ // Check if CSS exists
167
+ const cssExists = existsSync(join(srcDir, 'index.css'))
168
+
169
+ // Generate source
170
+ const source = generateEntrySource(componentNames, runtimeConfig, {
171
+ includeCss: cssExists,
172
+ componentExtensions,
173
+ })
174
+
175
+ // Write to file
176
+ const output = outputPath || join(srcDir, '_entry.generated.js')
177
+ await mkdir(dirname(output), { recursive: true })
178
+ await writeFile(output, source, 'utf-8')
179
+
180
+ console.log(`Generated entry point: ${output}`)
181
+ console.log(` - ${componentNames.length} components: ${componentNames.join(', ')}`)
182
+
183
+ return {
184
+ outputPath: output,
185
+ componentNames,
186
+ runtimeConfig,
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Check if entry point needs regeneration
192
+ * (Compare discovered components with existing generated file)
193
+ */
194
+ export async function shouldRegenerateEntry(srcDir, entryPath) {
195
+ if (!existsSync(entryPath)) return true
196
+
197
+ // Could add more sophisticated checking here
198
+ // For now, always regenerate during build
199
+ return true
200
+ }
package/src/images.js ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Image Processing Utilities
3
+ *
4
+ * Handles preview image discovery, conversion to webp, and metadata extraction.
5
+ */
6
+
7
+ import { readdir, mkdir, copyFile } from 'node:fs/promises'
8
+ import { existsSync } from 'node:fs'
9
+ import { join, extname, basename } from 'node:path'
10
+ import sharp from 'sharp'
11
+
12
+ // Supported image extensions
13
+ const IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif']
14
+
15
+ /**
16
+ * Check if a file is an image based on extension
17
+ */
18
+ function isImageFile(filename) {
19
+ const ext = extname(filename).toLowerCase()
20
+ return IMAGE_EXTENSIONS.includes(ext)
21
+ }
22
+
23
+ /**
24
+ * Get image metadata (dimensions)
25
+ */
26
+ async function getImageMetadata(imagePath) {
27
+ try {
28
+ const metadata = await sharp(imagePath).metadata()
29
+ return {
30
+ width: metadata.width,
31
+ height: metadata.height,
32
+ format: metadata.format,
33
+ }
34
+ } catch (error) {
35
+ console.warn(`Warning: Could not read metadata for ${imagePath}:`, error.message)
36
+ return null
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Convert an image to webp format
42
+ */
43
+ async function convertToWebp(inputPath, outputPath, options = {}) {
44
+ const { quality = 80 } = options
45
+
46
+ try {
47
+ await sharp(inputPath)
48
+ .webp({ quality })
49
+ .toFile(outputPath)
50
+ return true
51
+ } catch (error) {
52
+ console.warn(`Warning: Could not convert ${inputPath} to webp:`, error.message)
53
+ return false
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Process preview images for a single component
59
+ *
60
+ * @param {string} componentDir - Path to component directory (e.g., src/components/Hero)
61
+ * @param {string} componentName - Component name
62
+ * @param {string} outputDir - Output directory for processed images
63
+ * @param {boolean} isProduction - Whether to convert to webp
64
+ * @returns {Object} Map of preset name to image info
65
+ */
66
+ export async function processComponentPreviews(componentDir, componentName, outputDir, isProduction = true) {
67
+ const previewsDir = join(componentDir, 'previews')
68
+ const previews = {}
69
+
70
+ if (!existsSync(previewsDir)) {
71
+ return previews
72
+ }
73
+
74
+ // Create output directory
75
+ const componentOutputDir = join(outputDir, 'assets', componentName)
76
+ await mkdir(componentOutputDir, { recursive: true })
77
+
78
+ // Get all image files
79
+ const files = await readdir(previewsDir)
80
+ const imageFiles = files.filter(isImageFile)
81
+
82
+ for (const file of imageFiles) {
83
+ const inputPath = join(previewsDir, file)
84
+ const presetName = basename(file, extname(file))
85
+ const originalExt = extname(file).toLowerCase()
86
+
87
+ // Get original metadata
88
+ const metadata = await getImageMetadata(inputPath)
89
+ if (!metadata) continue
90
+
91
+ let outputFilename
92
+ let outputPath
93
+ let finalFormat
94
+
95
+ if (isProduction && originalExt !== '.webp') {
96
+ // Convert to webp in production
97
+ outputFilename = `${presetName}.webp`
98
+ outputPath = join(componentOutputDir, outputFilename)
99
+ finalFormat = 'webp'
100
+
101
+ const success = await convertToWebp(inputPath, outputPath)
102
+ if (!success) {
103
+ // Fall back to copying original
104
+ outputFilename = file
105
+ outputPath = join(componentOutputDir, file)
106
+ finalFormat = originalExt.slice(1)
107
+ await copyFile(inputPath, outputPath)
108
+ }
109
+ } else {
110
+ // Copy as-is in development or if already webp
111
+ outputFilename = file
112
+ outputPath = join(componentOutputDir, file)
113
+ finalFormat = originalExt.slice(1)
114
+ await copyFile(inputPath, outputPath)
115
+ }
116
+
117
+ previews[presetName] = {
118
+ path: `assets/${componentName}/${outputFilename}`,
119
+ width: metadata.width,
120
+ height: metadata.height,
121
+ type: finalFormat,
122
+ }
123
+ }
124
+
125
+ return previews
126
+ }
127
+
128
+ /**
129
+ * Process all preview images for a foundation
130
+ *
131
+ * @param {string} srcDir - Source directory (e.g., src/)
132
+ * @param {string} outputDir - Output directory (e.g., dist/)
133
+ * @param {Object} schema - Schema object to update with image info
134
+ * @param {boolean} isProduction - Whether to convert to webp
135
+ * @returns {Object} Updated schema with image references
136
+ */
137
+ export async function processAllPreviews(srcDir, outputDir, schema, isProduction = true) {
138
+ const componentsDir = join(srcDir, 'components')
139
+
140
+ if (!existsSync(componentsDir)) {
141
+ return schema
142
+ }
143
+
144
+ const entries = await readdir(componentsDir, { withFileTypes: true })
145
+ let totalImages = 0
146
+
147
+ for (const entry of entries) {
148
+ if (!entry.isDirectory()) continue
149
+
150
+ const componentName = entry.name
151
+ const componentDir = join(componentsDir, componentName)
152
+
153
+ // Skip if component not in schema
154
+ if (!schema[componentName]) continue
155
+
156
+ // Process preview images
157
+ const previews = await processComponentPreviews(
158
+ componentDir,
159
+ componentName,
160
+ outputDir,
161
+ isProduction
162
+ )
163
+
164
+ const previewCount = Object.keys(previews).length
165
+ if (previewCount > 0) {
166
+ totalImages += previewCount
167
+
168
+ // Attach preview info to presets in schema
169
+ if (schema[componentName].presets) {
170
+ for (const [presetName, previewInfo] of Object.entries(previews)) {
171
+ if (schema[componentName].presets[presetName]) {
172
+ schema[componentName].presets[presetName].image = previewInfo
173
+ } else {
174
+ // Preview exists but no matching preset - still include it
175
+ // This allows standalone preview images
176
+ if (!schema[componentName].images) {
177
+ schema[componentName].images = {}
178
+ }
179
+ schema[componentName].images[presetName] = previewInfo
180
+ }
181
+ }
182
+ } else {
183
+ // No presets defined, add as standalone images
184
+ schema[componentName].images = previews
185
+ }
186
+ }
187
+ }
188
+
189
+ return { schema, totalImages }
190
+ }
191
+
192
+ /**
193
+ * Copy a single image with optional conversion
194
+ */
195
+ export async function processImage(inputPath, outputPath, options = {}) {
196
+ const { convertToWebp: shouldConvert = false, quality = 80 } = options
197
+
198
+ const ext = extname(inputPath).toLowerCase()
199
+
200
+ if (shouldConvert && ext !== '.webp') {
201
+ const webpPath = outputPath.replace(/\.[^.]+$/, '.webp')
202
+ const success = await convertToWebp(inputPath, webpPath, { quality })
203
+ if (success) {
204
+ return { path: webpPath, converted: true }
205
+ }
206
+ }
207
+
208
+ // Copy as-is
209
+ await mkdir(join(outputPath, '..'), { recursive: true })
210
+ await copyFile(inputPath, outputPath)
211
+ return { path: outputPath, converted: false }
212
+ }
package/src/index.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @uniweb/build - Foundation Build Tooling
3
+ *
4
+ * Build utilities for Uniweb Foundations.
5
+ */
6
+
7
+ // Schema discovery and loading
8
+ export {
9
+ loadComponentMeta,
10
+ loadFoundationMeta,
11
+ discoverComponents,
12
+ extractRuntimeConfig,
13
+ buildSchema,
14
+ buildRuntimeConfig,
15
+ getExposedComponents,
16
+ } from './schema.js'
17
+
18
+ // Entry point generation
19
+ export {
20
+ generateEntryPoint,
21
+ shouldRegenerateEntry,
22
+ } from './generate-entry.js'
23
+
24
+ // Image processing
25
+ export {
26
+ processComponentPreviews,
27
+ processAllPreviews,
28
+ processImage,
29
+ } from './images.js'
30
+
31
+ // Vite plugins
32
+ export {
33
+ foundationPlugin,
34
+ foundationBuildPlugin,
35
+ foundationDevPlugin,
36
+ } from './vite-foundation-plugin.js'
37
+
38
+ // Default export is the combined Vite plugin
39
+ export { default } from './vite-foundation-plugin.js'
package/src/schema.js ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Schema Discovery and Loading Utilities
3
+ *
4
+ * Discovers component meta files, loads them, and extracts
5
+ * runtime-relevant configuration.
6
+ */
7
+
8
+ import { readdir, readFile } from 'node:fs/promises'
9
+ import { existsSync } from 'node:fs'
10
+ import { join, basename } from 'node:path'
11
+ import { pathToFileURL } from 'node:url'
12
+
13
+ // Meta file names in order of preference
14
+ const META_FILE_NAMES = ['meta.js', 'config.js', 'config.yml', 'meta.yml']
15
+
16
+ // Keys that should be extracted for runtime (embedded in foundation.js)
17
+ const RUNTIME_KEYS = ['input', 'props']
18
+
19
+ /**
20
+ * Simple YAML parser for backwards compatibility
21
+ * Supports basic key-value, nested objects, and arrays
22
+ */
23
+ function parseYaml(content) {
24
+ const lines = content.split('\n')
25
+ return parseYamlLines(lines, 0).value
26
+ }
27
+
28
+ function getIndent(line) {
29
+ const match = line.match(/^(\s*)/)
30
+ return match ? match[1].length : 0
31
+ }
32
+
33
+ function parseYamlValue(value) {
34
+ const trimmed = value.trim()
35
+ if (!trimmed) return null
36
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
37
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
38
+ return trimmed.slice(1, -1)
39
+ }
40
+ if (trimmed === 'true') return true
41
+ if (trimmed === 'false') return false
42
+ if (!isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed)
43
+ return trimmed
44
+ }
45
+
46
+ function parseYamlLines(lines, startIndex, baseIndent = 0) {
47
+ const result = {}
48
+ let i = startIndex
49
+
50
+ while (i < lines.length) {
51
+ const line = lines[i]
52
+ const trimmed = line.trim()
53
+
54
+ if (!trimmed || trimmed.startsWith('#')) {
55
+ i++
56
+ continue
57
+ }
58
+
59
+ const indent = getIndent(line)
60
+ if (indent < baseIndent && i > startIndex) break
61
+ if (trimmed.startsWith('- ')) {
62
+ i++
63
+ continue
64
+ }
65
+
66
+ const colonIndex = trimmed.indexOf(':')
67
+ if (colonIndex === -1) {
68
+ i++
69
+ continue
70
+ }
71
+
72
+ const key = trimmed.slice(0, colonIndex).trim()
73
+ const valueAfterColon = trimmed.slice(colonIndex + 1).trim()
74
+
75
+ const nextLine = lines[i + 1]
76
+ const nextTrimmed = nextLine?.trim()
77
+ const nextIndent = nextLine ? getIndent(nextLine) : 0
78
+
79
+ if (nextTrimmed?.startsWith('- ') && nextIndent > indent) {
80
+ const arrayResult = parseYamlArray(lines, i + 1, nextIndent)
81
+ result[key] = arrayResult.value
82
+ i = arrayResult.endIndex
83
+ } else if (!valueAfterColon && nextIndent > indent) {
84
+ const nestedResult = parseYamlLines(lines, i + 1, nextIndent)
85
+ result[key] = nestedResult.value
86
+ i = nestedResult.endIndex
87
+ } else {
88
+ result[key] = parseYamlValue(valueAfterColon)
89
+ i++
90
+ }
91
+ }
92
+
93
+ return { value: result, endIndex: i }
94
+ }
95
+
96
+ function parseYamlArray(lines, startIndex, baseIndent) {
97
+ const result = []
98
+ let i = startIndex
99
+
100
+ while (i < lines.length) {
101
+ const line = lines[i]
102
+ const trimmed = line.trim()
103
+
104
+ if (!trimmed || trimmed.startsWith('#')) {
105
+ i++
106
+ continue
107
+ }
108
+
109
+ const indent = getIndent(line)
110
+ if (indent < baseIndent) break
111
+
112
+ if (trimmed.startsWith('- ')) {
113
+ const afterDash = trimmed.slice(2)
114
+ const colonIndex = afterDash.indexOf(':')
115
+
116
+ if (colonIndex !== -1) {
117
+ const key = afterDash.slice(0, colonIndex).trim()
118
+ const value = afterDash.slice(colonIndex + 1).trim()
119
+ const obj = { [key]: parseYamlValue(value) }
120
+ const itemIndent = indent + 2
121
+ i++
122
+
123
+ while (i < lines.length) {
124
+ const propLine = lines[i]
125
+ const propTrimmed = propLine?.trim()
126
+
127
+ if (!propTrimmed || propTrimmed.startsWith('#')) {
128
+ i++
129
+ continue
130
+ }
131
+
132
+ const propIndent = getIndent(propLine)
133
+ if (propIndent < itemIndent || propTrimmed.startsWith('- ')) break
134
+
135
+ const propColonIndex = propTrimmed.indexOf(':')
136
+ if (propColonIndex !== -1) {
137
+ const propKey = propTrimmed.slice(0, propColonIndex).trim()
138
+ const propValue = propTrimmed.slice(propColonIndex + 1).trim()
139
+ obj[propKey] = parseYamlValue(propValue)
140
+ }
141
+ i++
142
+ }
143
+
144
+ result.push(obj)
145
+ } else {
146
+ result.push(parseYamlValue(afterDash))
147
+ i++
148
+ }
149
+ } else {
150
+ break
151
+ }
152
+ }
153
+
154
+ return { value: result, endIndex: i }
155
+ }
156
+
157
+ /**
158
+ * Load a meta file (JS or YAML)
159
+ */
160
+ async function loadMetaFile(filePath) {
161
+ if (filePath.endsWith('.js')) {
162
+ // Dynamic import for JS files
163
+ const fileUrl = pathToFileURL(filePath).href
164
+ const module = await import(fileUrl)
165
+ return module.default
166
+ } else {
167
+ // Parse YAML
168
+ const content = await readFile(filePath, 'utf-8')
169
+ return parseYaml(content)
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Find and load meta file for a component directory
175
+ * Returns null if no meta file found
176
+ */
177
+ export async function loadComponentMeta(componentDir) {
178
+ for (const fileName of META_FILE_NAMES) {
179
+ const filePath = join(componentDir, fileName)
180
+ if (existsSync(filePath)) {
181
+ try {
182
+ const meta = await loadMetaFile(filePath)
183
+ return { meta, fileName, filePath }
184
+ } catch (error) {
185
+ console.warn(`Warning: Failed to load ${filePath}:`, error.message)
186
+ return null
187
+ }
188
+ }
189
+ }
190
+ return null
191
+ }
192
+
193
+ /**
194
+ * Load foundation-level meta file
195
+ */
196
+ export async function loadFoundationMeta(srcDir) {
197
+ for (const fileName of META_FILE_NAMES) {
198
+ const filePath = join(srcDir, fileName)
199
+ if (existsSync(filePath)) {
200
+ try {
201
+ return await loadMetaFile(filePath)
202
+ } catch (error) {
203
+ console.warn(`Warning: Failed to load foundation meta ${filePath}:`, error.message)
204
+ return {}
205
+ }
206
+ }
207
+ }
208
+ return {}
209
+ }
210
+
211
+ /**
212
+ * Discover all exposed components in a foundation
213
+ * Returns map of componentName -> meta
214
+ */
215
+ export async function discoverComponents(srcDir) {
216
+ const componentsDir = join(srcDir, 'components')
217
+
218
+ if (!existsSync(componentsDir)) {
219
+ return {}
220
+ }
221
+
222
+ const entries = await readdir(componentsDir, { withFileTypes: true })
223
+ const components = {}
224
+
225
+ for (const entry of entries) {
226
+ if (!entry.isDirectory()) continue
227
+
228
+ const componentDir = join(componentsDir, entry.name)
229
+ const result = await loadComponentMeta(componentDir)
230
+
231
+ if (result && result.meta) {
232
+ // Check if explicitly not exposed
233
+ if (result.meta.exposed === false) {
234
+ continue
235
+ }
236
+
237
+ components[entry.name] = {
238
+ name: entry.name,
239
+ ...result.meta,
240
+ }
241
+ }
242
+ }
243
+
244
+ return components
245
+ }
246
+
247
+ /**
248
+ * Extract runtime-relevant config from meta
249
+ * Only includes keys that are needed at render time
250
+ */
251
+ export function extractRuntimeConfig(meta) {
252
+ if (!meta) return {}
253
+
254
+ const config = {}
255
+ for (const key of RUNTIME_KEYS) {
256
+ if (meta[key] !== undefined) {
257
+ config[key] = meta[key]
258
+ }
259
+ }
260
+ return config
261
+ }
262
+
263
+ /**
264
+ * Build complete schema for a foundation
265
+ * Returns { _self: foundationMeta, ComponentName: componentMeta, ... }
266
+ */
267
+ export async function buildSchema(srcDir) {
268
+ const foundationMeta = await loadFoundationMeta(srcDir)
269
+ const components = await discoverComponents(srcDir)
270
+
271
+ return {
272
+ _self: foundationMeta,
273
+ ...components,
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Build runtime config (minimal, for embedding in foundation.js)
279
+ */
280
+ export async function buildRuntimeConfig(srcDir) {
281
+ const foundationMeta = await loadFoundationMeta(srcDir)
282
+ const components = await discoverComponents(srcDir)
283
+
284
+ const componentConfigs = {}
285
+ for (const [name, meta] of Object.entries(components)) {
286
+ const config = extractRuntimeConfig(meta)
287
+ if (Object.keys(config).length > 0) {
288
+ componentConfigs[name] = config
289
+ }
290
+ }
291
+
292
+ return {
293
+ foundation: extractRuntimeConfig(foundationMeta),
294
+ components: componentConfigs,
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Get list of exposed component names
300
+ */
301
+ export async function getExposedComponents(srcDir) {
302
+ const components = await discoverComponents(srcDir)
303
+ return Object.keys(components)
304
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Vite Plugin for Foundation Builds
3
+ *
4
+ * Handles:
5
+ * - Auto-generating entry point from discovered components
6
+ * - Building schema.json from meta files
7
+ * - Processing preview images for presets
8
+ */
9
+
10
+ import { writeFile, readFile, readdir, mkdir } from 'node:fs/promises'
11
+ import { existsSync } from 'node:fs'
12
+ import { join, resolve, relative } from 'node:path'
13
+ import { buildSchema, discoverComponents } from './schema.js'
14
+ import { generateEntryPoint } from './generate-entry.js'
15
+ import { processAllPreviews } from './images.js'
16
+
17
+ /**
18
+ * Build schema.json with preview image references
19
+ */
20
+ async function buildSchemaWithPreviews(srcDir, outDir, isProduction) {
21
+ const schema = await buildSchema(srcDir)
22
+
23
+ // Process preview images
24
+ const { schema: schemaWithImages, totalImages } = await processAllPreviews(
25
+ srcDir,
26
+ outDir,
27
+ schema,
28
+ isProduction
29
+ )
30
+
31
+ if (totalImages > 0) {
32
+ console.log(`Processed ${totalImages} preview images`)
33
+ }
34
+
35
+ return schemaWithImages
36
+ }
37
+
38
+ /**
39
+ * Vite plugin for foundation builds
40
+ */
41
+ export function foundationBuildPlugin(options = {}) {
42
+ const {
43
+ srcDir = 'src',
44
+ generateEntry = true,
45
+ entryFileName = '_entry.generated.js',
46
+ } = options
47
+
48
+ let resolvedSrcDir
49
+ let resolvedOutDir
50
+ let isProduction
51
+
52
+ return {
53
+ name: 'uniweb-foundation-build',
54
+
55
+ async configResolved(config) {
56
+ resolvedSrcDir = resolve(config.root, srcDir)
57
+ resolvedOutDir = config.build.outDir
58
+ isProduction = config.mode === 'production'
59
+ },
60
+
61
+ async buildStart() {
62
+ if (!generateEntry) return
63
+
64
+ // Generate entry point before build starts
65
+ const entryPath = join(resolvedSrcDir, entryFileName)
66
+ await generateEntryPoint(resolvedSrcDir, entryPath)
67
+ },
68
+
69
+ async writeBundle() {
70
+ // After bundle is written, generate schema.json
71
+ const outDir = resolve(resolvedOutDir)
72
+
73
+ const schema = await buildSchemaWithPreviews(
74
+ resolvedSrcDir,
75
+ outDir,
76
+ isProduction
77
+ )
78
+
79
+ const schemaPath = join(outDir, 'schema.json')
80
+ await writeFile(schemaPath, JSON.stringify(schema, null, 2), 'utf-8')
81
+
82
+ console.log(`Generated schema.json with ${Object.keys(schema).length - 1} components`)
83
+ },
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Vite plugin for development mode
89
+ * Watches meta files and regenerates entry on change
90
+ */
91
+ export function foundationDevPlugin(options = {}) {
92
+ const {
93
+ srcDir = 'src',
94
+ entryFileName = '_entry.generated.js',
95
+ } = options
96
+
97
+ let resolvedSrcDir
98
+
99
+ return {
100
+ name: 'uniweb-foundation-dev',
101
+
102
+ configResolved(config) {
103
+ resolvedSrcDir = resolve(config.root, srcDir)
104
+ },
105
+
106
+ async buildStart() {
107
+ // Generate entry point at dev server start
108
+ const entryPath = join(resolvedSrcDir, entryFileName)
109
+ await generateEntryPoint(resolvedSrcDir, entryPath)
110
+ },
111
+
112
+ async handleHotUpdate({ file, server }) {
113
+ // Regenerate entry when meta files change
114
+ if (file.includes('/components/') && file.match(/meta\.(js|yml)$|config\.(js|yml)$/)) {
115
+ console.log('Meta file changed, regenerating entry...')
116
+ const entryPath = join(resolvedSrcDir, entryFileName)
117
+ await generateEntryPoint(resolvedSrcDir, entryPath)
118
+
119
+ // Trigger full reload since entry changed
120
+ server.ws.send({ type: 'full-reload' })
121
+ }
122
+ },
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Combined plugin that works for both dev and build
128
+ */
129
+ export function foundationPlugin(options = {}) {
130
+ const buildPlugin = foundationBuildPlugin(options)
131
+ const devPlugin = foundationDevPlugin(options)
132
+
133
+ return {
134
+ name: 'uniweb-foundation',
135
+
136
+ configResolved(config) {
137
+ buildPlugin.configResolved?.(config)
138
+ devPlugin.configResolved?.(config)
139
+ },
140
+
141
+ async buildStart() {
142
+ await devPlugin.buildStart?.()
143
+ },
144
+
145
+ async writeBundle(...args) {
146
+ await buildPlugin.writeBundle?.(...args)
147
+ },
148
+
149
+ handleHotUpdate(...args) {
150
+ return devPlugin.handleHotUpdate?.(...args)
151
+ },
152
+ }
153
+ }
154
+
155
+ export default foundationPlugin