Class: Quickjs::VM

Inherits:
Object
  • Object
show all
Defined in:
ext/quickjsrb/quickjsrb.c

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Object



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
# File 'ext/quickjsrb/quickjsrb.c', line 595

static VALUE vm_m_initialize(int argc, VALUE *argv, VALUE r_self)
{
  VALUE r_opts;
  rb_scan_args(argc, argv, ":", &r_opts);
  if (NIL_P(r_opts))
    r_opts = rb_hash_new();

  VALUE r_memory_limit = rb_hash_aref(r_opts, ID2SYM(rb_intern("memory_limit")));
  if (NIL_P(r_memory_limit))
    r_memory_limit = UINT2NUM(1024 * 1024 * 128);
  VALUE r_max_stack_size = rb_hash_aref(r_opts, ID2SYM(rb_intern("max_stack_size")));
  if (NIL_P(r_max_stack_size))
    r_max_stack_size = UINT2NUM(1024 * 1024 * 4);
  VALUE r_features = rb_hash_aref(r_opts, ID2SYM(rb_intern("features")));
  if (NIL_P(r_features))
    r_features = rb_ary_new();
  VALUE r_timeout_msec = rb_hash_aref(r_opts, ID2SYM(rb_intern("timeout_msec")));
  if (NIL_P(r_timeout_msec))
    r_timeout_msec = UINT2NUM(100);

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  data->eval_time->limit_ms = (int64_t)NUM2UINT(r_timeout_msec);
  JS_SetContextOpaque(data->context, data);
  JSRuntime *runtime = JS_GetRuntime(data->context);

  JS_SetMemoryLimit(runtime, NUM2UINT(r_memory_limit));
  JS_SetMaxStackSize(runtime, NUM2UINT(r_max_stack_size));

  JS_SetModuleLoaderFunc2(runtime, NULL, js_module_loader, js_module_check_attributes, NULL);
  js_std_init_handlers(runtime);

  JSValue j_global = JS_GetGlobalObject(data->context);

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featureStdId))))
  {
    js_init_module_std(data->context, "std");
    const char *enableStd = "import * as std from 'std';\n"
                            "globalThis.std = std;\n";
    JSValue j_stdEval = JS_Eval(data->context, enableStd, strlen(enableStd), "<vm>", JS_EVAL_TYPE_MODULE);
    JS_FreeValue(data->context, j_stdEval);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featureOsId))))
  {
    js_init_module_os(data->context, "os");
    const char *enableOs = "import * as os from 'os';\n"
                           "globalThis.os = os;\n";
    JSValue j_osEval = JS_Eval(data->context, enableOs, strlen(enableOs), "<vm>", JS_EVAL_TYPE_MODULE);
    JS_FreeValue(data->context, j_osEval);
  }
  else if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featureTimeoutId))))
  {
    JS_SetPropertyStr(
        data->context, j_global, "setTimeout",
        JS_NewCFunction(data->context, js_quickjsrb_set_timeout, "setTimeout", 2));
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillIntlId))))
  {
    const char *defineIntl = "Object.defineProperty(globalThis, 'Intl', { value:{} });\n";
    JSValue j_defineIntl = JS_Eval(data->context, defineIntl, strlen(defineIntl), "<vm>", JS_EVAL_TYPE_GLOBAL);
    JS_FreeValue(data->context, j_defineIntl);

    JSValue j_polyfillIntlObject = JS_ReadObject(data->context, &qjsc_polyfill_intl_en_min, qjsc_polyfill_intl_en_min_size, JS_READ_OBJ_BYTECODE);
    JSValue j_polyfillIntlResult = JS_EvalFunction(data->context, j_polyfillIntlObject); // Frees polyfillIntlObject
    JS_FreeValue(data->context, j_polyfillIntlResult);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillFileId))))
  {
    JSValue j_polyfillFileObject = JS_ReadObject(data->context, &qjsc_polyfill_file_min, qjsc_polyfill_file_min_size, JS_READ_OBJ_BYTECODE);
    JSValue j_polyfillFileResult = JS_EvalFunction(data->context, j_polyfillFileObject);
    JS_FreeValue(data->context, j_polyfillFileResult);

    quickjsrb_init_file_proxy(data);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillEncodingId))))
  {
    JSValue j_polyfillEncodingObject = JS_ReadObject(data->context, &qjsc_polyfill_encoding_min, qjsc_polyfill_encoding_min_size, JS_READ_OBJ_BYTECODE);
    JSValue j_polyfillEncodingResult = JS_EvalFunction(data->context, j_polyfillEncodingObject);
    JS_FreeValue(data->context, j_polyfillEncodingResult);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillUrlId))))
  {
    JSValue j_polyfillUrlObject = JS_ReadObject(data->context, &qjsc_polyfill_url_min, qjsc_polyfill_url_min_size, JS_READ_OBJ_BYTECODE);
    JSValue j_polyfillUrlResult = JS_EvalFunction(data->context, j_polyfillUrlObject);
    JS_FreeValue(data->context, j_polyfillUrlResult);
  }

  if (RTEST(rb_funcall(r_features, rb_intern("include?"), 1, QUICKJSRB_SYM(featurePolyfillCryptoId))))
  {
    quickjsrb_init_crypto(data->context, j_global);
  }

  JSValue j_console = JS_NewObject(data->context);
  JS_SetPropertyStr(
      data->context, j_console, "log",
      JS_NewCFunction(data->context, js_console_info, "log", 1));
  JS_SetPropertyStr(
      data->context, j_console, "debug",
      JS_NewCFunction(data->context, js_console_verbose, "debug", 1));
  JS_SetPropertyStr(
      data->context, j_console, "info",
      JS_NewCFunction(data->context, js_console_info, "info", 1));
  JS_SetPropertyStr(
      data->context, j_console, "warn",
      JS_NewCFunction(data->context, js_console_warn, "warn", 1));
  JS_SetPropertyStr(
      data->context, j_console, "error",
      JS_NewCFunction(data->context, js_console_error, "error", 1));

  JS_SetPropertyStr(data->context, j_global, "console", j_console);
  JS_FreeValue(data->context, j_global);

  return r_self;
}

