-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathutils.R
1594 lines (1402 loc) · 58.2 KB
/
utils.R
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
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
801
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
937
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
997
998
999
1000
# ----------------------------------------------------------------------------
# Class assertion
# ----------------------------------------------------------------------------
# fiery server
is.fire <- function(x) inherits(x, "Fire")
# dependencies
is.dependency <- function(x) inherits(x, "dash_dependency")
is.output <- function(x) inherits(x, "output")
is.input <- function(x) inherits(x, "input")
is.state <- function(x) inherits(x, "state")
is.event <- function(x) is.dependency(x) && inherits(x, "event")
# components (TODO: this should be exported by dashRtranspile!)
is.component <- function(x) inherits(x, "dash_component")
# retrieve the arguments of a callback function that are dash inputs
callback_inputs <- function(func) {
compact(lapply(formals(func), function(x) {
# missing arguments produce an error when evaluated
# TODO: should we only evaluate when `!identical(x, quote(expr = ))`?
val <- tryNULL(eval(x))
if (is.input(val)) val else NULL
}))
}
callback_states <- function(func) {
compact(lapply(formals(func), function(x) {
# missing arguments produce an error when evaluated
# TODO: should we only evaluate when `!identical(x, quote(expr = ))`?
val <- tryNULL(eval(x))
if (is.state(val)) val else NULL
}))
}
callback_events <- function(func) {
compact(lapply(formals(func), function(x) {
# missing arguments produce an error when evaluated
# TODO: should we only evaluate when `!identical(x, quote(expr = ))`?
val <- tryNULL(eval(x))
if (is.event(val)) val else NULL
}))
}
# search through a component (a recursive data structure) for a component with
# a given id and return the component's type
component_props_given_id <- function(component, id) {
is_component <- is.component(component)
is_match <- if (is_component) isTRUE(component$props$id == id) else FALSE
props <- if (is_match) component$propNames else NA
if (is_component && !is_match) {
if ("children" %in% names(component$props)) {
return(unlist(lapply(component$props$children, component_props_given_id, id)))
}
}
props
}
component_contains_type <- function(component, package, type) {
is_component <- is.component(component)
is_match <- if (is_component) isTRUE(component$type == type) && isTRUE(component$package == package) else FALSE
if (is_component && !is_match) {
if ("children" %in% names(component$props)) {
return(any(unlist(lapply(component$props$children, component_contains_type, package, type))))
}
}
is_match
}
# ----------------------------------------------------------------------
# HTTP helpers
# ----------------------------------------------------------------------
request_parse_json <- function(request) {
# request body must be parsed on demand (to avoid errors by odd formats)
# http://www.data-imaginist.com/2017/Introducing-reqres/
if (!request$is("json")) stop("Expected a JSON request", call. = FALSE)
# Unlike `reqres::default_parsers["application/json"]`, we don't
# simplify the *entire* JSON blob, but we do simplify input/state value(s)
# https://gist.github.com/cpsievert/04d53edbe902ca86a41949e24e8b4af7
from_JSON <- function(raw, directives) {
jsonlite::fromJSON(rawToChar(raw), simplifyVector = FALSE)
}
success <- request$parse(list(`application/json` = from_JSON))
if (!success) stop("Failed to parse body", call. = FALSE)
request
}
# ----------------------------------------------------------------------------
# HTML dependency helpers
# ----------------------------------------------------------------------------
# @param dependencies a list of HTML dependencies
# @param local should local versions be served instead of CDN hrefs?
# @param prefix the prefix to use for responding to requests, if set
render_dependencies <- function(dependencies, local = TRUE, prefix=NULL) {
html <- sapply(dependencies, function(dep, is_local=local, path_prefix=prefix) {
assertthat::assert_that(inherits(dep, "html_dependency"))
srcs <- names(dep[["src"]])
src <- if (!is_local && !"href" %in% srcs && "file" %in% srcs) {
msg <- paste0("No remote hyperlink found for HTML dependency ",
dep[["name"]],
". Using local file instead.")
message(msg)
"file"
} else if (is_local && !"file" %in% srcs && "href" %in% srcs) {
msg <- paste0("No local file found for HTML dependency ",
dep[["name"]],
". Using the remote URL instead.")
message(msg)
"href"
} else if (!is_local) {
"href"
} else {
"file"
}
# According to Dash convention, label react and react-dom as originating
# in dash_renderer package, even though all three are currently served
# up from the DashR package
if (dep$name %in% c("react", "react-dom", "prop-types")) {
dep$name <- "dash-renderer"
}
# The following lines inject _dash-component-suites into the src tags,
# as this is the current Dash convention. The dependency paths cannot
# be set solely at component library generation time, since hosted
# applications should have the app name injected as well.
#
# This is essentially analogous to this codeblock on the Python side:
# https://github.com/plotly/dash/blob/1249ffbd051bfb5fdbe439612cbec7fa8fff5ab5/dash/dash.py#L207
#
# Use the system file modification timestamp for the current
# package and add the version number of the package as a query
# parameter for cache busting
if (!is.null(dep$package)) {
full_path <- getDependencyPath(dep)
modified <- as.integer(file.mtime(full_path))
} else {
modified <- as.integer(Sys.time())
}
# we don't want to serve the JavaScript source maps here,
# until we are able to provide full support for debug mode,
# as in Dash for Python
if ("script" %in% names(dep) && tools::file_ext(dep[["script"]]) != "map") {
if (!(is_local) & !(is.null(dep$src$href))) {
html <- generate_js_dist_html(tagdata = dep$src$href)
} else {
script_mtime <- file.mtime(getDependencyPath(dep))
modtime <- as.integer(script_mtime)
dep$script <- buildFingerprint(dep$script, dep$version, modtime)
dep[["script"]] <- paste0(path_prefix,
"_dash-component-suites/",
dep$name,
"/",
basename(dep[["script"]]),
"?v=",
dep$version,
"&m=",
modified)
html <- generate_js_dist_html(tagdata = dep[["script"]], as_is = TRUE)
}
} else if (!(is_local) & "stylesheet" %in% names(dep) & src == "href") {
html <- generate_css_dist_html(tagdata = paste(dep[["src"]][["href"]],
dep[["stylesheet"]],
sep="/"),
local = FALSE)
} else if ("stylesheet" %in% names(dep) & src == "file") {
dep[["stylesheet"]] <- paste0(path_prefix,
"_dash-component-suites/",
dep$name,
"/",
basename(dep[["stylesheet"]]))
if (!(is.null(dep$version))) {
if(!is.null(dep$package)) {
sheetpath <- paste0(dep[["stylesheet"]],
"?v=",
dep$version)
html <- generate_css_dist_html(tagdata = sheetpath, as_is = TRUE)
} else {
sheetpath <- paste0(dep[["src"]][["file"]],
dep[["stylesheet"]],
"?v=",
dep$version)
html <- generate_css_dist_html(tagdata = sheetpath, as_is = TRUE)
}
} else {
sheetpath <- paste0(dep[["src"]][["file"]],
dep[["stylesheet"]])
html <- generate_css_dist_html(tagdata = sheetpath, as_is = TRUE)
}
}
})
paste(html, collapse = "\n")
}
# ----------------------------------------------------------------------------
# Other (generic) helpers
# ----------------------------------------------------------------------------
"%||%" <- function(x, y) {
if (length(x)) x else y
}
compact <- function(x) {
Filter(Negate(is.null), x)
}
# same as plotly:::to_JSON
to_JSON <- function(x, ...) {
jsonlite::toJSON(x, digits = 50, auto_unbox = TRUE, force = TRUE,
null = "null", na = "null", ...)
}
# same as plotly:::new_id
new_id <- function() {
basename(tempfile(""))
}
dir_exists <- function(paths) {
utils::file_test("-d", paths)
}
tryNULL <- function(expr) {
tryCatch(expr, error = function(e) NULL)
}
str_trim <- function(x) {
sub("\\s+$", "", sub("^\\s+", "", x))
}
setdiffsym <- function(x, y) {
setdiff(union(x, y), intersect(x, y))
}
stop_report <- function(msg = "") {
stop(
msg, "\n\n",
"Please let us know about this error via ",
"https://github.com/plotly/dashR/issues/new",
call. = FALSE
)
}
try_library <- function(pkg, fun = NULL) {
if (system.file(package = pkg) != "") {
return(invisible())
}
stop("Package `", pkg, "` required", if (!is.null(fun))
paste0(" for `", fun, "`"), ".\n", "Please install and try again.",
call. = FALSE)
}
assert_valid_children <- function(children, ...) {
kids <- list(children)
if (...length()) {
pattern <- paste(paste0('^', ...), collapse = '|')
kids <- kids[!grepl(pattern, names2(kids))]
}
if (!length(kids)) return(NULL)
assert_no_names(kids)
}
assert_no_names <- function (x)
{
if(!(is.list(x))) x <- list(x)
nms <- names(x)
if (is.null(nms))
return(x)
if (identical("", unique(nms)))
return(setNames(x, NULL))
stop(sprintf("Didn't recognize the following named arguments: '%s'",
paste(nms, collapse = "', '")), call. = FALSE)
}
assertValidWildcards <- function(dependency) {
if (is.symbol(dependency$id)) {
result <- (jsonlite::validate(as.character(dependency$id)) && grepl("{", dependency$id))
} else {
result <- TRUE
}
if (!result) {
dependencyType <- class(dependency)
stop(sprintf("A callback %s ID contains restricted pattern matching callback selectors ALL, MATCH or ALLSMALLER. Please verify that it is formatted as a pattern matching callback list ID, or choose a different component ID.",
dependencyType[dependencyType %in% c("input", "output", "state")]),
call. = FALSE)
} else {
return(result)
}
}
# the following function attempts to prune remote CSS
# or local CSS/JS dependencies that either should not
# be resolved to local R package paths, or which have
# insufficient information to do so.
#
# this attempts to avoid cryptic errors produced by
# get_package_mapping, which requires three parameters:
# -- the script name (i.e. x$script below)
# -- the package name from the URL (i.e. x$package)
# -- the list of dependencies (i.e. deps)
#
# within get_package_mapping, x$package is also required,
# so deps missing it here are assigned NULL and then
# filtered out by the subsequent vapply statement
clean_dependencies <- function(deps) {
dep_list <- lapply(deps, function(x) {
if (is.null(x$src$file) | (is.null(x$script) & is.null(x$stylesheet) & is.null(x$other)) | (is.null(x$package))) {
if (is.null(x$src$href))
stop(sprintf("Script, CSS, or other dependencies with NULL href fields must include a file path, dependency name, and R package name."), call. = FALSE)
else
return(NULL)
}
else
return(x)
}
)
deps_with_file <- dep_list[!vapply(dep_list, is.null, logical(1))]
return(deps_with_file)
}
insertIntoCallbackMap <- function(map, inputs, output, state, func, clientside_function) {
output_id <- createCallbackId(output)
if (output_id %in% names(map)) {
stop(
sprintf(
"One or more of the following outputs are duplicated across callbacks: %s. Please ensure that all ID and property combinations are unique.",
output_id
),
call. = FALSE
)
}
map[[output_id]] <- list(
inputs = inputs,
output = output,
state = state,
func = func,
clientside_function = clientside_function
)
if (length(map) >= 2) {
ids <- lapply(names(map), function(x) getIdProps(x)$ids)
props <- lapply(names(map), function(x) getIdProps(x)$props)
outputs_as_list <- mapply(paste, ids, props, sep=".", SIMPLIFY = FALSE)
if (length(Reduce(intersect, outputs_as_list))) {
stop(sprintf("One or more outputs are duplicated across callbacks. Please ensure that all ID and property combinations are unique."), call. = FALSE)
}
}
return(map)
}
assert_valid_callbacks <- function(output, params, func) {
inputs <- params[vapply(params, function(x) 'input' %in% attr(x, "class"), FUN.VALUE=logical(1))]
state <- params[vapply(params, function(x) 'state' %in% attr(x, "class"), FUN.VALUE=logical(1))]
invalid_params <- vapply(params, function(x) {
!any(c('input', 'state') %in% attr(x, "class"))
}, FUN.VALUE=logical(1))
if (!is.list(output[[1]])) listed_output <- list(output) else listed_output <- output
invalid_outputs <- vapply(listed_output, function(x) {
!any(c('output') %in% attr(x, "class"))
}, FUN.VALUE=logical(1))
# Verify that no outputs are duplicated
if (length(output) != length(unique(output))) {
stop(sprintf("One or more callback outputs have been duplicated; please confirm that all outputs are unique."), call. = FALSE)
}
# Verify that params contains no elements that are not either members of 'input' or 'state' classes
if (any(invalid_params)) {
stop(sprintf("Callback parameters must be inputs or states. Please verify formatting of callback parameters."), call. = FALSE)
}
# Verify that output contains no elements that are not a member of the 'output' class.
if (any(invalid_outputs)) {
stop(sprintf("Callback outputs must be output function calls. Please verify formatting of callback outputs."), call. = FALSE)
}
# Assert that the component ID as passed is a string.
# This function inspects the output object to see if its ID
# is a valid string.
validateOutput <- function(string) {
return((is.character(string[["id"]]) & !grepl("^\\s*$", string[["id"]]) & !grepl("\\.", string[["id"]])))
}
# Check if the callback uses multiple outputs
if (any(sapply(output, is.list))) {
invalid_callback_ID <- (!all(vapply(output, validateOutput, logical(1))))
} else {
invalid_callback_ID <- (!validateOutput(output))
}
if (invalid_callback_ID) {
stop(sprintf("Callback IDs must be (non-empty) character strings that do not contain one or more dots/periods. Please verify that the component ID is valid."), call. = FALSE)
}
# Assert that user_function is a valid function
if(!(is.function(func))) {
if (!(all(names(func) == c("namespace", "function_name")))) {
stop(sprintf("The callback method's 'func' parameter requires an R function or clientsideFunction call as its argument. Please verify that 'func' is either a valid R function or clientsideFunction."), call. = FALSE)
}
}
# Check if inputs are a nested list
if(!(any(sapply(inputs, is.list)))) {
stop(sprintf("Callback inputs should be a nested list, in which each element of the sublist represents a component ID and its properties."), call. = FALSE)
}
# Check if state is a nested list, if the list is not empty
if(!(length(state) == 0) & !(any(sapply(state, is.list)))) {
stop(sprintf("Callback states should be a nested list, in which each element of the sublist represents a component ID and its properties."), call. = FALSE)
}
# Check that input is not NULL
if(is.null(inputs)) {
stop(sprintf("The callback method requires that one or more properly formatted inputs are passed."), call. = FALSE)
}
# Verify that 'input', 'state' and 'output' parameters only contain 'Wildcard' keywords if they are JSON formatted ids for pattern matching callbacks
valid_wildcard_inputs <- sapply(inputs, function(x) {
assertValidWildcards(x)
})
valid_wildcard_state <- sapply(state, function(x) {
assertValidWildcards(x)
})
if(any(sapply(output, is.list))) {
valid_wildcard_output <- sapply(output, function(x) {
assertValidWildcards(x)
})
} else {
valid_wildcard_output <- sapply(list(output), function(x) {
assertValidWildcards(x)
})
}
# Check that outputs are not inputs
# https://github.com/plotly/dash/issues/323
# helper function to permit same mapply syntax regardless
# of whether output is defined using output function or not
listWrap <- function(x){
if (!any(sapply(x, is.list))) {
return(list(x))
} else {
x
}
}
# determine whether any input matches the output, or outputs, if
# multiple callback scenario
inputs_vs_outputs <- mapply(function(inputObject, outputObject) {
identical(outputObject[["id"]], inputObject[["id"]]) & identical(outputObject[["property"]], inputObject[["property"]])
}, inputs, listWrap(output))
if(TRUE %in% inputs_vs_outputs) {
stop(sprintf("Circular input and output arguments were found. Please verify that callback outputs are not also input arguments."), call. = FALSE)
}
# TO DO: check that components contain props
TRUE
}
names2 <- function(x) names(x) %||% rep('', length(x))
valid_seq <- function(params) {
class_attr <- vapply(params, function(x) {
attr(x, "class")[attr(x, "class") %in% c('input', 'state')]
}, FUN.VALUE=character(1))
rle_result <- rle(class_attr)$values
if (identical(rle_result, 'input')) {
return(TRUE)
} else if (identical(rle_result, c('input', 'state'))) {
return(TRUE)
} else {
return(FALSE)
}
}
resolvePrefix <- function(prefix, environment_var, base_pathname) {
if (!(is.null(prefix))) {
assertthat::assert_that(is.character(prefix))
return(prefix)
} else {
# Check environment variables
prefix_env <- Sys.getenv(environment_var)
env_base_pathname <- Sys.getenv("DASH_URL_BASE_PATHNAME")
app_name <- Sys.getenv("DASH_APP_NAME")
if (prefix_env != "")
return(prefix_env)
else if (app_name != "")
return(sprintf("/%s/", app_name))
else if (env_base_pathname != "")
return(env_base_pathname)
else
return(base_pathname)
}
}
# The function below requires a dependency path, package information
# retrieved from a request URL, as well as a list of dependencies
# (currently in htmltools htmlDependency format). get_package_mapping
# optionally returns an R package name (if the file is contained
# inside an R package), or NULL if the dependency is not found,
# and a (local) path to the dependency.
#
# script_name is e.g. "dash_core_components.min.js"
# url_package is e.g. "dash_core_components"
# dependencies = list of htmlDependency objects
# this function returns a list with two elements:
# rpkg_name = character string supplying the name of the R package
# rpkg_path = character string providing the path to the dependency
get_package_mapping <- function(script_name, url_package, dependencies) {
# TODO: improve validation of dependency inputs, particularly
# to avoid duplicating dependencies in the package_map
package_map <- vapply(unique(dependencies), function(x) {
if (x$name %in% c('react', 'react-dom', 'prop-types')) {
x$name <- 'dash-renderer'
}
if (!is.null(x$script))
dep_path <- file.path(x$src$file, x$script)
else if (!is.null(x$stylesheet))
dep_path <- file.path(x$src$file, x$stylesheet)
else if (!is.null(x$other))
dep_path <- file.path(x$src$file, x$other)
# remove n>1 slashes and replace with / if present;
# htmltools seems to permit // in pathnames, but
# this complicates string matching unless they're
# removed from the pathname
result <- c(pkg_name=ifelse("package" %in% names(x), x$package, NULL),
dep_name=x$name,
dep_path=gsub("//+", replacement = "/", dep_path)
)
}, FUN.VALUE = character(3))
package_map <- t(package_map)
# pos_match is a vector of logical() values -- this allows filtering
# of the package_map entries based on name, path, and matching of
# URL package name against R package names. when all conditions are
# satisfied, pos_match will return TRUE
pos_match <- grepl(paste0(script_name, "$"), package_map[, "dep_path"]) &
grepl(url_package, package_map[,"dep_name"])
rpkg_name <- package_map[,"pkg_name"][pos_match]
rpkg_path <- package_map[,"dep_path"][pos_match]
return(list(rpkg_name=rpkg_name, rpkg_path=rpkg_path))
}
get_mimetype <- function(filename) {
filename_ext <- getFileExt(filename)
if (filename_ext == 'js')
return('application/JavaScript')
else if (filename_ext == 'css')
return('text/css')
else if (filename_ext %in% c('js.map', 'map'))
return('application/json')
else
return(mime::guess_type(filename,
empty = "application/octet-stream"))
}
generate_css_dist_html <- function(tagdata,
local = FALSE,
local_path = NULL,
prefix = NULL,
as_is = FALSE) {
attribs <- names(tagdata)
if (!(local)) {
if (any(grepl("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$",
tagdata,
perl=TRUE)) || as_is) {
if (is.list(tagdata))
glue::glue('<link ', glue::glue_collapse(glue::glue('{attribs}="{tagdata}"'), sep=" "), ' rel="stylesheet">')
else {
interpolated_link <- glue::glue('href="{tagdata}"')
glue::glue('<link ', '{interpolated_link}', ' rel="stylesheet">')
}
}
else
stop(sprintf("Invalid URL supplied in external_stylesheets. Please check the syntax used for this parameter."), call. = FALSE)
} else {
modified <- as.integer(file.mtime(local_path))
# strip leading slash from href if present
if (is.list(tagdata)) {
tagdata$href <- paste0(prefix, sub("^/", "", tagdata$href))
glue::glue('<link ', glue::glue_collapse(glue::glue('{attribs}="{tagdata}?m={modified}"'), sep=" "), ' rel="stylesheet">')
}
else {
tagdata <- sub("^/", "", tagdata)
interpolated_link <- glue::glue('href="{prefix}{tagdata}?m={modified}"')
glue::glue('<link ', '{interpolated_link}', ' rel="stylesheet">')
}
}
}
generate_js_dist_html <- function(tagdata,
local = FALSE,
local_path = NULL,
prefix = NULL,
as_is = FALSE) {
attribs <- names(tagdata)
if (!(local)) {
if (any(grepl("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$",
tagdata,
perl=TRUE)) || as_is) {
if (is.list(tagdata))
glue::glue('<script ', glue::glue_collapse(glue::glue('{attribs}="{tagdata}"'), sep=" "), '></script>')
else {
interpolated_link <- glue::glue('src="{tagdata}"')
glue::glue('<script ', '{interpolated_link}', '></script>')
}
}
else
stop(sprintf("Invalid URL supplied. Please check the syntax used for this parameter."), call. = FALSE)
} else {
modified <- as.integer(file.mtime(local_path))
# strip leading slash from href if present
if (is.list(tagdata)) {
tagdata$src <- paste0(prefix, sub("^/", "", tagdata$src))
glue::glue('<script ', glue::glue_collapse(glue::glue('{attribs}="{tagdata}?m={modified}"'), sep=" "), '></script>')
}
else {
tagdata <- sub("^/", "", tagdata)
interpolated_link <- glue::glue('src="{prefix}{tagdata}?m={modified}"')
glue::glue('<script ', '{interpolated_link}', '></script>')
}
}
}
assertValidExternals <- function(scripts, stylesheets) {
allowed_js_attribs <- c("async",
"crossorigin",
"defer",
"integrity",
"nomodule",
"nonce",
"referrerpolicy",
"src",
"type",
"charset",
"language")
allowed_css_attribs <- c("as",
"crossorigin",
"disabled",
"href",
"hreflang",
"importance",
"integrity",
"media",
"referrerpolicy",
"rel",
"sizes",
"title",
"type",
"methods",
"prefetch",
"target",
"charset",
"rev")
script_attributes <- character()
stylesheet_attributes <- character()
for (item in scripts) {
if (is.list(item)) {
if (!"src" %in% names(item) || !(any(grepl("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$",
item,
perl=TRUE))))
stop("A valid URL must be included with every entry in external_scripts. Please sure no 'src' entries are missing or malformed.", call. = FALSE)
if (any(names(item) == ""))
stop("Please verify that all attributes are named elements when specifying URLs for scripts and stylesheets.", call. = FALSE)
script_attributes <- c(script_attributes, names(item))
}
else {
if (!grepl("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$",
item,
perl=TRUE))
stop("A valid URL must be included with every entry in external_scripts. Please sure no 'src' entries are missing or malformed.", call. = FALSE)
script_attributes <- c(script_attributes, character(0))
}
}
for (item in stylesheets) {
if (is.list(item)) {
if (!"href" %in% names(item) || !(any(grepl("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$",
item,
perl=TRUE))))
stop("A valid URL must be included with every entry in external_stylesheets. Please sure no 'href' entries are missing or malformed.", call. = FALSE)
if (any(names(item) == ""))
stop("Please verify that all attributes are named elements when specifying URLs for scripts and stylesheets.", call. = FALSE)
stylesheet_attributes <- c(stylesheet_attributes, names(item))
}
else {
if (!grepl("^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&'\\(\\)\\*\\+,;=.]+$",
item,
perl=TRUE))
stop("A valid URL must be included with every entry in external_stylesheets. Please sure no 'href' entries are missing or malformed.", call. = FALSE)
stylesheet_attributes <- c(stylesheet_attributes, character(0))
}
}
invalid_script_attributes <- setdiff(script_attributes, allowed_js_attribs)
invalid_stylesheet_attributes <- setdiff(stylesheet_attributes, allowed_css_attribs)
if (length(invalid_script_attributes) > 0 || length(invalid_stylesheet_attributes) > 0) {
stop(sprintf("The following script or stylesheet attributes are invalid: %s.",
paste0(c(invalid_script_attributes, invalid_stylesheet_attributes), collapse=", ")), call. = FALSE)
}
invisible(TRUE)
}
generate_meta_tags <- function(metas) {
has_ie_compat <- any(vapply(metas, function(x)
x$name == "http-equiv" && x$content == "X-UA-Compatible",
logical(1)), na.rm=TRUE)
has_charset <- any(vapply(metas, function(x)
"charset" %in% names(x),
logical(1)), na.rm=TRUE)
# allow arbitrary tags with varying numbers of keys
tags <- vapply(metas,
function(tag) sprintf("<meta %s>", paste(sprintf("%s=\"%s\"",
names(tag),
unlist(tag, use.names = FALSE)),
collapse=" ")),
character(1))
if (!has_ie_compat) {
tags <- c('<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">', tags)
}
if (!has_charset) {
tags <- c('<meta charset=\"UTF-8\">', tags)
}
return(tags)
}
# This function takes the list object containing asset paths
# for all stylesheets and scripts, as well as the URL path
# to search, then returns the absolute local path (when
# present) to the requested asset
#
# e.g. assets_map is a named list potentially containing
# $css, a list of absolute paths as character strings
# for all locally supplied CSS assets, named with their
# assets pathname (i.e. "assets/stylesheet.css"), and
# $scripts, a list of character strings formatted
# identically to $css, also named with subpaths.
#
get_asset_path <- function(assets_map, asset_path) {
unlist(setNames(assets_map, NULL))[asset_path]
}
# This function returns the URL corresponding to assets
# included in the asset map, with the request prefix
# prepended, e.g. when asset_path is
#
# assets/stylesheet.css
# "/Users/testuser/assets/stylesheet.css"
#
# ... the function will return
#
# "/assets/stylesheet.css"
#
get_asset_url <- function(asset_path, prefix = "/") {
# the subpath is stored in the names attribute
# of the return object from get_asset_path, so
# we can retrieve it using names()
asset <- names(asset_path)
# strip one or more trailing slashes, since we'll
# introduce one when we concatenate the prefix and
# asset path
prefix <- gsub(pattern = "/+$",
replacement = "",
x = prefix)
# prepend the asset name with the route prefix
return(paste(prefix, asset, sep="/"))
}
encode_plotly <- function(layout_objs) {
if (is.list(layout_objs)) {
if ("plotly" %in% class(layout_objs) &&
"x" %in% names(layout_objs) &&
any(c("visdat", "data") %in% names(layout_objs$x))) {
# check to determine whether the current element is an
# object output from the plot_ly or ggplotly function;
# if it is, we can safely assume that it contains no
# other plot_ly or ggplotly objects and return the updated
# element as a mutated plotly figure argument that contains
# only data and layout attributes. we suppress messages
# since the plotly_build function will supply them, as it's
# typically run interactively.
obj <- suppressMessages(plotly::plotly_build(layout_objs)$x)
layout_objs <- obj[c("data", "layout")]
return(layout_objs)
} else {
for (i in seq_along(layout_objs)) {
# if the current element is a nested list, pass the
# element to encode_plotly to continue recursing the
# tree of components
if (any(sapply(layout_objs[[i]], is.list)))
layout_objs[[i]] <- encode_plotly(layout_objs[[i]])
}
}
}
layout_objs
}
# This function formats the output from sys.calls()
# so that it is pretty printed to stderr()
printCallStack <- function(call_stack, header=TRUE) {
if (header) {
write(crayon::yellow$bold(" ### Dash for R Traceback (most recent/innermost call last) ###"), stderr())
}
write(
crayon::white(
paste0(
" ",
seq_along(
call_stack
),
": ",
call_stack,
" ",
lapply(call_stack, attr, "flineref")
)
),
stderr()
)
}
stackTraceToHTML <- function(call_stack,
throwing_call,
error_message) {
if(is.null(call_stack)) {
return(NULL)
}
header <- " ### Dash for R Traceback (most recent/innermost call last) ###\n"
formattedStack <- c(paste0(
" ",
seq_along(
call_stack
),
": ",
call_stack,
" ",
lapply(call_stack, attr, "lineref"),
collapse="\n"
)
)
template <- "%s\nError: %s: %s\n%s"
response <- sprintf(template,
header,
throwing_call,
error_message,
formattedStack)
# properly format anonymous tags if present in call stack
#response <- gsub("<anonymous>", "<anonymous>", response)
return(response)
}
# This function is essentially the R equivalent of a
# Python decorator method; if debug mode is active,
# it will wrap an expression using withCallingHandlers
# and capture the call stack. By default, the call
# stack will be "pruned" of error handling functions
# for greater readability.
getStackTrace <- function(expr, debug = FALSE, prune_errors = TRUE) {
if (debug) {
tryCatch(withCallingHandlers(
expr,
error = function(e) {
if (is.null(attr(e, "stack.trace", exact = TRUE))) {
calls <- sys.calls()
reverseStack <- rev(calls)
attr(e, "stack.trace") <- calls
if (!is.null(e$call[[1]]))
errorCall <- e$call[[1]]
else {
# attempt to capture the error or warning if thrown by
# simpleError or simpleWarning (which may arise for user-defined errors)
#
# the first matching call in the reversed stack will always be
# getStackTrace, so we select the second match instead
errorCall <- reverseStack[grepl(x=reverseStack, "simpleError|simpleWarning")][[2]]
}
functionsAsList <- lapply(calls, function(completeCall) {
# avoid attempting to cast closures as strings, which will fail
# some calls in the stack are symbol (name) objects, while others
# are calls, which must be deparsed; the first element in the vector
# should be the function signature
if (is.name(completeCall[[1]]))
currentCall <- as.character(completeCall[[1]])
else if (is.call(completeCall[[1]]))
currentCall <- deparse(completeCall)[1]
else
currentCall <- completeCall[[1]]
attr(currentCall, "flineref") <- getLineWithError(completeCall, formatted=TRUE)
attr(currentCall, "lineref") <- getLineWithError(completeCall, formatted=FALSE)
if (is.function(currentCall) & !is.primitive(currentCall)) {
constructedCall <- paste0("<anonymous> function(",
paste(names(formals(currentCall)), collapse = ", "),
")")
return(constructedCall)
} else {
return(currentCall)
}
})
if (prune_errors) {
# this line should match the last occurrence of the function
# which raised the error within the call stack; prune here
indexFromLast <- match(TRUE, lapply(reverseStack, function(currentCall) {
# if the first element of the current call pulled from the stack
# is a function, deparse the error object's call and compare
# to the current call from the stack -- if they're the same,
# return TRUE -- the match function will return the position
# of the first successful match.
#
# since the stack of calls being evaluated is reversed, "pruning"
# here has the effect of capturing the stack up to the most recent
# call which matches the call throwing the error. the call may have
# not thrown an error further up the stack, so we want to be sure
# to stop at the correct position.
if (is.function(currentCall[[1]])) {
identical(deparse(errorCall), deparse(currentCall[[1]]))
} else if (currentCall[[1]] == "stop") {
# handle case where function developer deliberately invokes a stop
# condition and halts function execution
TRUE
} else {
FALSE
}
}))
# the position to stop at is one less than the difference
# between the total number of calls and the index of the
# call throwing the error
stopIndex <- length(calls) - indexFromLast + 1
startIndex <- match(TRUE, lapply(functionsAsList, function(fn) fn == "getStackTrace"))
functionsAsList <- functionsAsList[seq(startIndex, stopIndex)]
functionsAsList <- removeHandlers(functionsAsList)
}
warning(call. = FALSE, immediate. = TRUE, sprintf("Execution error in %s: %s",
functionsAsList[[length(functionsAsList)]],
conditionMessage(e)))
stack_message <- stackTraceToHTML(functionsAsList,
functionsAsList[[length(functionsAsList)]],
conditionMessage(e))
assign("stack_message", value=stack_message,
envir=sys.frame(countEnclosingFrames("private"))$private)