Debian Codegraph @

dojox/json/ref.js

raw symbols SCIP
1 define([
2 "dojo/_base/array",
3 "dojo/_base/json",
4 "dojo/_base/kernel",
5 "dojo/_base/lang",
6 "dojo/date/stamp",
7 "dojox"
8 ],
9 function(array, djson, dojo, lang, stamp, dojox){
10
11 lang.getObject("json", true, dojox);
12
13 return dojox.json.ref = {
14 // summary:
15 // Adds advanced JSON {de}serialization capabilities to the base json library.
16 // This enhances the capabilities of dojo.toJson and dojo.fromJson,
17 // adding referencing support, date handling, and other extra format handling.
18 // On parsing, references are resolved. When references are made to
19 // ids/objects that have been loaded yet, the loader function will be set to
20 // _loadObject to denote a lazy loading (not loaded yet) object.
21
22
23 resolveJson: function(/*Object*/ root, /*Object?*/ args){
24 // summary:
25 // Indexes and resolves references in the JSON object.
26 // description:
27 // A JSON Schema object that can be used to advise the handling of the JSON (defining ids, date properties, urls, etc)
28 // root:
29 // The root object of the object graph to be processed
30 // args:
31 // Object with additional arguments:
32 //
33 // - The *index* parameter:
34 // This is the index object (map) to use to store an index of all the objects.
35 // If you are using inter-message referencing, you must provide the same object for each call.
36 // - The *defaultId* parameter:
37 // This is the default id to use for the root object (if it doesn't define it's own id)
38 // - The *idPrefix* parameter:
39 // This the prefix to use for the ids as they enter the index. This allows multiple tables
40 // to use ids (that might otherwise collide) that enter the same global index.
41 // idPrefix should be in the form "/Service/". For example,
42 // if the idPrefix is "/Table/", and object is encountered {id:"4",...}, this would go in the
43 // index as "/Table/4".
44 // - The *idAttribute* parameter:
45 // This indicates what property is the identity property. This defaults to "id"
46 // - The *assignAbsoluteIds* parameter:
47 // This indicates that the resolveJson should assign absolute ids (__id) as the objects are being parsed.
48 // - The *schemas* parameter:
49 // This provides a map of schemas, from which prototypes can be retrieved
50 // - The *loader* parameter:
51 // This is a function that is called added to the reference objects that can't be resolved (lazy objects)
52 // returns:
53 // An object, the result of the processing
54 args = args || {};
55 var idAttribute = args.idAttribute || 'id';
56 var refAttribute = this.refAttribute;
57 var idAsRef = args.idAsRef;
58 var prefix = args.idPrefix || '';
59 var assignAbsoluteIds = args.assignAbsoluteIds;
60 var index = args.index || {}; // create an index if one doesn't exist
61 var timeStamps = args.timeStamps;
62 var ref,reWalk=[];
63 var pathResolveRegex = /^(.*\/)?(\w+:\/\/)|[^\/\.]+\/\.\.\/|^.*\/(\/)/;
64 var addProp = this._addProp;
65 var F = function(){};
66 function walk(it, stop, defaultId, needsPrefix, schema, defaultObject, parent){
67 // this walks the new graph, resolving references and making other changes
68 var i, update, val, id = idAttribute in it ? it[idAttribute] : defaultId;
69 if(idAttribute in it || ((id !== undefined) && needsPrefix)){
70 id = (prefix + id).replace(pathResolveRegex,'$2$3');
71 }
72 var target = defaultObject || it;
73 if(id !== undefined){ // if there is an id available...
74 if(assignAbsoluteIds){
75 it.__id = id;
76 }
77 if(args.schemas && (!(it instanceof Array)) && // won't try on arrays to do prototypes, plus it messes with queries
78 (val = id.match(/^(.+\/)[^\.\[]*$/))){ // if it has a direct table id (no paths)
79 schema = args.schemas[val[1]];
80 }
81 // if the id already exists in the system, we should use the existing object, and just
82 // update it... as long as the object is compatible
83 if(index[id] && ((it instanceof Array) == (index[id] instanceof Array))){
84 target = index[id];
85 delete target.$ref; // remove this artifact
86 delete target._loadObject;
87 update = true;
88 }else{
89 var proto = schema && schema.prototype; // and if has a prototype
90 if(proto){
91 // if the schema defines a prototype, that needs to be the prototype of the object
92 F.prototype = proto;
93 target = new F();
94 }
95 }
96 index[id] = target; // add the prefix, set _id, and index it
97 if(timeStamps){
98 timeStamps[id] = args.time;
99 }
100 }
101 while(schema){
102 var properties = schema.properties;
103 if(properties){
104 for(i in it){
105 var propertyDefinition = properties[i];
106 if(propertyDefinition && propertyDefinition.format == 'date-time' && typeof it[i] == 'string'){
107 it[i] = stamp.fromISOString(it[i]);
108 }
109 }
110 }
111 schema = schema["extends"];
112 }
113 var length = it.length;
114 for(i in it){
115 if(i==length){
116 break;
117 }
118 if(it.hasOwnProperty(i)){
119 val=it[i];
120 if((typeof val =='object') && val && !(val instanceof Date) && i != '__parent'){
121 ref=val[refAttribute] || (idAsRef && val[idAttribute]);
122 if(it != reWalk && (!ref || !val.__parent)){
123 val.__parent = parent ? parent : target;
124 }
125 if(ref){ // a reference was found
126 // make sure it is a safe reference
127 delete it[i];// remove the property so it doesn't resolve to itself in the case of id.propertyName lazy values
128 var path = ref.toString().replace(/(#)([^\.\[])/,'$1.$2').match(/(^([^\[]*\/)?[^#\.\[]*)#?([\.\[].*)?/); // divide along the path
129 if(index[(prefix + ref).replace(pathResolveRegex,'$2$3')]){
130 ref = index[(prefix + ref).replace(pathResolveRegex,'$2$3')];
131 }else if((ref = (path[1]=='$' || path[1]=='this' || path[1]==='') ? root : index[(prefix + path[1]).replace(pathResolveRegex,'$2$3')])){ // a $ indicates to start with the root, otherwise start with an id
132 // if there is a path, we will iterate through the path references
133 if(path[3]){
134 path[3].replace(/(\[([^\]]+)\])|(\.?([^\.\[]+))/g,function(t,a,b,c,d){
135 ref = ref && ref[b ? b.replace(/[\"\'\\]/,'') : d];
136 });
137 }
138 }
139 if(ref){
140 val = ref;
141 }else{
142 // otherwise, no starting point was found (id not found), if stop is set, it does not exist, we have
143 // unloaded reference, if stop is not set, it may be in a part of the graph not walked yet,
144 // we will wait for the second loop
145 if(!stop){
146 var rewalking;
147 if(!rewalking){
148 reWalk.push(target); // we need to rewalk it to resolve references
149 }
150 rewalking = true; // we only want to add it once
151 // TODO: What is propertyDefinition supposed to be here?
152 val = walk(val, false, val[refAttribute], true, propertyDefinition);
153 // create a lazy loaded object
154 val._loadObject = args.loader;
155 }
156 }
157 }else{
158 if(!stop){ // if we are in stop, that means we are in the second loop, and we only need to check this current one,
159 // further walking may lead down circular loops
160 val = walk(
161 val,
162 reWalk==it,
163 id === undefined ? undefined : addProp(id, i), // the default id to use
164 false,
165 // TODO: What is propertyDefinition supposed to be here?
166 propertyDefinition,
167 // if we have an existing object child, we want to
168 // maintain it's identity, so we pass it as the default object
169 target != it && typeof target[i] == 'object' && target[i],
170 it
171 );
172 }
173 }
174 }
175 it[i] = val;
176 if(target!=it && !target.__isDirty){// do updates if we are updating an existing object and it's not dirty
177 var old = target[i];
178 target[i] = val; // only update if it changed
179 if(update && val !== old && // see if it is different
180 !target._loadObject && // no updates if we are just lazy loading
181 !(i.charAt(0) == '_' && i.charAt(1) == '_') && i != "$ref" &&
182 !(val instanceof Date && old instanceof Date && val.getTime() == old.getTime()) && // make sure it isn't an identical date
183 !(typeof val == 'function' && typeof old == 'function' && val.toString() == old.toString()) && // make sure it isn't an indentical function
184 index.onUpdate){
185 index.onUpdate(target,i,old,val); // call the listener for each update
186 }
187 }
188 }
189 }
190
191 if(update && (idAttribute in it || target instanceof Array)){
192 // this means we are updating with a full representation of the object, we need to remove deleted
193 for(i in target){
194 if(!target.__isDirty && target.hasOwnProperty(i) && !it.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && !(target instanceof Array && isNaN(i))){
195 if(index.onUpdate && i != "_loadObject" && i != "_idAttr"){
196 index.onUpdate(target,i,target[i],undefined); // call the listener for each update
197 }
198 delete target[i];
199 while(target instanceof Array && target.length && target[target.length-1] === undefined){
200 // shorten the target if necessary
201 target.length--;
202 }
203 }
204 }
205 }else{
206 if(index.onLoad){
207 index.onLoad(target);
208 }
209 }
210 return target;
211 }
212 if(root && typeof root == 'object'){
213 root = walk(root,false,args.defaultId, true); // do the main walk through
214 walk(reWalk,false); // re walk any parts that were not able to resolve references on the first round
215 }
216 return root;
217 },
218
219
220 fromJson: function(/*String*/ str,/*Object?*/ args){
221 // summary:
222 // evaluates the passed string-form of a JSON object.
223 // str:
224 // a string literal of a JSON item, for instance:
225 // | '{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
226 // args:
227 // See resolveJson
228 // returns:
229 // An object, the result of the evaluation
230 function ref(target){ // support call styles references as well
231 var refObject = {};
232 refObject[this.refAttribute] = target;
233 return refObject;
234 }
235 var root;
236 try{
237 root = eval('(' + str + ')'); // do the eval
238 }catch(e){
239 throw new SyntaxError("Invalid JSON string: " + e.message + " parsing: "+ str);
240 }
241 if(root){
242 return this.resolveJson(root, args);
243 }
244 return root;
245 },
246
247 toJson: function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*Object?*/ idPrefix, /*Object?*/ indexSubObjects, /*String*/idAttribute){
248 // summary:
249 // Create a JSON serialization of an object.
250 // This has support for referencing, including circular references, duplicate references, and out-of-message references
251 // id and path-based referencing is supported as well and is based on http://www.json.com/2007/10/19/json-referencing-proposal-and-library/.
252 // it:
253 // an object to be serialized.
254 // prettyPrint:
255 // if true, we indent objects and arrays to make the output prettier.
256 // The variable dojo.toJsonIndentStr is used as the indent string
257 // -- to use something other than the default (tab),
258 // change that variable before calling dojo.toJson().
259 // idPrefix:
260 // The prefix that has been used for the absolute ids
261 // returns:
262 // a String representing the serialized version of the passed object.
263 var useRefs = this._useRefs;
264 var addProp = this._addProp;
265 var refAttribute = this.refAttribute;
266 idPrefix = idPrefix || ''; // the id prefix for this context
267 var paths={};
268 var generated = {};
269 var idAttributeProvided = idAttribute ? true: false;
270 var uniqueIdCount = 1;
271 function getUniqueId() {
272 var str = (uniqueIdCount++).toString();
273 if (generated.hasOwnProperty(str)) {
274 return getUniqueId();
275 }
276 return str;
277 }
278 function serialize(it,path,_indentStr){
279 if(typeof it == 'object' && it){
280 var value;
281 if(it instanceof Date){ // properly serialize dates
282 return '"' + stamp.toISOString(it,{zulu:true}) + '"';
283 }
284 var id = it.__id;
285 if(id){ // we found an identifiable object, we will just serialize a reference to it... unless it is the root
286 if(path != '#' && ((useRefs && !id.match(/#/)) || paths[id])){
287 var ref = id;
288 if(id.charAt(0)!='#'){
289 if(it.__clientId == id){
290 ref = "cid:" + id;
291 }else if(id.substring(0, idPrefix.length) == idPrefix){ // see if the reference is in the current context
292 // a reference with a prefix matching the current context, the prefix should be removed
293 ref = id.substring(idPrefix.length);
294 }else{
295 // a reference to a different context, assume relative url based referencing
296 ref = id;
297 }
298 }
299 var refObject = {};
300 refObject[refAttribute] = ref;
301 return djson.toJson(refObject, prettyPrint);
302 }
303 path = id;
304 }else{
305 if (idAttributeProvided) {
306 if(!(it instanceof Array)){
307 path = getUniqueId();
308 it.__id = path; // we will create path ids for other objects in case they are circular
309 generated[path] = it;
310 }
311 } else {
312 it.__id = path; // we will create path ids for other objects in case they are circular
313 generated[path] = it;
314 }
315 }
316 paths[path] = it;// save it here so they can be deleted at the end
317 _indentStr = _indentStr || "";
318 var nextIndent = prettyPrint ? _indentStr + djson.toJsonIndentStr : "";
319 var newLine = prettyPrint ? "\n" : "";
320 var sep = prettyPrint ? " " : "";
321
322 if(it instanceof Array){
323 var res = array.map(it, function(obj,i){
324 var val = serialize(obj, idAttributeProvided ? undefined : addProp(path, i), nextIndent);
325 if(typeof val != "string"){
326 val = "undefined";
327 }
328 return newLine + nextIndent + val;
329 });
330 return "[" + res.join("," + sep) + newLine + _indentStr + "]";
331 }
332
333 var output = [];
334 if (idAttributeProvided && (typeof it[idAttribute] === 'undefined')) {
335 output.push(newLine + nextIndent + djson._escapeString(idAttribute) + ":" + sep + djson.toJson(it.__id));
336 }
337 for(var i in it){
338 if(it.hasOwnProperty(i)){
339 var keyStr;
340 if(typeof i == "number"){
341 keyStr = '"' + i + '"';
342 }else if(typeof i == "string" && (i.charAt(0) != '_' || i.charAt(1) != '_')){
343 // we don't serialize our internal properties __id and __clientId
344 keyStr = djson._escapeString(i);
345 }else{
346 // skip non-string or number keys
347 continue;
348 }
349 var val = serialize(it[i],idAttributeProvided ? undefined : addProp(path, i),nextIndent);
350 if(typeof val != "string"){
351 // skip non-serializable values
352 continue;
353 }
354 output.push(newLine + nextIndent + keyStr + ":" + sep + val);
355 }
356 }
357 return "{" + output.join("," + sep) + newLine + _indentStr + "}";
358 }else if(typeof it == "function" && dojox.json.ref.serializeFunctions){
359 return it.toString();
360 }
361
362 return djson.toJson(it); // use the default serializer for primitives
363 }
364 var json = serialize(it,idAttributeProvided ? undefined : '#','');
365 if(!indexSubObjects){
366 for(var i in generated) {// cleanup the temporary path-generated ids
367 delete generated[i].__id;
368 }
369 }
370 return json;
371 },
372 _addProp: function(id, prop){
373 return id + (id.match(/#/) ? id.length == 1 ? '' : '.' : '#') + prop;
374 },
375 // refAttribute: String
376 // This indicates what property is the reference property. This acts like the idAttribute
377 // except that this is used to indicate the current object is a reference or only partially
378 // loaded. This defaults to "$ref".
379 refAttribute: "$ref",
380 _useRefs: false,
381 serializeFunctions: false
382 };
383 });