@textmode/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.
@@ -0,0 +1,109 @@
1
+ export class IdentifierObfuscator {
2
+ constructor(preservedSymbols) {
3
+ this.map = new Map();
4
+ this.uniformCounter = 0;
5
+ this.attributeCounter = 0;
6
+ this.preservedSymbols = new Set(preservedSymbols);
7
+ }
8
+
9
+ seed(names) {
10
+ for (const name of [...new Set(names)].sort()) {
11
+ this.get(name);
12
+ }
13
+ }
14
+
15
+ get(name) {
16
+ if (this.preservedSymbols.has(name)) {
17
+ return name;
18
+ }
19
+
20
+ const existing = this.map.get(name);
21
+ if (existing) {
22
+ return existing;
23
+ }
24
+
25
+ const value = this.nextName(name);
26
+ this.map.set(name, value);
27
+ return value;
28
+ }
29
+
30
+ lookup(name) {
31
+ return this.preservedSymbols.has(name) ? name : this.map.get(name);
32
+ }
33
+
34
+ nextName(originalName) {
35
+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
36
+ const isAttribute = originalName.startsWith('a_');
37
+ const prefix = isAttribute ? 'A' : 'U';
38
+ let counter = isAttribute ? this.attributeCounter++ : this.uniformCounter++;
39
+ let output = '';
40
+
41
+ do {
42
+ output = alphabet[counter % alphabet.length] + output;
43
+ counter = Math.floor(counter / alphabet.length) - 1;
44
+ } while (counter >= 0);
45
+
46
+ return `${prefix}${output}`;
47
+ }
48
+ }
49
+
50
+ function escapeRegExp(value) {
51
+ return value.replace(/[.*+?^${}()|[\]\\]/g, (character) => `\\${character}`);
52
+ }
53
+
54
+ export function replaceIdentifiers(source, mapping) {
55
+ let output = source;
56
+ for (const [from, to] of mapping) {
57
+ output = output.replace(new RegExp(`\\b${escapeRegExp(from)}\\b`, 'g'), to);
58
+ }
59
+ return output;
60
+ }
61
+
62
+ export function findGLSLHostIdentifiers(code) {
63
+ const identifiers = new Set();
64
+ const uniformPattern =
65
+ /\buniform\s+(?:(?:lowp|mediump|highp)\s+)?[A-Za-z0-9_]+(?:\s*\[[^\]]*\])?\s+([A-Za-z_][A-Za-z0-9_]*)/g;
66
+ const attributePattern =
67
+ /\b(?:in|attribute)\s+(?:(?:lowp|mediump|highp)\s+)?[A-Za-z0-9_]+(?:\s*\[[^\]]*\])?\s+([A-Za-z_][A-Za-z0-9_]*)/g;
68
+ let match;
69
+
70
+ while ((match = uniformPattern.exec(code))) {
71
+ if (match[1].startsWith('u_')) {
72
+ identifiers.add(match[1]);
73
+ }
74
+ }
75
+ while ((match = attributePattern.exec(code))) {
76
+ if (match[1].startsWith('a_')) {
77
+ identifiers.add(match[1]);
78
+ }
79
+ }
80
+ return [...identifiers];
81
+ }
82
+
83
+ export function buildIdentifierMapping(code, obfuscator) {
84
+ const identifiers = findGLSLHostIdentifiers(code);
85
+ obfuscator.seed(identifiers);
86
+ return new Map(identifiers.map((name) => [name, obfuscator.get(name)]));
87
+ }
88
+
89
+ export function findGLSLDeclaredSymbols(code) {
90
+ const symbols = new Set();
91
+ const declarationPattern =
92
+ /^[ \t]*(?:layout\s*\([^)]*\)\s*)?(?:uniform|in|out|attribute)\s+(?:(?:lowp|mediump|highp)\s+)?[A-Za-z0-9_]+(?:\s*\[[^\]]*\])?\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*\[[^\]]*\])?/gm;
93
+ const constPattern =
94
+ /^[ \t]*const\s+(?:(?:lowp|mediump|highp)\s+)?[A-Za-z0-9_]+(?:\s*\[[^\]]*\])?\s+([A-Za-z_][A-Za-z0-9_]*)/gm;
95
+ const functionPattern =
96
+ /^[ \t]*(?:void|bool|int|uint|float|double|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/gm;
97
+ let match;
98
+
99
+ while ((match = declarationPattern.exec(code))) {
100
+ symbols.add(match[1]);
101
+ }
102
+ while ((match = constPattern.exec(code))) {
103
+ symbols.add(match[1]);
104
+ }
105
+ while ((match = functionPattern.exec(code))) {
106
+ symbols.add(match[1]);
107
+ }
108
+ return [...symbols];
109
+ }
@@ -0,0 +1,64 @@
1
+ export class IncludeGraph {
2
+ constructor() {
3
+ /** @type {Map<string, Set<string>>} */
4
+ this.includeParents = new Map();
5
+ /** @type {Map<string, Set<string>>} */
6
+ this.parentIncludes = new Map();
7
+ }
8
+
9
+ clear() {
10
+ this.includeParents.clear();
11
+ this.parentIncludes.clear();
12
+ }
13
+
14
+ clearParent(parent) {
15
+ const previousIncludes = this.parentIncludes.get(parent);
16
+ if (!previousIncludes) {
17
+ return;
18
+ }
19
+
20
+ for (const includePath of previousIncludes) {
21
+ const parents = this.includeParents.get(includePath);
22
+ parents?.delete(parent);
23
+ if (parents?.size === 0) {
24
+ this.includeParents.delete(includePath);
25
+ }
26
+ }
27
+ this.parentIncludes.delete(parent);
28
+ }
29
+
30
+ record(parent, child) {
31
+ let children = this.parentIncludes.get(parent);
32
+ if (!children) {
33
+ children = new Set();
34
+ this.parentIncludes.set(parent, children);
35
+ }
36
+ children.add(child);
37
+
38
+ let parents = this.includeParents.get(child);
39
+ if (!parents) {
40
+ parents = new Set();
41
+ this.includeParents.set(child, parents);
42
+ }
43
+ parents.add(parent);
44
+ }
45
+
46
+ hasParent(file) {
47
+ return this.includeParents.has(file);
48
+ }
49
+
50
+ collectParents(file, out) {
51
+ const parents = this.includeParents.get(file);
52
+ if (!parents) {
53
+ return;
54
+ }
55
+
56
+ for (const parent of parents) {
57
+ if (out.has(parent)) {
58
+ continue;
59
+ }
60
+ out.add(parent);
61
+ this.collectParents(parent, out);
62
+ }
63
+ }
64
+ }
@@ -0,0 +1,91 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, resolve } from 'node:path';
3
+
4
+ import { isInsideAnyDirectory, normalizePath } from './paths.js';
5
+
6
+ const shaderIncludePattern = /^[ \t]*#include\s+["']([^"']+)["'][ \t]*(?:\/\/[^\n]*)?\r?\n?/gm;
7
+ const shaderFileExtensionsPattern = /\.(?:glsl|vert|frag)$/;
8
+
9
+ function resolveIncludePath(specifier, importer, includeRoots) {
10
+ const normalizedSpecifier = specifier.replace(/\\/g, '/');
11
+ const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(normalizedSpecifier);
12
+
13
+ if (
14
+ !normalizedSpecifier ||
15
+ isAbsolute(normalizedSpecifier) ||
16
+ hasScheme ||
17
+ normalizedSpecifier.includes('?') ||
18
+ normalizedSpecifier.includes('#')
19
+ ) {
20
+ throw new Error(`[GLSL] Invalid include path "${specifier}" in ${importer}. Includes must be relative files.`);
21
+ }
22
+ if (!shaderFileExtensionsPattern.test(normalizedSpecifier)) {
23
+ throw new Error(`[GLSL] Invalid include path "${specifier}" in ${importer}. Expected .glsl, .vert, or .frag.`);
24
+ }
25
+
26
+ const resolvedPath = normalizePath(resolve(dirname(importer), normalizedSpecifier));
27
+ if (!isInsideAnyDirectory(resolvedPath, includeRoots)) {
28
+ throw new Error(`[GLSL] Include "${specifier}" in ${importer} resolves outside the configured include roots.`);
29
+ }
30
+ return resolvedPath;
31
+ }
32
+
33
+ export async function resolveShaderIncludes(code, id, includeRoots, recordInclude, stack = [normalizePath(id)]) {
34
+ const importer = normalizePath(id);
35
+ const includePattern = new RegExp(shaderIncludePattern);
36
+ /** @type {Array<{ type: 'code', code: string } | { type: 'include', path: string }>} */
37
+ const segments = [];
38
+ /** @type {string[]} */
39
+ const expandedParts = [];
40
+ /** @type {string[]} */
41
+ const includedParts = [];
42
+ const includedFiles = new Set();
43
+ let lastIndex = 0;
44
+ let match;
45
+
46
+ while ((match = includePattern.exec(code))) {
47
+ const codeBeforeInclude = code.slice(lastIndex, match.index);
48
+ if (codeBeforeInclude) {
49
+ segments.push({ type: 'code', code: codeBeforeInclude });
50
+ expandedParts.push(codeBeforeInclude);
51
+ }
52
+
53
+ const includePath = resolveIncludePath(match[1], importer, includeRoots);
54
+ if (stack.includes(includePath)) {
55
+ throw new Error(`[GLSL] Include cycle detected: ${[...stack, includePath].join(' -> ')}`);
56
+ }
57
+
58
+ recordInclude(importer, includePath);
59
+ includedFiles.add(includePath);
60
+
61
+ let includeCode;
62
+ try {
63
+ includeCode = await readFile(includePath, 'utf8');
64
+ } catch {
65
+ throw new Error(`[GLSL] Missing include "${match[1]}" in ${importer}.`);
66
+ }
67
+
68
+ const resolvedInclude = await resolveShaderIncludes(includeCode, includePath, includeRoots, recordInclude, [
69
+ ...stack,
70
+ includePath,
71
+ ]);
72
+ resolvedInclude.includedFiles.forEach((file) => includedFiles.add(file));
73
+ includedParts.push(resolvedInclude.expandedCode, resolvedInclude.includedCode);
74
+ segments.push({ type: 'include', path: includePath });
75
+ expandedParts.push('\n', resolvedInclude.expandedCode, '\n');
76
+ lastIndex = match.index + match[0].length;
77
+ }
78
+
79
+ const codeAfterIncludes = code.slice(lastIndex);
80
+ if (codeAfterIncludes) {
81
+ segments.push({ type: 'code', code: codeAfterIncludes });
82
+ expandedParts.push(codeAfterIncludes);
83
+ }
84
+
85
+ return {
86
+ expandedCode: expandedParts.join(''),
87
+ includedCode: includedParts.join('\n'),
88
+ includedFiles,
89
+ segments,
90
+ };
91
+ }
@@ -0,0 +1,38 @@
1
+ import { toModuleSpecifier } from './paths.js';
2
+ import { createShaderMinifier, minifyShaderSegment, minifyShaderSegmentWithMinifier } from './shader-minifier.js';
3
+
4
+ export async function buildShaderModule(resolvedIncludes, id, mapping, preservedSymbols) {
5
+ const hasIncludes = resolvedIncludes.segments.some((segment) => segment.type === 'include');
6
+ if (!hasIncludes) {
7
+ const output = await minifyShaderSegment(resolvedIncludes.expandedCode, id, mapping, preservedSymbols);
8
+ return `export default ${JSON.stringify(output)};`;
9
+ }
10
+
11
+ const composedMinifier = createShaderMinifier(preservedSymbols);
12
+ /** @type {string[]} */
13
+ const imports = [];
14
+ /** @type {string[]} */
15
+ const expressionParts = [];
16
+ const importNames = new Map();
17
+
18
+ for (const segment of resolvedIncludes.segments) {
19
+ if (segment.type === 'code') {
20
+ const output = await minifyShaderSegmentWithMinifier(segment.code, id, mapping, composedMinifier);
21
+ if (output) {
22
+ expressionParts.push(JSON.stringify(output));
23
+ }
24
+ continue;
25
+ }
26
+
27
+ let importName = importNames.get(segment.path);
28
+ if (!importName) {
29
+ importName = `__tmGlslChunk${importNames.size}`;
30
+ importNames.set(segment.path, importName);
31
+ imports.push(`import ${importName} from ${JSON.stringify(toModuleSpecifier(id, segment.path))};`);
32
+ expressionParts.push(JSON.stringify('\n'), importName, JSON.stringify('\n'));
33
+ }
34
+ }
35
+
36
+ const expression = expressionParts.length > 0 ? expressionParts.join(' + ') : JSON.stringify('');
37
+ return `${imports.join('\n')}\nexport default ${expression};`;
38
+ }
@@ -0,0 +1,45 @@
1
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
2
+
3
+ const shaderFilePattern = /\.(?:glsl|vert|frag)$/;
4
+
5
+ export function normalizePath(id) {
6
+ return id.split('?')[0].replace(/\\/g, '/').replace(/^\0/, '');
7
+ }
8
+
9
+ export function isBareShaderRequest(id) {
10
+ return !id.includes('?') && shaderFilePattern.test(normalizePath(id));
11
+ }
12
+
13
+ export function isInsideDirectory(file, directory) {
14
+ const relativePath = relative(directory, file);
15
+ return relativePath === '' || (!relativePath.startsWith('..') && !isAbsolute(relativePath));
16
+ }
17
+
18
+ export function isInsideAnyDirectory(file, directories) {
19
+ return directories.some((directory) => isInsideDirectory(file, directory));
20
+ }
21
+
22
+ export function resolveConfiguredRoots(projectRoot, values, field) {
23
+ return values.map((value) => {
24
+ if (typeof value !== 'string' || value.trim().length === 0) {
25
+ throw new TypeError(`@textmode/build: ${field} entries must be non-empty strings.`);
26
+ }
27
+ if (isAbsolute(value)) {
28
+ throw new Error(`@textmode/build: ${field} entries must be relative to the Vite root.`);
29
+ }
30
+
31
+ const resolved = resolve(projectRoot, value);
32
+ if (!isInsideDirectory(resolved, projectRoot)) {
33
+ throw new Error(`@textmode/build: ${field} entry "${value}" resolves outside the Vite root.`);
34
+ }
35
+ return resolved;
36
+ });
37
+ }
38
+
39
+ export function toModuleSpecifier(fromFile, targetFile) {
40
+ let specifier = normalizePath(relative(dirname(fromFile), targetFile));
41
+ if (!specifier.startsWith('.')) {
42
+ specifier = `./${specifier}`;
43
+ }
44
+ return specifier;
45
+ }
@@ -0,0 +1,164 @@
1
+ import { readFile } from 'node:fs/promises';
2
+
3
+ import { buildIdentifierMapping, findGLSLDeclaredSymbols, IdentifierObfuscator } from './identifiers.js';
4
+ import { IncludeGraph } from './include-graph.js';
5
+ import { resolveShaderIncludes } from './include-resolver.js';
6
+ import { buildShaderModule } from './module-builder.js';
7
+ import { isBareShaderRequest, isInsideAnyDirectory, normalizePath, resolveConfiguredRoots } from './paths.js';
8
+ import { builtInPreservedSymbols } from './preserved-symbols.js';
9
+ import { indexShaderRoots } from './scanner.js';
10
+ import { rewriteHostIdentifiers } from './host-rewriter.js';
11
+
12
+ const hostFilePattern = /\.(?:ts|tsx|js|jsx)$/;
13
+
14
+ /** @returns {string[]} */
15
+ function requireStringArray(value, field, allowEmpty = false) {
16
+ if (!Array.isArray(value) || (!allowEmpty && value.length === 0)) {
17
+ throw new TypeError(`@textmode/build: ${field} must be a non-empty array.`);
18
+ }
19
+ for (const entry of value) {
20
+ if (typeof entry !== 'string' || entry.trim().length === 0) {
21
+ throw new TypeError(`@textmode/build: ${field} entries must be non-empty strings.`);
22
+ }
23
+ }
24
+ return [...value];
25
+ }
26
+
27
+ /**
28
+ * Create the shared textmode GLSL Vite plugin.
29
+ *
30
+ * @param {import('../../../index.d.ts').TextmodeGlslOptions} options
31
+ * @returns {import('vite').Plugin}
32
+ */
33
+ export function textmodeGlsl(options) {
34
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
35
+ throw new TypeError('@textmode/build: options must be an object.');
36
+ }
37
+
38
+ const shaderRootOptions = requireStringArray(options.shaderRoots, 'shaderRoots');
39
+ const includeRootOptions =
40
+ options.includeRoots === undefined
41
+ ? shaderRootOptions
42
+ : requireStringArray(options.includeRoots, 'includeRoots');
43
+ const publicSymbols =
44
+ options.publicSymbols === undefined ? [] : requireStringArray(options.publicSymbols, 'publicSymbols', true);
45
+ let hostRootOptions = null;
46
+ if (options.hostIdentifiers !== undefined) {
47
+ if (
48
+ !options.hostIdentifiers ||
49
+ typeof options.hostIdentifiers !== 'object' ||
50
+ Array.isArray(options.hostIdentifiers)
51
+ ) {
52
+ throw new TypeError('@textmode/build: hostIdentifiers must be an object.');
53
+ }
54
+ hostRootOptions = requireStringArray(options.hostIdentifiers.sourceRoots, 'hostIdentifiers.sourceRoots');
55
+ }
56
+
57
+ const preservedSymbols = [...new Set([...builtInPreservedSymbols, ...publicSymbols])];
58
+ const obfuscator = new IdentifierObfuscator(preservedSymbols);
59
+ const includeGraph = new IncludeGraph();
60
+ /** @type {string[]} */
61
+ let shaderRoots = [];
62
+ /** @type {string[]} */
63
+ let includeRoots = [];
64
+ /** @type {string[]} */
65
+ let hostRoots = [];
66
+
67
+ return {
68
+ name: 'textmode-glsl',
69
+ enforce: 'pre',
70
+
71
+ configResolved(config) {
72
+ const projectRoot = normalizePath(config.root);
73
+ shaderRoots = resolveConfiguredRoots(projectRoot, shaderRootOptions, 'shaderRoots');
74
+ includeRoots = resolveConfiguredRoots(projectRoot, includeRootOptions, 'includeRoots');
75
+ hostRoots = hostRootOptions
76
+ ? resolveConfiguredRoots(projectRoot, hostRootOptions, 'hostIdentifiers.sourceRoots')
77
+ : [];
78
+ },
79
+
80
+ async buildStart() {
81
+ await indexShaderRoots(
82
+ [...new Set([...shaderRoots, ...includeRoots])],
83
+ includeRoots,
84
+ obfuscator,
85
+ includeGraph,
86
+ (file) => this.addWatchFile(file)
87
+ );
88
+ },
89
+
90
+ async handleHotUpdate(context) {
91
+ const file = normalizePath(context.file);
92
+ if (!isBareShaderRequest(file) || !isInsideAnyDirectory(file, [...shaderRoots, ...includeRoots])) {
93
+ return undefined;
94
+ }
95
+
96
+ const code = await readFile(file, 'utf8');
97
+ includeGraph.clearParent(file);
98
+ const resolved = await resolveShaderIncludes(code, file, includeRoots, (parent, child) =>
99
+ includeGraph.record(parent, child)
100
+ );
101
+ buildIdentifierMapping(resolved.expandedCode, obfuscator);
102
+
103
+ const parents = new Set();
104
+ includeGraph.collectParents(file, parents);
105
+ if (parents.size === 0) {
106
+ return undefined;
107
+ }
108
+
109
+ const modules = [...context.modules];
110
+ for (const parent of parents) {
111
+ const parentModule = context.server.moduleGraph.getModuleById(parent);
112
+ if (parentModule && !modules.includes(parentModule)) {
113
+ modules.push(parentModule);
114
+ }
115
+ }
116
+ return modules;
117
+ },
118
+
119
+ async transform(code, id) {
120
+ if (id.includes('?')) {
121
+ return null;
122
+ }
123
+
124
+ const normalizedId = normalizePath(id);
125
+ const shaderDirectories = [...shaderRoots, ...includeRoots];
126
+ if (isBareShaderRequest(normalizedId) && isInsideAnyDirectory(normalizedId, shaderDirectories)) {
127
+ includeGraph.clearParent(normalizedId);
128
+ const resolvedIncludes = await resolveShaderIncludes(
129
+ code,
130
+ normalizedId,
131
+ includeRoots,
132
+ (parent, child) => includeGraph.record(parent, child)
133
+ );
134
+ resolvedIncludes.includedFiles.forEach((includePath) => this.addWatchFile(includePath));
135
+
136
+ const mapping = buildIdentifierMapping(resolvedIncludes.expandedCode, obfuscator);
137
+ const isSharedInclude = includeGraph.hasParent(normalizedId);
138
+ const boundarySymbols = isSharedInclude
139
+ ? findGLSLDeclaredSymbols(resolvedIncludes.expandedCode)
140
+ : findGLSLDeclaredSymbols(resolvedIncludes.includedCode);
141
+ const segmentPreservedSymbols = [
142
+ ...new Set([...preservedSymbols, ...mapping.values(), ...boundarySymbols]),
143
+ ];
144
+ const moduleCode = await buildShaderModule(
145
+ resolvedIncludes,
146
+ normalizedId,
147
+ mapping,
148
+ segmentPreservedSymbols
149
+ );
150
+ return { code: moduleCode, map: null };
151
+ }
152
+
153
+ if (
154
+ hostRoots.length > 0 &&
155
+ hostFilePattern.test(normalizedId) &&
156
+ isInsideAnyDirectory(normalizedId, hostRoots)
157
+ ) {
158
+ const updated = rewriteHostIdentifiers(code, (name) => obfuscator.lookup(name));
159
+ return updated === code ? null : { code: updated, map: null };
160
+ }
161
+ return null;
162
+ },
163
+ };
164
+ }
@@ -0,0 +1,75 @@
1
+ // GLSL ES/WebGL entrypoints, variables, and functions that the minifier must never rename.
2
+ export const builtInPreservedSymbols = [
3
+ 'gl_Position',
4
+ 'gl_PointSize',
5
+ 'gl_FragCoord',
6
+ 'gl_FrontFacing',
7
+ 'gl_PointCoord',
8
+ 'gl_FragColor',
9
+ 'gl_FragData',
10
+ 'gl_FragDepth',
11
+ 'gl_VertexID',
12
+ 'gl_InstanceID',
13
+ 'main',
14
+ 'texture',
15
+ 'texture2D',
16
+ 'textureCube',
17
+ 'textureSize',
18
+ 'textureProj',
19
+ 'textureLod',
20
+ 'textureOffset',
21
+ 'textureProjOffset',
22
+ 'textureLodOffset',
23
+ 'texelFetch',
24
+ 'texelFetchOffset',
25
+ 'sin',
26
+ 'cos',
27
+ 'tan',
28
+ 'asin',
29
+ 'acos',
30
+ 'atan',
31
+ 'radians',
32
+ 'degrees',
33
+ 'pow',
34
+ 'exp',
35
+ 'log',
36
+ 'exp2',
37
+ 'log2',
38
+ 'sqrt',
39
+ 'inversesqrt',
40
+ 'abs',
41
+ 'sign',
42
+ 'floor',
43
+ 'ceil',
44
+ 'fract',
45
+ 'mod',
46
+ 'min',
47
+ 'max',
48
+ 'clamp',
49
+ 'mix',
50
+ 'step',
51
+ 'smoothstep',
52
+ 'length',
53
+ 'distance',
54
+ 'dot',
55
+ 'cross',
56
+ 'normalize',
57
+ 'faceforward',
58
+ 'reflect',
59
+ 'refract',
60
+ 'matrixCompMult',
61
+ 'transpose',
62
+ 'determinant',
63
+ 'lessThan',
64
+ 'lessThanEqual',
65
+ 'greaterThan',
66
+ 'greaterThanEqual',
67
+ 'equal',
68
+ 'notEqual',
69
+ 'any',
70
+ 'all',
71
+ 'not',
72
+ 'dFdx',
73
+ 'dFdy',
74
+ 'fwidth',
75
+ ];
@@ -0,0 +1,42 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+
4
+ import { findGLSLHostIdentifiers } from './identifiers.js';
5
+ import { resolveShaderIncludes } from './include-resolver.js';
6
+ import { isBareShaderRequest, normalizePath } from './paths.js';
7
+
8
+ async function collectShaderFiles(directory) {
9
+ const entries = await readdir(directory, { withFileTypes: true });
10
+ /** @type {string[]} */
11
+ const files = [];
12
+
13
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
14
+ const entryPath = resolve(directory, entry.name);
15
+ if (entry.isDirectory()) {
16
+ files.push(...(await collectShaderFiles(entryPath)));
17
+ } else if (entry.isFile() && isBareShaderRequest(entryPath)) {
18
+ files.push(normalizePath(entryPath));
19
+ }
20
+ }
21
+ return files;
22
+ }
23
+
24
+ export async function indexShaderRoots(shaderRoots, includeRoots, obfuscator, includeGraph, addWatchFile) {
25
+ const files = [...new Set((await Promise.all(shaderRoots.map(collectShaderFiles))).flat())].sort();
26
+ const identifiers = new Set();
27
+ includeGraph.clear();
28
+
29
+ for (const file of files) {
30
+ const code = await readFile(file, 'utf8');
31
+ findGLSLHostIdentifiers(code).forEach((identifier) => identifiers.add(identifier));
32
+ includeGraph.clearParent(file);
33
+ const resolved = await resolveShaderIncludes(code, file, includeRoots, (parent, child) =>
34
+ includeGraph.record(parent, child)
35
+ );
36
+ addWatchFile(file);
37
+ resolved.includedFiles.forEach(addWatchFile);
38
+ }
39
+
40
+ obfuscator.seed([...identifiers]);
41
+ return files;
42
+ }
@@ -0,0 +1,38 @@
1
+ import { GlslMinify } from '@mapwhit/glsl-minify';
2
+
3
+ import { replaceIdentifiers } from './identifiers.js';
4
+
5
+ export function createShaderMinifier(preservedSymbols) {
6
+ return new GlslMinify({
7
+ nomangle: preservedSymbols,
8
+ preserveDefines: false,
9
+ preserveUniforms: true,
10
+ preserveVariables: false,
11
+ stripVersion: false,
12
+ output: 'object',
13
+ esModule: false,
14
+ });
15
+ }
16
+
17
+ export async function runShaderMinifier(source, id, minifier) {
18
+ if (!source.trim()) {
19
+ return '';
20
+ }
21
+
22
+ try {
23
+ const result = await minifier.execute(source);
24
+ return typeof result?.sourceCode === 'string' ? result.sourceCode : source;
25
+ } catch (error) {
26
+ console.error('[GLSL] Minify failed for', id, error);
27
+ return source;
28
+ }
29
+ }
30
+
31
+ export async function minifyShaderSegment(source, id, mapping, preservedSymbols) {
32
+ const minifier = createShaderMinifier(preservedSymbols);
33
+ return runShaderMinifier(replaceIdentifiers(source, mapping), id, minifier);
34
+ }
35
+
36
+ export async function minifyShaderSegmentWithMinifier(source, id, mapping, minifier) {
37
+ return runShaderMinifier(replaceIdentifiers(source, mapping), id, minifier);
38
+ }