Initial commit
[yaffs-website] / node_modules / node-sass / src / binding.cpp
1 #include <nan.h>
2 #include <vector>
3 #include "sass_context_wrapper.h"
4 #include "custom_function_bridge.h"
5 #include "create_string.h"
6 #include "sass_types/factory.h"
7
8 Sass_Import_List sass_importer(const char* cur_path, Sass_Importer_Entry cb, struct Sass_Compiler* comp)
9 {
10   void* cookie = sass_importer_get_cookie(cb);
11   struct Sass_Import* previous = sass_compiler_get_last_import(comp);
12   const char* prev_path = sass_import_get_abs_path(previous);
13   CustomImporterBridge& bridge = *(static_cast<CustomImporterBridge*>(cookie));
14
15   std::vector<void*> argv;
16   argv.push_back((void*)cur_path);
17   argv.push_back((void*)prev_path);
18
19   return bridge(argv);
20 }
21
22 union Sass_Value* sass_custom_function(const union Sass_Value* s_args, Sass_Function_Entry cb, struct Sass_Compiler* comp)
23 {
24   void* cookie = sass_function_get_cookie(cb);
25   CustomFunctionBridge& bridge = *(static_cast<CustomFunctionBridge*>(cookie));
26
27   std::vector<void*> argv;
28   for (unsigned l = sass_list_get_length(s_args), i = 0; i < l; i++) {
29     argv.push_back((void*)sass_list_get_value(s_args, i));
30   }
31
32   return bridge(argv);
33 }
34
35 int ExtractOptions(v8::Local<v8::Object> options, void* cptr, sass_context_wrapper* ctx_w, bool is_file, bool is_sync) {
36   Nan::HandleScope scope;
37
38   struct Sass_Context* ctx;
39
40   v8::Local<v8::Value> result_ = Nan::Get(
41     options,
42     Nan::New("result").ToLocalChecked()
43   ).ToLocalChecked();
44   if (!result_->IsObject()) {
45     Nan::ThrowTypeError("\"result\" element is not an object");
46     return -1;
47   }
48
49   ctx_w->result.Reset(result_.As<v8::Object>());
50
51   if (is_file) {
52     ctx_w->fctx = (struct Sass_File_Context*) cptr;
53     ctx = sass_file_context_get_context(ctx_w->fctx);
54   }
55   else {
56     ctx_w->dctx = (struct Sass_Data_Context*) cptr;
57     ctx = sass_data_context_get_context(ctx_w->dctx);
58   }
59
60   struct Sass_Options* sass_options = sass_context_get_options(ctx);
61
62   ctx_w->is_sync = is_sync;
63
64   if (!is_sync) {
65     ctx_w->request.data = ctx_w;
66
67     // async (callback) style
68     v8::Local<v8::Function> success_callback = v8::Local<v8::Function>::Cast(Nan::Get(options, Nan::New("success").ToLocalChecked()).ToLocalChecked());
69     v8::Local<v8::Function> error_callback = v8::Local<v8::Function>::Cast(Nan::Get(options, Nan::New("error").ToLocalChecked()).ToLocalChecked());
70
71     ctx_w->success_callback = new Nan::Callback(success_callback);
72     ctx_w->error_callback = new Nan::Callback(error_callback);
73   }
74
75   if (!is_file) {
76     ctx_w->file = create_string(Nan::Get(options, Nan::New("file").ToLocalChecked()));
77     sass_option_set_input_path(sass_options, ctx_w->file);
78   }
79
80   int indent_len = Nan::To<int32_t>(
81     Nan::Get(
82         options,
83         Nan::New("indentWidth").ToLocalChecked()
84     ).ToLocalChecked()).FromJust();
85
86   ctx_w->indent = (char*)malloc(indent_len + 1);
87
88   strcpy(ctx_w->indent, std::string(
89     indent_len,
90     Nan::To<int32_t>(
91         Nan::Get(
92             options,
93             Nan::New("indentType").ToLocalChecked()
94         ).ToLocalChecked()).FromJust() == 1 ? '\t' : ' '
95     ).c_str());
96
97   ctx_w->linefeed = create_string(Nan::Get(options, Nan::New("linefeed").ToLocalChecked()));
98   ctx_w->include_path = create_string(Nan::Get(options, Nan::New("includePaths").ToLocalChecked()));
99   ctx_w->out_file = create_string(Nan::Get(options, Nan::New("outFile").ToLocalChecked()));
100   ctx_w->source_map = create_string(Nan::Get(options, Nan::New("sourceMap").ToLocalChecked()));
101   ctx_w->source_map_root = create_string(Nan::Get(options, Nan::New("sourceMapRoot").ToLocalChecked()));
102
103   sass_option_set_output_path(sass_options, ctx_w->out_file);
104   sass_option_set_output_style(sass_options, (Sass_Output_Style)Nan::To<int32_t>(Nan::Get(options, Nan::New("style").ToLocalChecked()).ToLocalChecked()).FromJust());
105   sass_option_set_is_indented_syntax_src(sass_options, Nan::To<bool>(Nan::Get(options, Nan::New("indentedSyntax").ToLocalChecked()).ToLocalChecked()).FromJust());
106   sass_option_set_source_comments(sass_options, Nan::To<bool>(Nan::Get(options, Nan::New("sourceComments").ToLocalChecked()).ToLocalChecked()).FromJust());
107   sass_option_set_omit_source_map_url(sass_options, Nan::To<bool>(Nan::Get(options, Nan::New("omitSourceMapUrl").ToLocalChecked()).ToLocalChecked()).FromJust());
108   sass_option_set_source_map_embed(sass_options, Nan::To<bool>(Nan::Get(options, Nan::New("sourceMapEmbed").ToLocalChecked()).ToLocalChecked()).FromJust());
109   sass_option_set_source_map_contents(sass_options, Nan::To<bool>(Nan::Get(options, Nan::New("sourceMapContents").ToLocalChecked()).ToLocalChecked()).FromJust());
110   sass_option_set_source_map_file(sass_options, ctx_w->source_map);
111   sass_option_set_source_map_root(sass_options, ctx_w->source_map_root);
112   sass_option_set_include_path(sass_options, ctx_w->include_path);
113   sass_option_set_precision(sass_options, Nan::To<int32_t>(Nan::Get(options, Nan::New("precision").ToLocalChecked()).ToLocalChecked()).FromJust());
114   sass_option_set_indent(sass_options, ctx_w->indent);
115   sass_option_set_linefeed(sass_options, ctx_w->linefeed);
116
117   v8::Local<v8::Value> importer_callback = Nan::Get(options, Nan::New("importer").ToLocalChecked()).ToLocalChecked();
118
119   if (importer_callback->IsFunction()) {
120     v8::Local<v8::Function> importer = importer_callback.As<v8::Function>();
121
122     CustomImporterBridge *bridge = new CustomImporterBridge(importer, ctx_w->is_sync);
123     ctx_w->importer_bridges.push_back(bridge);
124
125     Sass_Importer_List c_importers = sass_make_importer_list(1);
126     c_importers[0] = sass_make_importer(sass_importer, 0, bridge);
127
128     sass_option_set_c_importers(sass_options, c_importers);
129   }
130   else if (importer_callback->IsArray()) {
131     v8::Local<v8::Array> importers = importer_callback.As<v8::Array>();
132     Sass_Importer_List c_importers = sass_make_importer_list(importers->Length());
133
134     for (size_t i = 0; i < importers->Length(); ++i) {
135       v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(Nan::Get(importers, static_cast<uint32_t>(i)).ToLocalChecked());
136
137       CustomImporterBridge *bridge = new CustomImporterBridge(callback, ctx_w->is_sync);
138       ctx_w->importer_bridges.push_back(bridge);
139
140       c_importers[i] = sass_make_importer(sass_importer, importers->Length() - i - 1, bridge);
141     }
142
143     sass_option_set_c_importers(sass_options, c_importers);
144   }
145
146   v8::Local<v8::Value> custom_functions = Nan::Get(options, Nan::New("functions").ToLocalChecked()).ToLocalChecked();
147
148   if (custom_functions->IsObject()) {
149     v8::Local<v8::Object> functions = custom_functions.As<v8::Object>();
150     v8::Local<v8::Array> signatures = Nan::GetOwnPropertyNames(functions).ToLocalChecked();
151     unsigned num_signatures = signatures->Length();
152     Sass_Function_List fn_list = sass_make_function_list(num_signatures);
153
154     for (unsigned i = 0; i < num_signatures; i++) {
155       v8::Local<v8::String> signature = v8::Local<v8::String>::Cast(Nan::Get(signatures, Nan::New(i)).ToLocalChecked());
156       v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(Nan::Get(functions, signature).ToLocalChecked());
157
158       CustomFunctionBridge *bridge = new CustomFunctionBridge(callback, ctx_w->is_sync);
159       ctx_w->function_bridges.push_back(bridge);
160
161       Sass_Function_Entry fn = sass_make_function(create_string(signature), sass_custom_function, bridge);
162       sass_function_set_list_entry(fn_list, i, fn);
163     }
164
165     sass_option_set_c_functions(sass_options, fn_list);
166   }
167   return 0;
168 }
169
170 void GetStats(sass_context_wrapper* ctx_w, Sass_Context* ctx) {
171   Nan::HandleScope scope;
172
173   char** included_files = sass_context_get_included_files(ctx);
174   v8::Local<v8::Array> arr = Nan::New<v8::Array>();
175
176   if (included_files) {
177     for (int i = 0; included_files[i] != nullptr; ++i) {
178       Nan::Set(arr, i, Nan::New<v8::String>(included_files[i]).ToLocalChecked());
179     }
180   }
181
182   v8::Local<v8::Object> result = Nan::New(ctx_w->result);
183   assert(result->IsObject());
184
185   v8::Local<v8::Value> stats = Nan::Get(
186     result,
187     Nan::New("stats").ToLocalChecked()
188   ).ToLocalChecked();
189   if (stats->IsObject()) {
190     Nan::Set(
191       stats.As<v8::Object>(),
192       Nan::New("includedFiles").ToLocalChecked(),
193       arr
194     );
195   } else {
196     Nan::ThrowTypeError("\"result.stats\" element is not an object");
197   }
198 }
199
200 int GetResult(sass_context_wrapper* ctx_w, Sass_Context* ctx, bool is_sync = false) {
201   Nan::HandleScope scope;
202   v8::Local<v8::Object> result;
203
204   int status = sass_context_get_error_status(ctx);
205
206   result = Nan::New(ctx_w->result);
207   assert(result->IsObject());
208
209   if (status == 0) {
210     const char* css = sass_context_get_output_string(ctx);
211     const char* map = sass_context_get_source_map_string(ctx);
212
213     Nan::Set(result, Nan::New("css").ToLocalChecked(), Nan::CopyBuffer(css, static_cast<uint32_t>(strlen(css))).ToLocalChecked());
214
215     GetStats(ctx_w, ctx);
216
217     if (map) {
218       Nan::Set(result, Nan::New("map").ToLocalChecked(), Nan::CopyBuffer(map, static_cast<uint32_t>(strlen(map))).ToLocalChecked());
219     }
220   }
221   else if (is_sync) {
222     Nan::Set(result, Nan::New("error").ToLocalChecked(), Nan::New<v8::String>(sass_context_get_error_json(ctx)).ToLocalChecked());
223   }
224
225   return status;
226 }
227
228 void MakeCallback(uv_work_t* req) {
229   Nan::HandleScope scope;
230
231   Nan::TryCatch try_catch;
232   sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
233   struct Sass_Context* ctx;
234
235   if (ctx_w->dctx) {
236     ctx = sass_data_context_get_context(ctx_w->dctx);
237   }
238   else {
239     ctx = sass_file_context_get_context(ctx_w->fctx);
240   }
241
242   int status = GetResult(ctx_w, ctx);
243
244   if (status == 0 && ctx_w->success_callback) {
245     // if no error, do callback(null, result)
246     ctx_w->success_callback->Call(0, 0);
247   }
248   else if (ctx_w->error_callback) {
249     // if error, do callback(error)
250     const char* err = sass_context_get_error_json(ctx);
251     v8::Local<v8::Value> argv[] = {
252       Nan::New<v8::String>(err).ToLocalChecked()
253     };
254     ctx_w->error_callback->Call(1, argv);
255   }
256   if (try_catch.HasCaught()) {
257     Nan::FatalException(try_catch);
258   }
259
260   sass_free_context_wrapper(ctx_w);
261 }
262
263 NAN_METHOD(render) {
264
265   v8::Local<v8::Object> options = Nan::To<v8::Object>(info[0]).ToLocalChecked();
266   char* source_string = create_string(Nan::Get(options, Nan::New("data").ToLocalChecked()));
267   struct Sass_Data_Context* dctx = sass_make_data_context(source_string);
268   sass_context_wrapper* ctx_w = sass_make_context_wrapper();
269
270   if (ExtractOptions(options, dctx, ctx_w, false, false) >= 0) { 
271
272     int status = uv_queue_work(uv_default_loop(), &ctx_w->request, compile_it, (uv_after_work_cb)MakeCallback);
273
274     assert(status == 0);
275   }
276 }
277
278 NAN_METHOD(render_sync) {
279
280   v8::Local<v8::Object> options = Nan::To<v8::Object>(info[0]).ToLocalChecked();
281   char* source_string = create_string(Nan::Get(options, Nan::New("data").ToLocalChecked()));
282   struct Sass_Data_Context* dctx = sass_make_data_context(source_string);
283   struct Sass_Context* ctx = sass_data_context_get_context(dctx);
284   sass_context_wrapper* ctx_w = sass_make_context_wrapper();
285   int result = -1;
286
287   if ((result = ExtractOptions(options, dctx, ctx_w, false, true)) >= 0) {
288     compile_data(dctx);
289     result = GetResult(ctx_w, ctx, true);
290   }
291
292   sass_free_context_wrapper(ctx_w);
293   info.GetReturnValue().Set(result == 0);
294 }
295
296 NAN_METHOD(render_file) {
297
298   v8::Local<v8::Object> options = Nan::To<v8::Object>(info[0]).ToLocalChecked();
299   char* input_path = create_string(Nan::Get(options, Nan::New("file").ToLocalChecked()));
300   struct Sass_File_Context* fctx = sass_make_file_context(input_path);
301   sass_context_wrapper* ctx_w = sass_make_context_wrapper();
302
303   if (ExtractOptions(options, fctx, ctx_w, true, false) >= 0) {
304
305     int status = uv_queue_work(uv_default_loop(), &ctx_w->request, compile_it, (uv_after_work_cb)MakeCallback);
306     assert(status == 0);
307   }
308 }
309
310 NAN_METHOD(render_file_sync) {
311
312   v8::Local<v8::Object> options = Nan::To<v8::Object>(info[0]).ToLocalChecked();
313   char* input_path = create_string(Nan::Get(options, Nan::New("file").ToLocalChecked()));
314   struct Sass_File_Context* fctx = sass_make_file_context(input_path);
315   struct Sass_Context* ctx = sass_file_context_get_context(fctx);
316   sass_context_wrapper* ctx_w = sass_make_context_wrapper();
317   int result = -1;
318
319   if ((result = ExtractOptions(options, fctx, ctx_w, true, true)) >= 0) {
320     compile_file(fctx);
321     result = GetResult(ctx_w, ctx, true);
322   };
323
324   free(input_path);
325   sass_free_context_wrapper(ctx_w);
326
327   info.GetReturnValue().Set(result == 0);
328 }
329
330 NAN_METHOD(libsass_version) {
331   info.GetReturnValue().Set(Nan::New<v8::String>(libsass_version()).ToLocalChecked());
332 }
333
334 NAN_MODULE_INIT(RegisterModule) {
335   Nan::SetMethod(target, "render", render);
336   Nan::SetMethod(target, "renderSync", render_sync);
337   Nan::SetMethod(target, "renderFile", render_file);
338   Nan::SetMethod(target, "renderFileSync", render_file_sync);
339   Nan::SetMethod(target, "libsassVersion", libsass_version);
340   SassTypes::Factory::initExports(target);
341 }
342
343 NODE_MODULE(binding, RegisterModule);