-
Notifications
You must be signed in to change notification settings - Fork 68
/
cram.js
254 lines (204 loc) · 6.56 KB
/
cram.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* wire/cram/builder plugin
* Builder plugin for cram
* https://github.com/cujojs/cram
*
* wire is part of the cujoJS family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*/
(function(define) {
define(function(require) {
var when, unfold, mid, defaultModuleRegex, defaultSpecRegex, replaceIdsRegex,
removeCommentsRx, splitIdsRegex;
when = require('when');
unfold = require('when/unfold');
mid = require('../lib/loader/moduleId');
// default dependency regex
defaultModuleRegex = /\.(module|create)$/;
defaultSpecRegex = /\.(wire\.spec|wire)$/;
// adapted from cram's scan function:
//replaceIdsRegex = /(define)\s*\(\s*(?:\s*["']([^"']*)["']\s*,)?(?:\s*\[([^\]]+)\]\s*,)?\s*(function)?\s*(?:\(([^)]*)\))?/g;
//replaceIdsRegex = /(define)\s*\(\s*(?:\s*["']([^"']*)["']\s*,)?(?:\s*\[([^\]]*)\]\s*,)?/;
replaceIdsRegex = /(\bdefine)\s*\(\s*(?:\s*'([^']*)'|"([^"]*)"\s*,)?(?:\s*\[([^\]]*)\]\s*,)?/;
removeCommentsRx = /\/\*[\s\S]*?\*\//g;
splitIdsRegex = /\s*,\s*/;
return {
normalize: normalize,
compile: compile
};
function normalize(resourceId, toAbsId) {
return resourceId ? toAbsId(resourceId.split("!")[0]) : resourceId;
}
function compile(wireId, resourceId, require, io, config) {
// Track all modules seen in wire spec, so we only include them once
var specIds, defines, seenModules, childSpecRegex,
moduleRegex;
defines = [];
seenModules = {};
moduleRegex = defaultModuleRegex;
childSpecRegex = defaultSpecRegex;
// Get config values
if(config) {
if(config.moduleRegex) moduleRegex = new RegExp(config.moduleRegex);
if(config.childSpecRegex) childSpecRegex = new RegExp(config.childSpecRegex);
}
// Grab the spec module id, *or comma separated list of spec module ids*
// Split in case it's a comma separated list of spec ids
specIds = resourceId.split(splitIdsRegex);
return when.map(specIds, function(specId) {
return processSpec(specId);
}).then(write, io.error);
// For each spec id, add the spec itself as a dependency, and then
// scan the spec contents to find all modules that it needs (e.g.
// "module" and "create")
function processSpec(specId) {
var dependencies, ids;
dependencies = [];
ids = [specId];
_addDep(wireId);
return unfold(fetchNextSpec, endOfList, scanSpec, ids)
.then(function() {
return generateDefine(specId, dependencies);
}
);
function fetchNextSpec() {
var id = ids.shift();
return when.promise(function(resolve, reject) {
require(
[id],
function(spec) { resolve([{ spec: spec, id: id }, ids]); },
reject
);
});
}
function _addDep(moduleId) {
if(!(moduleId in seenModules)) {
dependencies.push(moduleId);
seenModules[moduleId] = moduleId;
}
}
function scanSpec(specDescriptor) {
var spec = specDescriptor.spec;
scanPlugins(spec);
scanObj(spec);
function resolveId(moduleId) {
return mid.resolve(specDescriptor.id, moduleId)
}
function scanObj(obj, path) {
// Scan all keys. This might be the spec itself,
// or any sub-object-literal in the spec.
for (var name in obj) {
scanItem(obj[name], createPath(path, name));
}
}
function scanItem(it, path) {
// Determine the kind of thing we're looking at
// 1. If it's a string, and the key is module or create, then assume it
// is a moduleId, and add it as a dependency.
// 2. If it's an object or an array, scan it recursively
// 3. If it's a wire spec, add it to the list of spec ids
if (isSpec(path) && typeof it === 'string') {
addSpec(it);
} else if (isDep(path) && typeof it === 'string') {
// Get module def
addDep(it);
} else if (isStrictlyObject(it)) {
// Descend into subscope
scanObj(it, path);
} else if (Array.isArray(it)) {
// Descend into array
var arrayPath = path + '[]';
it.forEach(function(arrayItem) {
scanItem(arrayItem, arrayPath);
});
}
}
function scanPlugins(spec) {
var plugins = spec.$plugins || spec.plugins;
if(Array.isArray(plugins)) {
plugins.forEach(addPlugin);
} else if(typeof plugins === 'object') {
Object.keys(plugins).forEach(function(key) {
addPlugin(plugins[key]);
});
}
}
function addPlugin(plugin) {
if(typeof plugin === 'string') {
addDep(plugin);
} else if(typeof plugin === 'object' && plugin.module) {
addDep(plugin.module);
}
}
function addDep(moduleId) {
_addDep(resolveId(moduleId));
}
function addSpec(specId) {
specId = resolveId(specId);
if(!(specId in seenModules)) {
ids.push(specId);
}
_addDep(specId);
}
}
}
function generateDefine(specId, dependencies) {
var dfd, buffer;
dfd = when.defer();
io.read(ensureExtension(specId, 'js'), function(specText) {
buffer = injectIds(specText, specId, dependencies);
defines.push(buffer);
dfd.resolve();
}, dfd.reject);
return dfd.promise;
}
function write() {
// protect against prior code that may have omitted a semi-colon
io.write('\n;' + defines.join('\n'));
}
function isDep(path) {
return moduleRegex.test(path);
}
function isSpec(path) {
return childSpecRegex.test(path);
}
}
function createPath(path, name) {
return path ? (path + '.' + name) : name
}
function isStrictlyObject(it) {
return (it && Object.prototype.toString.call(it) == '[object Object]');
}
function ensureExtension(id, ext) {
return id.lastIndexOf('.') <= id.lastIndexOf('/')
? id + '.' + ext
: id;
}
function injectIds(moduleText, absId, moduleIds) {
var replaced, newText;
// note: replaceIdsRegex removes commas, parens, and brackets
newText = moduleText.replace(removeCommentsRx, '').replace(replaceIdsRegex, function (m, def, mid1, mid2, depIds) {
replaced = true;
// merge deps, but not args since they're not referenced in module
if(depIds) {
moduleIds = depIds.split(splitIdsRegex).concat(moduleIds);
}
moduleIds = '[' + moduleIds.map(quoted).join(', ') + '], ';
return def + '(' + quoted(absId) + ', ' + moduleIds;
});
if (!replaced) {
throw new Error('Unable to parse AMD define() in ' + absId);
}
return newText;
}
function quoted(id) {
return '"' + id + '"';
}
function endOfList(ids) {
return !ids.length;
}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));