Instance Method Details

#call(*args) ⇒ Object



802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
# File 'ext/quickjsrb/quickjsrb.c', line 802

static VALUE vm_m_callGlobalFunction(int argc, VALUE *argv, VALUE r_self)
{
  if (argc < 1)
    rb_raise(rb_eArgError, "wrong number of arguments (given 0, expected 1+)");

  VALUE r_name = argv[0];

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  JSValue j_this = JS_UNDEFINED;
  JSValue j_func;

  VALUE r_path;
  if (SYMBOL_P(r_name) || RB_TYPE_P(r_name, T_STRING))
  {
    VALUE r_name_str = rb_funcall(r_name, rb_intern("to_s"), 0);
    const char *name_str = StringValueCStr(r_name_str);
    size_t name_len = strlen(name_str);
    const char *last_bracket = strrchr(name_str, '[');
    const char *last_dot = strrchr(name_str, '.');

    if (last_bracket != NULL && last_bracket != name_str && name_str[name_len - 1] == ']')
    {
      // Bracket notation: 'a["key"]' or 'a.b["key"]' or 'a[0]'
      // Split into parent expression and the bracketed key
      VALUE r_parent = rb_str_new(name_str, last_bracket - name_str);
      const char *key_start = last_bracket + 1;
      size_t key_len = name_len - (key_start - name_str) - 1; // exclude ']'
      // Strip surrounding quotes for string keys: 'a["b"]' → key = b
      if (key_len >= 2 &&
          ((key_start[0] == '\'' && key_start[key_len - 1] == '\'') ||
           (key_start[0] == '"' && key_start[key_len - 1] == '"')))
      {
        key_start++;
        key_len -= 2;
      }
      VALUE r_key = rb_str_new(key_start, key_len);
      r_path = rb_ary_new3(2, r_parent, r_key);
    }
    else if (last_dot != NULL && last_dot != name_str)
    {
      // Dot notation: 'a.b.c' → ['a.b', 'c'] so the parent becomes `this`
      VALUE r_parent = rb_str_new(name_str, last_dot - name_str);
      VALUE r_key = rb_str_new2(last_dot + 1);
      r_path = rb_ary_new3(2, r_parent, r_key);
    }
    else
    {
      r_path = rb_ary_new3(1, r_name_str);
    }
  }
  else
  {
    rb_raise(rb_eTypeError, "function's name should be a Symbol or a String");
  }

  {
    long path_len = RARRAY_LEN(r_path);

    VALUE r_first = RARRAY_AREF(r_path, 0);
    if (!(SYMBOL_P(r_first) || RB_TYPE_P(r_first, T_STRING)))
      rb_raise(rb_eTypeError, "function path elements should be Symbols or Strings");

    VALUE r_first_str = rb_funcall(r_first, rb_intern("to_s"), 0);
    const char *first_seg = StringValueCStr(r_first_str);

    // JS_Eval accesses both global object properties and lexical (const/let) bindings
    JSValue j_cur = JS_Eval(data->context, first_seg, strlen(first_seg), "<vm>", JS_EVAL_TYPE_GLOBAL);
    if (JS_IsException(j_cur))
      return to_rb_value(data->context, j_cur); // raises

    for (long i = 1; i < path_len; i++)
    {
      VALUE r_seg = RARRAY_AREF(r_path, i);
      if (!(SYMBOL_P(r_seg) || RB_TYPE_P(r_seg, T_STRING)))
      {
        JS_FreeValue(data->context, j_cur);
        JS_FreeValue(data->context, j_this);
        rb_raise(rb_eTypeError, "function path elements should be Symbols or Strings");
      }
      VALUE r_seg_str = rb_funcall(r_seg, rb_intern("to_s"), 0);
      const char *seg = StringValueCStr(r_seg_str);

      JSValue j_next = JS_GetPropertyStr(data->context, j_cur, seg);
      if (JS_IsException(j_next))
      {
        JS_FreeValue(data->context, j_cur);
        JS_FreeValue(data->context, j_this);
        return to_rb_value(data->context, j_next); // raises
      }

      JS_FreeValue(data->context, j_this);
      j_this = j_cur;
      j_cur = j_next;
    }

    j_func = j_cur;
  }

  if (!JS_IsFunction(data->context, j_func))
  {
    JS_FreeValue(data->context, j_func);
    JS_FreeValue(data->context, j_this);
    VALUE r_error_message = rb_str_new2("given path is not a function");
    rb_exc_raise(rb_funcall(QUICKJSRB_ERROR_FOR(QUICKJSRB_ROOT_RUNTIME_ERROR), rb_intern("new"), 2, r_error_message, Qnil));
    return Qnil;
  }

  int nargs = argc - 1;
  JSValue *j_args = NULL;
  if (nargs > 0)
  {
    j_args = (JSValue *)malloc(sizeof(JSValue) * nargs);
    for (int i = 0; i < nargs; i++)
      j_args[i] = to_js_value(data->context, argv[i + 1]);
  }

  clock_gettime(CLOCK_MONOTONIC, &data->eval_time->started_at);
  JS_SetInterruptHandler(JS_GetRuntime(data->context), interrupt_handler, data->eval_time);

  JSValue j_result = JS_Call(data->context, j_func, j_this, nargs, (JSValueConst *)j_args);

  JS_FreeValue(data->context, j_func);
  JS_FreeValue(data->context, j_this);
  if (j_args)
  {
    for (int i = 0; i < nargs; i++)
      JS_FreeValue(data->context, j_args[i]);
    free(j_args);
  }

  // js_std_await handles both async (promise) and sync results; frees j_result
  return to_rb_return_value(data->context, js_std_await(data->context, j_result));
}

