@ai.all/ds 0.0.0-stage → 0.1.0-beta.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/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@ai.all/ds",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Static-site build and delivery optimization engine for AI.ALL",
5
+ "keywords": [
6
+ "ai.all",
7
+ "static-site",
8
+ "build",
9
+ "optimization",
10
+ "critical-css",
11
+ "brotli",
12
+ "gzip"
13
+ ],
14
+ "homepage": "https://github.com/ai-all-ai/ds#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/ai-all-ai/ds.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/ai-all-ai/ds/issues"
21
+ },
22
+ "license": "MIT",
23
+ "author": "Igor Orlov",
24
+ "type": "module",
25
+ "exports": {
26
+ ".": "./src/index.mjs",
27
+ "./nuxt": "./nuxt/module.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "bin": {
31
+ "ds": "bin/ds.js"
32
+ },
33
+ "files": [
34
+ "bin/",
35
+ "brand/",
36
+ "docs/",
37
+ "nuxt/",
38
+ "src/",
39
+ "ALL.md",
40
+ "CHANGELOG.md",
41
+ "LICENSE",
42
+ "README.md",
43
+ "ds.config.schema.json"
44
+ ],
45
+ "engines": {
46
+ "node": ">=20.19.0"
47
+ },
48
+ "dependencies": {
49
+ "beasties": "^0.5.7",
50
+ "cross-spawn": "^7.0.6",
51
+ "html-minifier-terser": "^7.2.0"
52
+ },
53
+ "peerDependencies": {
54
+ "nuxt": "^4.0.0"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "nuxt": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "publishConfig": {
62
+ "access": "public",
63
+ "registry": "https://registry.npmjs.org/",
64
+ "tag": "next"
65
+ },
66
+ "scripts": {
67
+ "test": "node --test",
68
+ "format": "npx --yes prettier@3.10.1 --write \"**/*.{js,mjs,cjs,json,yml,yaml}\"",
69
+ "format:check": "npx --yes prettier@3.10.1 --check \"**/*.{js,mjs,cjs,json,yml,yaml}\"",
70
+ "prepublishOnly": "npm run format:check && npm test",
71
+ "verify": "npm run format:check && npm test && npm pack --dry-run"
72
+ }
73
+ }
package/src/build.mjs ADDED
@@ -0,0 +1,18 @@
1
+ import spawn from 'cross-spawn';
2
+
3
+ export function runGenerator(command, cwd) {
4
+ const [executable, ...args] = command;
5
+ return new Promise((resolve, reject) => {
6
+ const child = spawn(executable, args, { cwd, stdio: 'inherit' });
7
+ child.once('error', reject);
8
+ child.once('close', (code, signal) => {
9
+ if (code === 0) resolve();
10
+ else
11
+ reject(
12
+ new Error(
13
+ `Generator failed${signal ? ` with signal ${signal}` : ` with exit code ${code}`}.`,
14
+ ),
15
+ );
16
+ });
17
+ });
18
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,172 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {
4
+ DEFAULT_CONFIG,
5
+ loadConfig,
6
+ resolveOutputDirectory,
7
+ } from './config.mjs';
8
+ import { runGenerator } from './build.mjs';
9
+ import { optimizeOutput } from './optimize.mjs';
10
+ import { analyzeOutput, formatReport } from './report.mjs';
11
+
12
+ const projectRoot = process.cwd();
13
+ const packageJson = JSON.parse(
14
+ await fs.readFile(new URL('../package.json', import.meta.url), 'utf8'),
15
+ );
16
+
17
+ function help() {
18
+ return `DS ${packageJson.version}
19
+
20
+ Usage:
21
+ ds init
22
+ ds build [--config <file>]
23
+ ds optimize [--dir <output>] [--config <file>]
24
+ ds analyze [--dir <output>] [--config <file>] [--json]
25
+
26
+ Commands:
27
+ init Create ds.config.json without overwriting existing files
28
+ build Run the configured static generator, then optimize its output
29
+ optimize Optimize an existing static output directory
30
+ analyze Report raw, gzip and Brotli sizes for the output
31
+
32
+ Critical CSS and HTML minification are opt-in. See README.md for configuration.`;
33
+ }
34
+
35
+ function parseOptions(args) {
36
+ const options = {
37
+ config: 'ds.config.json',
38
+ dir: null,
39
+ json: false,
40
+ positional: [],
41
+ };
42
+ for (let index = 0; index < args.length; index += 1) {
43
+ const argument = args[index];
44
+ if (argument === '--config' || argument === '--dir') {
45
+ const value = args[index + 1];
46
+ if (!value || value.startsWith('--'))
47
+ throw new Error(`${argument} requires a value.`);
48
+ options[argument === '--config' ? 'config' : 'dir'] = value;
49
+ index += 1;
50
+ } else if (argument === '--json') options.json = true;
51
+ else if (argument.startsWith('-'))
52
+ throw new Error(`Unknown option: ${argument}`);
53
+ else options.positional.push(argument);
54
+ }
55
+ return options;
56
+ }
57
+
58
+ async function loadProjectConfig(configFile) {
59
+ return loadConfig(projectRoot, configFile);
60
+ }
61
+
62
+ async function getOutputDirectory(config, options) {
63
+ return resolveOutputDirectory(
64
+ projectRoot,
65
+ options.dir ?? config.generator.outputDir,
66
+ );
67
+ }
68
+
69
+ async function writeConfig() {
70
+ const configPath = path.join(projectRoot, 'ds.config.json');
71
+ try {
72
+ await fs.access(configPath);
73
+ console.log('Kept existing ds.config.json.');
74
+ } catch (error) {
75
+ if (error.code !== 'ENOENT') throw error;
76
+ await fs.writeFile(
77
+ configPath,
78
+ `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`,
79
+ { flag: 'wx' },
80
+ );
81
+ console.log('Created ds.config.json.');
82
+ }
83
+
84
+ const packagePath = path.join(projectRoot, 'package.json');
85
+ try {
86
+ const pkg = JSON.parse(await fs.readFile(packagePath, 'utf8'));
87
+ pkg.scripts ??= {};
88
+ if (pkg.scripts.generate && !pkg.scripts['generate:optimized']) {
89
+ pkg.scripts['generate:optimized'] = 'ds build';
90
+ await fs.writeFile(packagePath, `${JSON.stringify(pkg, null, 2)}\n`);
91
+ console.log('Added package script generate:optimized.');
92
+ }
93
+ } catch (error) {
94
+ if (error.code !== 'ENOENT') throw error;
95
+ }
96
+ }
97
+
98
+ export async function main(args) {
99
+ const command = args[0];
100
+ if (!command || command === '--help' || command === '-h') {
101
+ console.log(help());
102
+ return;
103
+ }
104
+ if (command === '--version' || command === '-v') {
105
+ console.log(packageJson.version);
106
+ return;
107
+ }
108
+ if (command === 'init') {
109
+ if (args.length > 1) throw new Error('Usage: ds init');
110
+ await writeConfig();
111
+ return;
112
+ }
113
+
114
+ const options = parseOptions(args.slice(1));
115
+ if (command === 'build') {
116
+ if (options.positional.length || options.dir || options.json) {
117
+ throw new Error('Usage: ds build [--config <file>]');
118
+ }
119
+ const config = await loadProjectConfig(options.config);
120
+ console.log(`Running: ${config.generator.command.join(' ')}`);
121
+ await runGenerator(config.generator.command, projectRoot);
122
+ const outputDir = await getOutputDirectory(config, options);
123
+ const result = await optimizeOutput(outputDir, config.optimization);
124
+ console.log(
125
+ `Optimized ${result.htmlFiles} HTML files; changed ${result.changedHtmlFiles}; generated or refreshed ${result.addedOrUpdatedSidecars} compression sidecars.`,
126
+ );
127
+ console.log(
128
+ formatReport(result.report, path.relative(projectRoot, outputDir)),
129
+ );
130
+ return;
131
+ }
132
+ if (command === 'optimize' || command === 'analyze') {
133
+ if (options.positional.length > 1) {
134
+ throw new Error(
135
+ `Usage: ds ${command} [--dir <output>] [--config <file>]${command === 'analyze' ? ' [--json]' : ''}`,
136
+ );
137
+ }
138
+ if (options.positional.length && options.dir) {
139
+ throw new Error(
140
+ 'Pass the output directory either as a positional argument or with --dir, not both.',
141
+ );
142
+ }
143
+ if (command === 'optimize' && options.json) {
144
+ throw new Error('The --json option is supported by ds analyze only.');
145
+ }
146
+ const config = await loadProjectConfig(options.config);
147
+ const outputDir = await getOutputDirectory(config, {
148
+ ...options,
149
+ dir: options.dir ?? options.positional[0],
150
+ });
151
+
152
+ if (command === 'optimize') {
153
+ const result = await optimizeOutput(outputDir, config.optimization);
154
+ console.log(
155
+ `Optimized ${result.htmlFiles} HTML files; changed ${result.changedHtmlFiles}; generated or refreshed ${result.addedOrUpdatedSidecars} compression sidecars.`,
156
+ );
157
+ console.log(
158
+ formatReport(result.report, path.relative(projectRoot, outputDir)),
159
+ );
160
+ } else {
161
+ const report = await analyzeOutput(outputDir);
162
+ console.log(
163
+ options.json
164
+ ? JSON.stringify(report, null, 2)
165
+ : formatReport(report, path.relative(projectRoot, outputDir)),
166
+ );
167
+ }
168
+ return;
169
+ }
170
+
171
+ throw new Error(`Unknown command "${command}".\n\n${help()}`);
172
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,231 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ export const DEFAULT_CONFIG = {
5
+ $schema:
6
+ 'https://raw.githubusercontent.com/ai-all-ai/ds/main/ds.config.schema.json',
7
+ schemaVersion: 1,
8
+ generator: {
9
+ command: ['npm', 'run', 'generate'],
10
+ outputDir: '.output/public',
11
+ },
12
+ optimization: {
13
+ html: { minify: false },
14
+ criticalCss: {
15
+ enabled: false,
16
+ routes: [],
17
+ allowRules: [],
18
+ preload: 'body',
19
+ },
20
+ compression: { gzip: true, brotli: true },
21
+ },
22
+ };
23
+
24
+ function isRecord(value) {
25
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
26
+ }
27
+
28
+ function assertRecord(value, name) {
29
+ if (!isRecord(value)) throw new Error(`${name} must be an object.`);
30
+ }
31
+
32
+ function assertKeys(value, name, allowed) {
33
+ const unexpected = Object.keys(value).find((key) => !allowed.includes(key));
34
+ if (unexpected) throw new Error(`Unknown ${name} option: ${unexpected}`);
35
+ }
36
+
37
+ function assertStringArray(value, name, { allowEmpty = true } = {}) {
38
+ if (!Array.isArray(value) || (!allowEmpty && value.length === 0)) {
39
+ throw new Error(
40
+ `${name} must be ${allowEmpty ? 'an' : 'a non-empty'} array of strings.`,
41
+ );
42
+ }
43
+ if (value.some((item) => typeof item !== 'string' || item.length === 0)) {
44
+ throw new Error(`${name} must contain only non-empty strings.`);
45
+ }
46
+ }
47
+
48
+ export function validateConfig(input) {
49
+ assertRecord(input, 'Configuration');
50
+ assertKeys(input, 'configuration', [
51
+ '$schema',
52
+ 'schemaVersion',
53
+ 'generator',
54
+ 'optimization',
55
+ ]);
56
+ if (input.$schema !== undefined && typeof input.$schema !== 'string') {
57
+ throw new Error('$schema must be a string.');
58
+ }
59
+ if (input.schemaVersion !== 1) {
60
+ throw new Error('Unsupported or missing schemaVersion; expected 1.');
61
+ }
62
+ assertRecord(input.generator, 'generator');
63
+ assertKeys(input.generator, 'generator', ['command', 'outputDir']);
64
+ assertStringArray(input.generator.command, 'generator.command', {
65
+ allowEmpty: false,
66
+ });
67
+ if (
68
+ typeof input.generator.outputDir !== 'string' ||
69
+ !input.generator.outputDir.trim()
70
+ ) {
71
+ throw new Error('generator.outputDir must be a non-empty path.');
72
+ }
73
+
74
+ assertRecord(input.optimization, 'optimization');
75
+ assertKeys(input.optimization, 'optimization', [
76
+ 'html',
77
+ 'criticalCss',
78
+ 'compression',
79
+ ]);
80
+ assertRecord(input.optimization.html, 'optimization.html');
81
+ assertKeys(input.optimization.html, 'optimization.html', ['minify']);
82
+ if (typeof input.optimization.html.minify !== 'boolean') {
83
+ throw new Error('optimization.html.minify must be a boolean.');
84
+ }
85
+
86
+ assertRecord(input.optimization.criticalCss, 'optimization.criticalCss');
87
+ const critical = input.optimization.criticalCss;
88
+ assertKeys(critical, 'optimization.criticalCss', [
89
+ 'enabled',
90
+ 'routes',
91
+ 'allowRules',
92
+ 'preload',
93
+ ]);
94
+ if (typeof critical.enabled !== 'boolean') {
95
+ throw new Error('optimization.criticalCss.enabled must be a boolean.');
96
+ }
97
+ assertStringArray(critical.routes, 'optimization.criticalCss.routes');
98
+ assertStringArray(critical.allowRules, 'optimization.criticalCss.allowRules');
99
+ if (critical.preload !== 'body' && critical.preload !== false) {
100
+ throw new Error(
101
+ 'optimization.criticalCss.preload must be "body" or false.',
102
+ );
103
+ }
104
+ if (critical.enabled && critical.routes.length === 0) {
105
+ throw new Error(
106
+ 'List at least one path in optimization.criticalCss.routes when critical CSS is enabled.',
107
+ );
108
+ }
109
+ for (const route of critical.routes) {
110
+ if (
111
+ route.includes('\\') ||
112
+ path.posix.isAbsolute(route) ||
113
+ route.split('/').some((part) => part === '..') ||
114
+ !route.toLowerCase().endsWith('.html')
115
+ ) {
116
+ throw new Error(
117
+ `Critical CSS route must be a relative .html path without "..": ${route}`,
118
+ );
119
+ }
120
+ }
121
+
122
+ assertRecord(input.optimization.compression, 'optimization.compression');
123
+ assertKeys(input.optimization.compression, 'optimization.compression', [
124
+ 'gzip',
125
+ 'brotli',
126
+ ]);
127
+ for (const algorithm of ['gzip', 'brotli']) {
128
+ if (typeof input.optimization.compression[algorithm] !== 'boolean') {
129
+ throw new Error(
130
+ `optimization.compression.${algorithm} must be a boolean.`,
131
+ );
132
+ }
133
+ }
134
+
135
+ return {
136
+ ...(input.$schema ? { $schema: input.$schema } : {}),
137
+ schemaVersion: 1,
138
+ generator: {
139
+ command: [...input.generator.command],
140
+ outputDir: input.generator.outputDir,
141
+ },
142
+ optimization: {
143
+ html: { minify: input.optimization.html.minify },
144
+ criticalCss: {
145
+ enabled: critical.enabled,
146
+ routes: [...critical.routes],
147
+ allowRules: [...critical.allowRules],
148
+ preload: critical.preload,
149
+ },
150
+ compression: { ...input.optimization.compression },
151
+ },
152
+ };
153
+ }
154
+
155
+ export async function loadConfig(projectRoot, configFile = 'ds.config.json') {
156
+ const configPath = path.resolve(projectRoot, configFile);
157
+ let contents;
158
+ try {
159
+ contents = await fs.readFile(configPath, 'utf8');
160
+ } catch (error) {
161
+ if (error.code === 'ENOENT') {
162
+ throw new Error(
163
+ `Configuration not found: ${configPath}. Run "ds init" first.`,
164
+ );
165
+ }
166
+ throw error;
167
+ }
168
+
169
+ let parsed;
170
+ try {
171
+ parsed = JSON.parse(contents);
172
+ } catch (error) {
173
+ throw new Error(`Invalid JSON in ${configPath}: ${error.message}`);
174
+ }
175
+
176
+ const merged = {
177
+ ...DEFAULT_CONFIG,
178
+ ...parsed,
179
+ generator: { ...DEFAULT_CONFIG.generator, ...parsed?.generator },
180
+ optimization: {
181
+ ...DEFAULT_CONFIG.optimization,
182
+ ...parsed?.optimization,
183
+ html: {
184
+ ...DEFAULT_CONFIG.optimization.html,
185
+ ...parsed?.optimization?.html,
186
+ },
187
+ criticalCss: {
188
+ ...DEFAULT_CONFIG.optimization.criticalCss,
189
+ ...parsed?.optimization?.criticalCss,
190
+ },
191
+ compression: {
192
+ ...DEFAULT_CONFIG.optimization.compression,
193
+ ...parsed?.optimization?.compression,
194
+ },
195
+ },
196
+ };
197
+ return validateConfig(merged);
198
+ }
199
+
200
+ export async function resolveOutputDirectory(projectRoot, outputDir) {
201
+ const root = await fs.realpath(projectRoot);
202
+ const output = path.resolve(root, outputDir);
203
+ const relative = path.relative(root, output);
204
+ if (
205
+ !relative ||
206
+ relative === '..' ||
207
+ relative.startsWith(`..${path.sep}`) ||
208
+ path.isAbsolute(relative)
209
+ ) {
210
+ throw new Error(
211
+ 'The output directory must be a child of the project directory.',
212
+ );
213
+ }
214
+
215
+ const realOutput = await fs.realpath(output);
216
+ const realRelative = path.relative(root, realOutput);
217
+ if (
218
+ !realRelative ||
219
+ realRelative === '..' ||
220
+ realRelative.startsWith(`..${path.sep}`) ||
221
+ path.isAbsolute(realRelative)
222
+ ) {
223
+ throw new Error(
224
+ 'The resolved output directory must remain inside the project directory.',
225
+ );
226
+ }
227
+ const stat = await fs.stat(realOutput);
228
+ if (!stat.isDirectory())
229
+ throw new Error(`Output path is not a directory: ${output}`);
230
+ return realOutput;
231
+ }
package/src/files.mjs ADDED
@@ -0,0 +1,36 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ const COMPRESSIBLE_EXTENSIONS = new Set([
5
+ '.css',
6
+ '.cjs',
7
+ '.html',
8
+ '.htm',
9
+ '.js',
10
+ '.json',
11
+ '.map',
12
+ '.mjs',
13
+ '.svg',
14
+ '.txt',
15
+ '.wasm',
16
+ '.webmanifest',
17
+ '.xml',
18
+ ]);
19
+
20
+ export async function listFiles(root, current = root, files = []) {
21
+ const entries = await fs.readdir(current, { withFileTypes: true });
22
+ for (const entry of entries) {
23
+ const absolute = path.join(current, entry.name);
24
+ if (entry.isDirectory()) await listFiles(root, absolute, files);
25
+ else if (entry.isFile()) files.push(absolute);
26
+ }
27
+ return files;
28
+ }
29
+
30
+ export function isCompressible(file) {
31
+ return COMPRESSIBLE_EXTENSIONS.has(path.extname(file).toLowerCase());
32
+ }
33
+
34
+ export function relativePosix(root, file) {
35
+ return path.relative(root, file).split(path.sep).join('/');
36
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,10 @@
1
+ export {
2
+ DEFAULT_CONFIG,
3
+ loadConfig,
4
+ resolveOutputDirectory,
5
+ validateConfig,
6
+ } from './config.mjs';
7
+ export { runGenerator } from './build.mjs';
8
+ export { optimizeOutput } from './optimize.mjs';
9
+ export { analyzeOutput, formatReport } from './report.mjs';
10
+ export { applyProductionDefaults } from './nuxt-options.mjs';
@@ -0,0 +1,27 @@
1
+ export function applyProductionDefaults(nuxt, options) {
2
+ if (nuxt.options.dev) return;
3
+
4
+ if (options.minify) {
5
+ nuxt.options.vite ??= {};
6
+ nuxt.options.vite.build ??= {};
7
+ if (nuxt.options.vite.build.minify === undefined) {
8
+ nuxt.options.vite.build.minify = true;
9
+ }
10
+ if (nuxt.options.vite.build.cssMinify === undefined) {
11
+ nuxt.options.vite.build.cssMinify = true;
12
+ }
13
+ }
14
+
15
+ if (!options.compression) return;
16
+ nuxt.options.nitro ??= {};
17
+ const compression = nuxt.options.nitro.compressPublicAssets;
18
+ if (compression === undefined) {
19
+ nuxt.options.nitro.compressPublicAssets = {
20
+ gzip: options.compression.gzip,
21
+ brotli: options.compression.brotli,
22
+ };
23
+ } else if (compression && typeof compression === 'object') {
24
+ compression.gzip ??= options.compression.gzip;
25
+ compression.brotli ??= options.compression.brotli;
26
+ }
27
+ }