forked from supermedium/aframe-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
204 lines (175 loc) · 6.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env node
const bodyParser = require('body-parser');
const Confirm = require('prompt-confirm');
const cors = require('cors');
const express = require('express');
const fs = require('fs');
const glob = require('glob');
let files;
const app = express()
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello!');
});
app.post('/save', (req, res) => {
const changes = req.body;
// Prompt to confirm.
console.log([
`\nA-Frame Inspector from ${req.hostname} has requested the following changes:\n`,
`${prettyPrintChanges(changes)}`,
'Do you allow the A-Frame Inspector Watcher to write these updates directly ' +
'within this directory?'
].join('\n'));
const prompt = new Confirm('Y/n');
prompt.run().then(answer => {
// Denied.
if (!answer) { res.sendStatus(403); }
// Accepted.
sync(changes);
res.sendStatus(200);
});
});
function prettyPrintChanges (changes) {
let output = '';
Object.keys(changes).forEach(id => {
output += `#${id}:\n`;
Object.keys(changes[id]).forEach(component => {
if (typeof changes[id][component] === 'object') {
output += ` ${component}:\n`;
Object.keys(changes[id][component]).forEach(property => {
output += ` ${property}: ${changes[id][component][property]}\n`;
});
} else {
output += ` ${component}: ${JSON.stringify(changes[id][component])}\n`;
}
});
output += '\n';
});
return output;
}
function sync (changes) {
files.forEach(file => {
const contents = updateFile(file, fs.readFileSync(file, 'utf-8'), changes);
fs.writeFileSync(file, contents);
});
console.log('Sync complete.');
}
/**
* Given changes, scan for IDs, and write to HTML file.
*/
function updateFile (file, content, changes) {
// Matches any character including line breaks.
const element = '(<a-[\\w]+)';
const filler = '([^]*?)';
const whitespace = '[\\s\\n]';
const propertyDelimit = '["\\s;\]';
Object.keys(changes).forEach(id => {
// Scan for ID in file.
const regex = new RegExp(`${element}${filler}(${whitespace})id="${id}"${filler}>`);
const match = regex.exec(content);
if (!match) { return; }
// Might match unwanted parent entities, filter out.
const entitySplit = match[0].split('<a-');
let entityString = '<a-' + entitySplit[entitySplit.length - 1];
const originalEntityString = entityString;
// Post-process regex to get only last occurence.
const idWhitespaceMatch = match[3];
// Scan for components within entity.
Object.keys(changes[id]).forEach(attribute => {
// Check if component is defined already.
const attributeRegex = new RegExp(`(${whitespace})${attribute}="(.*?)(;?)"`);
const attributeMatch = attributeRegex.exec(entityString);
const value = changes[id][attribute];
if (typeof value === 'string') {
// Single-property attribute match (e.g., position, rotation, scale).
if (attributeMatch) {
const whitespaceMatch = attributeMatch[1];
// Modify.
entityString = entityString.replace(
new RegExp(`${whitespaceMatch}${attribute}=".*?"`),
`${whitespaceMatch}${attribute}="${value}"`
);
} else {
// Add.
entityString = entityString.replace(
new RegExp(`${idWhitespaceMatch}id="${id}"`),
`${idWhitespaceMatch}id="${id}" ${attribute}="${value}"`
);
}
} else {
// Multi-property attribute match (e.g., material).
Object.keys(value).forEach(property => {
const attributeMatch = attributeRegex.exec(entityString);
const propertyValue = value[property];
if (attributeMatch) {
// Modify attribute.
let attributeString = attributeMatch[0];
const whitespaceMatch = attributeMatch[1];
const propertyRegex = new RegExp(`(${propertyDelimit})${property}:(.*?)([";])`);
propertyMatch = propertyRegex.exec(attributeMatch);
if (propertyMatch) {
// Modify property.
const propertyDelimitMatch = propertyMatch[1];
attributeString = attributeString.replace(
new RegExp(`${propertyDelimitMatch}${property}:(.*?)([";])`),
`${propertyDelimitMatch}${property}: ${propertyValue}${propertyMatch[3]}`
);
} else {
// Add property to existing.
attributeString = attributeString.replace(
new RegExp(`${whitespaceMatch}${attribute}="(.*?)(;?)"`),
`${whitespaceMatch}${attribute}="${attributeMatch[2]}${attributeMatch[3]}; ${property}: ${propertyValue}"`
);
}
// Update entity string with updated component.
entityString = entityString.replace(attributeMatch[0], attributeString);
} else {
// Add component entirely.
entityString = entityString.replace(
new RegExp(`${idWhitespaceMatch}id="${id}"`),
`${idWhitespaceMatch}id="${id}" ${attribute}="${property}: ${propertyValue}"`
);
}
});
}
console.log(`Updated ${attribute} of #${id} in ${file}.`);
});
// Splice in updated entity string into file content.
content = content.replace(originalEntityString, entityString);
});
return content;
}
module.exports.updateFile = updateFile;
/**
* What files to edit, can be passed in as glob string.
*/
function getWorkingFiles () {
let files = [];
if (process.argv.length <= 2) {
return glob.sync('**/*.html');
}
process.argv.forEach(function (val, index, array) {
if (index < 2) { return; }
if (fs.lstatSync(val).isDirectory()) {
if (!val.endsWith('/')) { val += '/'; }
val += '**/*.html';
}
files = files.concat(glob.sync(val));
});
return files;
}
if (process.env.NODE_ENV !== 'test') {
const PORT = process.env.PORT || 51234;
app.listen(PORT, () => {
console.log(`Watching for messages from Inspector on localhost:${PORT}.`);
});
files = getWorkingFiles();
console.log('Found HTML files:', files);
if (!files.length) {
throw new Error(
'No HTML files found. ' +
'Try passing a directory or wildcard pointing to HTML files (e.g., **/*.html).');
}
}