#define_function(*args) ⇒ Object



764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# File 'ext/quickjsrb/quickjsrb.c', line 764

static VALUE vm_m_defineGlobalFunction(int argc, VALUE *argv, VALUE r_self)
{
  rb_need_block();

  VALUE r_name;
  VALUE r_flags;
  VALUE r_block;
  rb_scan_args(argc, argv, "10*&", &r_name, &r_flags, &r_block);

  if (!(SYMBOL_P(r_name) || RB_TYPE_P(r_name, T_STRING)))
  {
    rb_raise(rb_eTypeError, "function's name should be a Symbol or a String");
  }

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  VALUE r_name_sym = rb_funcall(r_name, rb_intern("to_sym"), 0);

  rb_hash_aset(data->defined_functions, r_name_sym, r_block);
  VALUE r_name_str = rb_funcall(r_name, rb_intern("to_s"), 0);
  char *funcName = StringValueCStr(r_name_str);

  JSValueConst ruby_data[2];
  ruby_data[0] = JS_NewString(data->context, funcName);
  ruby_data[1] = JS_NewBool(data->context, RTEST(rb_funcall(r_flags, rb_intern("include?"), 1, ID2SYM(rb_intern("async")))));

  JSValue j_global = JS_GetGlobalObject(data->context);
  JS_SetPropertyStr(
      data->context, j_global, funcName,
      JS_NewCFunctionData(data->context, js_quickjsrb_call_global, 1, 0, 2, ruby_data));
  JS_FreeValue(data->context, j_global);
  JS_FreeValue(data->context, ruby_data[0]);
  JS_FreeValue(data->context, ruby_data[1]);

  return r_name_sym;
}

#eval_code(r_code) ⇒ Object



740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'ext/quickjsrb/quickjsrb.c', line 740

static VALUE vm_m_evalCode(VALUE r_self, VALUE r_code)
{
  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  if (!RB_TYPE_P(r_code, T_STRING))
  {
    VALUE r_code_class = rb_class_name(CLASS_OF(r_code));
    rb_raise(rb_eTypeError, "JavaScript code must be a String, got %s", StringValueCStr(r_code_class));
  }

  clock_gettime(CLOCK_MONOTONIC, &data->eval_time->started_at);
  JS_SetInterruptHandler(JS_GetRuntime(data->context), interrupt_handler, data->eval_time);

  char *code = StringValueCStr(r_code);
  JSValue j_codeResult = JS_Eval(data->context, code, strlen(code), "<code>", JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_ASYNC);
  JSValue j_awaitedResult = js_std_await(data->context, j_codeResult); // This frees j_codeResult
  // JS_EVAL_FLAG_ASYNC wraps the result in {value, done} — extract the actual value
  // Free j_awaitedResult before to_rb_return_value because it may raise (longjmp), which would skip cleanup
  JSValue j_returnedValue = JS_GetPropertyStr(data->context, j_awaitedResult, "value");
  JS_FreeValue(data->context, j_awaitedResult);
  return to_rb_return_value(data->context, j_returnedValue);
}

#import(*args) ⇒ Object



938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
# File 'ext/quickjsrb/quickjsrb.c', line 938

static VALUE vm_m_import(int argc, VALUE *argv, VALUE r_self)
{
  VALUE r_import_string, r_opts;
  rb_scan_args(argc, argv, "10:", &r_import_string, &r_opts);
  if (NIL_P(r_opts))
    r_opts = rb_hash_new();
  VALUE r_from = rb_hash_aref(r_opts, ID2SYM(rb_intern("from")));
  if (NIL_P(r_from))
  {
    VALUE r_error_message = rb_str_new2("missing import source");
    rb_exc_raise(rb_funcall(QUICKJSRB_ERROR_FOR(QUICKJSRB_ROOT_RUNTIME_ERROR), rb_intern("new"), 2, r_error_message, Qnil));
    return Qnil;
  }
  VALUE r_custom_exposure = rb_hash_aref(r_opts, ID2SYM(rb_intern("code_to_expose")));

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  char *filename = random_string();
  char *source = StringValueCStr(r_from);
  JSValue module = JS_Eval(data->context, source, strlen(source), filename, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  if (JS_IsException(module))
  {
    JS_FreeValue(data->context, module);
    return to_rb_value(data->context, module);
  }
  js_module_set_import_meta(data->context, module, TRUE, FALSE);
  JS_FreeValue(data->context, module);

  VALUE r_import_settings = rb_funcall(
      rb_const_get(rb_cClass, rb_intern("Quickjs")),
      rb_intern("_build_import"),
      1,
      r_import_string);
  VALUE r_import_name = rb_ary_entry(r_import_settings, 0);
  char *import_name = StringValueCStr(r_import_name);
  VALUE r_default_exposure = rb_ary_entry(r_import_settings, 1);
  char *globalize;
  if (RTEST(r_custom_exposure))
  {
    globalize = StringValueCStr(r_custom_exposure);
  }
  else
  {
    globalize = StringValueCStr(r_default_exposure);
  }

  const char *importAndGlobalizeModule = "import %s from '%s';\n"
                                         "%s\n";
  int length = snprintf(NULL, 0, importAndGlobalizeModule, import_name, filename, globalize);
  char *result = (char *)malloc(length + 1);
  snprintf(result, length + 1, importAndGlobalizeModule, import_name, filename, globalize);

  JSValue j_codeResult = JS_Eval(data->context, result, strlen(result), "<vm>", JS_EVAL_TYPE_MODULE);
  free(result);
  JS_FreeValue(data->context, j_codeResult);

  return Qtrue;
}

#on_logObject



503
504
505
506
507
508
509
510
511
512
513
# File 'ext/quickjsrb/quickjsrb.c', line 503

static VALUE vm_m_on_log(VALUE r_self)
{
  rb_need_block();

  VMData *data;
  TypedData_Get_Struct(r_self, VMData, &vm_type, data);

  data->log_listener = rb_block_proc();

  return Qnil;
}