This commit is contained in:
2025-05-09 05:30:08 +02:00
parent 7bb10e7df4
commit 73367bad9e
5322 changed files with 1266973 additions and 313 deletions

View File

@@ -0,0 +1,25 @@
import { defaultSerializeError } from "./router.js";
const TSR_DEFERRED_PROMISE = Symbol.for("TSR_DEFERRED_PROMISE");
function defer(_promise, options) {
const promise = _promise;
if (promise[TSR_DEFERRED_PROMISE]) {
return promise;
}
promise[TSR_DEFERRED_PROMISE] = { status: "pending" };
promise.then((data) => {
promise[TSR_DEFERRED_PROMISE].status = "success";
promise[TSR_DEFERRED_PROMISE].data = data;
}).catch((error) => {
promise[TSR_DEFERRED_PROMISE].status = "error";
promise[TSR_DEFERRED_PROMISE].error = {
data: ((options == null ? void 0 : options.serializeError) ?? defaultSerializeError)(error),
__isServerError: true
};
});
return promise;
}
export {
TSR_DEFERRED_PROMISE,
defer
};
//# sourceMappingURL=defer.js.map

View File

@@ -0,0 +1,65 @@
{
"name": "@humanwhocodes/module-importer",
"version": "1.0.1",
"description": "Universal module importer for Node.js",
"main": "src/module-importer.cjs",
"module": "src/module-importer.js",
"type": "module",
"types": "dist/module-importer.d.ts",
"exports": {
"require": "./src/module-importer.cjs",
"import": "./src/module-importer.js"
},
"files": [
"dist",
"src"
],
"publishConfig": {
"access": "public"
},
"gitHooks": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.js": [
"eslint --fix"
]
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/nzakas"
},
"scripts": {
"build": "rollup -c && tsc",
"prepare": "npm run build",
"lint": "eslint src/ tests/",
"test:unit": "c8 mocha tests/module-importer.test.js",
"test:build": "node tests/pkg.test.cjs && node tests/pkg.test.mjs",
"test": "npm run test:unit && npm run test:build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/humanwhocodes/module-importer.git"
},
"keywords": [
"modules",
"esm",
"commonjs"
],
"engines": {
"node": ">=12.22"
},
"author": "Nicholas C. Zaks",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^18.7.6",
"c8": "7.12.0",
"chai": "4.3.6",
"eslint": "8.22.0",
"lint-staged": "13.0.3",
"mocha": "9.2.2",
"rollup": "2.78.0",
"typescript": "4.7.4",
"yorkie": "2.0.0"
}
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"F A B","2":"K D mC","132":"E"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"0 1 2 3 4 5 6 7 8 9 nC LC J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC qC rC"},D:{"1":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC"},E:{"1":"J PB K D E F A B C L M G sC SC tC uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C"},F:{"1":"0 1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 4C 5C 6C 7C FC kC 8C GC"},G:{"1":"E SC 9C lC AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC"},H:{"1":"WD"},I:{"1":"LC J I XD YD ZD aD lC bD cD"},J:{"1":"D A"},K:{"1":"A B C H FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:2,C:"CSS Generated content for pseudo-elements",D:true};

View File

@@ -0,0 +1,938 @@
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
#include "Canvas.h"
#include "InstanceData.h"
#include <algorithm> // std::min
#include <assert.h>
#include <cairo-pdf.h>
#include <cairo-svg.h>
#include "CanvasRenderingContext2d.h"
#include "closure.h"
#include <cstring>
#include <cctype>
#include <ctime>
#include <glib.h>
#include "PNG.h"
#include "register_font.h"
#include <sstream>
#include <stdlib.h>
#include <string>
#include <unordered_set>
#include "Util.h"
#include <vector>
#include "node_buffer.h"
#include "FontParser.h"
#ifdef HAVE_JPEG
#include "JPEGStream.h"
#endif
#include "backend/ImageBackend.h"
#include "backend/PdfBackend.h"
#include "backend/SvgBackend.h"
#define GENERIC_FACE_ERROR \
"The second argument to registerFont is required, and should be an object " \
"with at least a family (string) and optionally weight (string/number) " \
"and style (string)."
using namespace std;
std::vector<FontFace> Canvas::font_face_list;
// Increases each time a font is (de)registered
int Canvas::fontSerial = 1;
/*
* Initialize Canvas.
*/
void
Canvas::Initialize(Napi::Env& env, Napi::Object& exports) {
Napi::HandleScope scope(env);
InstanceData* data = env.GetInstanceData<InstanceData>();
// Constructor
Napi::Function ctor = DefineClass(env, "Canvas", {
InstanceMethod<&Canvas::ToBuffer>("toBuffer", napi_default_method),
InstanceMethod<&Canvas::StreamPNGSync>("streamPNGSync", napi_default_method),
InstanceMethod<&Canvas::StreamPDFSync>("streamPDFSync", napi_default_method),
#ifdef HAVE_JPEG
InstanceMethod<&Canvas::StreamJPEGSync>("streamJPEGSync", napi_default_method),
#endif
InstanceAccessor<&Canvas::GetType>("type", napi_default_jsproperty),
InstanceAccessor<&Canvas::GetStride>("stride", napi_default_jsproperty),
InstanceAccessor<&Canvas::GetWidth, &Canvas::SetWidth>("width", napi_default_jsproperty),
InstanceAccessor<&Canvas::GetHeight, &Canvas::SetHeight>("height", napi_default_jsproperty),
StaticValue("PNG_NO_FILTERS", Napi::Number::New(env, PNG_NO_FILTERS), napi_default_jsproperty),
StaticValue("PNG_FILTER_NONE", Napi::Number::New(env, PNG_FILTER_NONE), napi_default_jsproperty),
StaticValue("PNG_FILTER_SUB", Napi::Number::New(env, PNG_FILTER_SUB), napi_default_jsproperty),
StaticValue("PNG_FILTER_UP", Napi::Number::New(env, PNG_FILTER_UP), napi_default_jsproperty),
StaticValue("PNG_FILTER_AVG", Napi::Number::New(env, PNG_FILTER_AVG), napi_default_jsproperty),
StaticValue("PNG_FILTER_PAETH", Napi::Number::New(env, PNG_FILTER_PAETH), napi_default_jsproperty),
StaticValue("PNG_ALL_FILTERS", Napi::Number::New(env, PNG_ALL_FILTERS), napi_default_jsproperty),
StaticMethod<&Canvas::RegisterFont>("_registerFont", napi_default_method),
StaticMethod<&Canvas::DeregisterAllFonts>("_deregisterAllFonts", napi_default_method),
StaticMethod<&Canvas::ParseFont>("parseFont", napi_default_method)
});
data->CanvasCtor = Napi::Persistent(ctor);
exports.Set("Canvas", ctor);
}
/*
* Initialize a Canvas with the given width and height.
*/
Canvas::Canvas(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Canvas>(info), env(info.Env()) {
InstanceData* data = env.GetInstanceData<InstanceData>();
ctor = Napi::Persistent(data->CanvasCtor.Value());
Backend* backend = NULL;
Napi::Object jsBackend;
if (info[0].IsNumber()) {
Napi::Number width = info[0].As<Napi::Number>();
Napi::Number height = Napi::Number::New(env, 0);
if (info[1].IsNumber()) height = info[1].As<Napi::Number>();
if (info[2].IsString()) {
std::string str = info[2].As<Napi::String>();
if (str == "pdf") {
Napi::Maybe<Napi::Object> instance = data->PdfBackendCtor.New({ width, height });
if (instance.IsJust()) backend = PdfBackend::Unwrap(jsBackend = instance.Unwrap());
} else if (str == "svg") {
Napi::Maybe<Napi::Object> instance = data->SvgBackendCtor.New({ width, height });
if (instance.IsJust()) backend = SvgBackend::Unwrap(jsBackend = instance.Unwrap());
} else {
Napi::Maybe<Napi::Object> instance = data->ImageBackendCtor.New({ width, height });
if (instance.IsJust()) backend = ImageBackend::Unwrap(jsBackend = instance.Unwrap());
}
} else {
Napi::Maybe<Napi::Object> instance = data->ImageBackendCtor.New({ width, height });
if (instance.IsJust()) backend = ImageBackend::Unwrap(jsBackend = instance.Unwrap());
}
} else if (info[0].IsObject()) {
jsBackend = info[0].As<Napi::Object>();
if (jsBackend.InstanceOf(data->ImageBackendCtor.Value()).UnwrapOr(false)) {
backend = ImageBackend::Unwrap(jsBackend);
} else if (jsBackend.InstanceOf(data->PdfBackendCtor.Value()).UnwrapOr(false)) {
backend = PdfBackend::Unwrap(jsBackend);
} else if (jsBackend.InstanceOf(data->SvgBackendCtor.Value()).UnwrapOr(false)) {
backend = SvgBackend::Unwrap(jsBackend);
} else {
Napi::TypeError::New(env, "Invalid arguments").ThrowAsJavaScriptException();
return;
}
} else {
Napi::Number width = Napi::Number::New(env, 0);
Napi::Number height = Napi::Number::New(env, 0);
Napi::Maybe<Napi::Object> instance = data->ImageBackendCtor.New({ width, height });
if (instance.IsJust()) backend = ImageBackend::Unwrap(jsBackend = instance.Unwrap());
}
if (!backend->isSurfaceValid()) {
Napi::Error::New(env, backend->getError()).ThrowAsJavaScriptException();
return;
}
backend->setCanvas(this);
// Note: the backend gets destroyed when the jsBackend is GC'd. The cleaner
// way would be to only store the jsBackend and unwrap it when the c++ ref is
// needed, but that's slower and a burden. The _backend might be null if we
// returned early, but since an exception was thrown it gets destroyed soon.
_backend = backend;
_jsBackend = Napi::Persistent(jsBackend);
}
/*
* Get type string.
*/
Napi::Value
Canvas::GetType(const Napi::CallbackInfo& info) {
return Napi::String::New(env, backend()->getName());
}
/*
* Get stride.
*/
Napi::Value
Canvas::GetStride(const Napi::CallbackInfo& info) {
return Napi::Number::New(env, stride());
}
/*
* Get width.
*/
Napi::Value
Canvas::GetWidth(const Napi::CallbackInfo& info) {
return Napi::Number::New(env, getWidth());
}
/*
* Set width.
*/
void
Canvas::SetWidth(const Napi::CallbackInfo& info, const Napi::Value& value) {
if (value.IsNumber()) {
backend()->setWidth(value.As<Napi::Number>().Uint32Value());
resurface(info.This().As<Napi::Object>());
}
}
/*
* Get height.
*/
Napi::Value
Canvas::GetHeight(const Napi::CallbackInfo& info) {
return Napi::Number::New(env, getHeight());
}
/*
* Set height.
*/
void
Canvas::SetHeight(const Napi::CallbackInfo& info, const Napi::Value& value) {
if (value.IsNumber()) {
backend()->setHeight(value.As<Napi::Number>().Uint32Value());
resurface(info.This().As<Napi::Object>());
}
}
/*
* EIO toBuffer callback.
*/
void
Canvas::ToPngBufferAsync(Closure* base) {
PngClosure* closure = static_cast<PngClosure*>(base);
closure->status = canvas_write_to_png_stream(
closure->canvas->surface(),
PngClosure::writeVec,
closure);
}
#ifdef HAVE_JPEG
void
Canvas::ToJpegBufferAsync(Closure* base) {
JpegClosure* closure = static_cast<JpegClosure*>(base);
write_to_jpeg_buffer(closure->canvas->surface(), closure);
}
#endif
static void
parsePNGArgs(Napi::Value arg, PngClosure& pngargs) {
if (arg.IsObject()) {
Napi::Object obj = arg.As<Napi::Object>();
Napi::Value cLevel;
if (obj.Get("compressionLevel").UnwrapTo(&cLevel) && cLevel.IsNumber()) {
uint32_t val = cLevel.As<Napi::Number>().Uint32Value();
// See quote below from spec section 4.12.5.5.
if (val <= 9) pngargs.compressionLevel = val;
}
Napi::Value rez;
if (obj.Get("resolution").UnwrapTo(&rez) && rez.IsNumber()) {
uint32_t val = rez.As<Napi::Number>().Uint32Value();
if (val > 0) pngargs.resolution = val;
}
Napi::Value filters;
if (obj.Get("filters").UnwrapTo(&filters) && filters.IsNumber()) {
pngargs.filters = filters.As<Napi::Number>().Uint32Value();
}
Napi::Value palette;
if (obj.Get("palette").UnwrapTo(&palette) && palette.IsTypedArray()) {
Napi::TypedArray palette_ta = palette.As<Napi::TypedArray>();
if (palette_ta.TypedArrayType() == napi_uint8_clamped_array) {
pngargs.nPaletteColors = palette_ta.ElementLength();
if (pngargs.nPaletteColors % 4 != 0) {
throw "Palette length must be a multiple of 4.";
}
pngargs.palette = palette_ta.As<Napi::Uint8Array>().Data();
pngargs.nPaletteColors /= 4;
// Optional background color index:
Napi::Value backgroundIndexVal;
if (obj.Get("backgroundIndex").UnwrapTo(&backgroundIndexVal) && backgroundIndexVal.IsNumber()) {
pngargs.backgroundIndex = backgroundIndexVal.As<Napi::Number>().Uint32Value();
}
}
}
}
}
#ifdef HAVE_JPEG
static void parseJPEGArgs(Napi::Value arg, JpegClosure& jpegargs) {
// "If Type(quality) is not Number, or if quality is outside that range, the
// user agent must use its default quality value, as if the quality argument
// had not been given." - 4.12.5.5
if (arg.IsObject()) {
Napi::Object obj = arg.As<Napi::Object>();
Napi::Value qual;
if (obj.Get("quality").UnwrapTo(&qual) && qual.IsNumber()) {
double quality = qual.As<Napi::Number>().DoubleValue();
if (quality >= 0.0 && quality <= 1.0) {
jpegargs.quality = static_cast<uint32_t>(100.0 * quality);
}
}
Napi::Value chroma;
if (obj.Get("chromaSubsampling").UnwrapTo(&chroma)) {
if (chroma.IsBoolean()) {
bool subsample = chroma.As<Napi::Boolean>().Value();
jpegargs.chromaSubsampling = subsample ? 2 : 1;
} else if (chroma.IsNumber()) {
jpegargs.chromaSubsampling = chroma.As<Napi::Number>().Uint32Value();
}
}
Napi::Value progressive;
if (obj.Get("progressive").UnwrapTo(&progressive) && progressive.IsBoolean()) {
jpegargs.progressive = progressive.As<Napi::Boolean>().Value();
}
}
}
#endif
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
static inline void setPdfMetaStr(cairo_surface_t* surf, Napi::Object opts,
cairo_pdf_metadata_t t, const char* propName) {
Napi::Value propValue;
if (opts.Get(propName).UnwrapTo(&propValue) && propValue.IsString()) {
// (copies char data)
cairo_pdf_surface_set_metadata(surf, t, propValue.As<Napi::String>().Utf8Value().c_str());
}
}
static inline void setPdfMetaDate(cairo_surface_t* surf, Napi::Object opts,
cairo_pdf_metadata_t t, const char* propName) {
Napi::Value propValue;
if (opts.Get(propName).UnwrapTo(&propValue) && propValue.IsDate()) {
auto date = static_cast<time_t>(propValue.As<Napi::Date>().ValueOf() / 1000); // ms -> s
char buf[sizeof "2011-10-08T07:07:09Z"];
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&date));
cairo_pdf_surface_set_metadata(surf, t, buf);
}
}
static void setPdfMetadata(Canvas* canvas, Napi::Object opts) {
cairo_surface_t* surf = canvas->surface();
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_TITLE, "title");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_AUTHOR, "author");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_SUBJECT, "subject");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_KEYWORDS, "keywords");
setPdfMetaStr(surf, opts, CAIRO_PDF_METADATA_CREATOR, "creator");
setPdfMetaDate(surf, opts, CAIRO_PDF_METADATA_CREATE_DATE, "creationDate");
setPdfMetaDate(surf, opts, CAIRO_PDF_METADATA_MOD_DATE, "modDate");
}
#endif // CAIRO 16+
/*
* Converts/encodes data to a Buffer. Async when a callback function is passed.
* PDF canvases:
(any) => Buffer
("application/pdf", config) => Buffer
* SVG canvases:
(any) => Buffer
* ARGB data:
("raw") => Buffer
* PNG-encoded
() => Buffer
(undefined|"image/png", {compressionLevel?: number, filter?: number}) => Buffer
((err: null|Error, buffer) => any)
((err: null|Error, buffer) => any, undefined|"image/png", {compressionLevel?: number, filter?: number})
* JPEG-encoded
("image/jpeg") => Buffer
("image/jpeg", {quality?: number, progressive?: Boolean, chromaSubsampling?: Boolean|number}) => Buffer
((err: null|Error, buffer) => any, "image/jpeg")
((err: null|Error, buffer) => any, "image/jpeg", {quality?: number, progressive?: Boolean, chromaSubsampling?: Boolean|number})
*/
Napi::Value
Canvas::ToBuffer(const Napi::CallbackInfo& info) {
EncodingWorker *worker = new EncodingWorker(info.Env());
cairo_status_t status;
// Vector canvases, sync only
const std::string name = backend()->getName();
if (name == "pdf" || name == "svg") {
// mime type may be present, but it's not checked
PdfSvgClosure* closure;
if (name == "pdf") {
closure = static_cast<PdfBackend*>(backend())->closure();
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
if (info[1].IsObject()) { // toBuffer("application/pdf", config)
setPdfMetadata(this, info[1].As<Napi::Object>());
}
#endif // CAIRO 16+
} else {
closure = static_cast<SvgBackend*>(backend())->closure();
}
cairo_surface_t *surf = surface();
cairo_surface_finish(surf);
cairo_status_t status = cairo_surface_status(surf);
if (status != CAIRO_STATUS_SUCCESS) {
Napi::Error::New(env, cairo_status_to_string(status)).ThrowAsJavaScriptException();
return env.Undefined();
}
return Napi::Buffer<uint8_t>::Copy(env, &closure->vec[0], closure->vec.size());
}
// Raw ARGB data -- just a memcpy()
if (info[0].StrictEquals(Napi::String::New(env, "raw"))) {
cairo_surface_t *surface = this->surface();
cairo_surface_flush(surface);
if (nBytes() > node::Buffer::kMaxLength) {
Napi::Error::New(env, "Data exceeds maximum buffer length.").ThrowAsJavaScriptException();
return env.Undefined();
}
return Napi::Buffer<uint8_t>::Copy(env, cairo_image_surface_get_data(surface), nBytes());
}
// Sync PNG, default
if (info[0].IsUndefined() || info[0].StrictEquals(Napi::String::New(env, "image/png"))) {
try {
PngClosure closure(this);
parsePNGArgs(info[1], closure);
if (closure.nPaletteColors == 0xFFFFFFFF) {
Napi::Error::New(env, "Palette length must be a multiple of 4.").ThrowAsJavaScriptException();
return env.Undefined();
}
status = canvas_write_to_png_stream(surface(), PngClosure::writeVec, &closure);
if (!env.IsExceptionPending()) {
if (status) {
throw status; // TODO: throw in js?
} else {
// TODO it's possible to avoid this copy
return Napi::Buffer<uint8_t>::Copy(env, &closure.vec[0], closure.vec.size());
}
}
} catch (cairo_status_t ex) {
CairoError(ex).ThrowAsJavaScriptException();
} catch (const char* ex) {
Napi::Error::New(env, ex).ThrowAsJavaScriptException();
}
return env.Undefined();
}
// Async PNG
if (info[0].IsFunction() &&
(info[1].IsUndefined() || info[1].StrictEquals(Napi::String::New(env, "image/png")))) {
PngClosure* closure;
try {
closure = new PngClosure(this);
parsePNGArgs(info[2], *closure);
} catch (cairo_status_t ex) {
CairoError(ex).ThrowAsJavaScriptException();
return env.Undefined();
} catch (const char* ex) {
Napi::Error::New(env, ex).ThrowAsJavaScriptException();
return env.Undefined();
}
Ref();
closure->cb = Napi::Persistent(info[0].As<Napi::Function>());
// Make sure the surface exists since we won't have an isolate context in the async block:
surface();
worker->Init(&ToPngBufferAsync, closure);
worker->Queue();
return env.Undefined();
}
#ifdef HAVE_JPEG
// Sync JPEG
Napi::Value jpegStr = Napi::String::New(env, "image/jpeg");
if (info[0].StrictEquals(jpegStr)) {
try {
JpegClosure closure(this);
parseJPEGArgs(info[1], closure);
write_to_jpeg_buffer(surface(), &closure);
if (!env.IsExceptionPending()) {
// TODO it's possible to avoid this copy.
return Napi::Buffer<uint8_t>::Copy(env, &closure.vec[0], closure.vec.size());
}
} catch (cairo_status_t ex) {
CairoError(ex).ThrowAsJavaScriptException();
return env.Undefined();
}
return env.Undefined();
}
// Async JPEG
if (info[0].IsFunction() && info[1].StrictEquals(jpegStr)) {
JpegClosure* closure = new JpegClosure(this);
parseJPEGArgs(info[2], *closure);
Ref();
closure->cb = Napi::Persistent(info[0].As<Napi::Function>());
// Make sure the surface exists since we won't have an isolate context in the async block:
surface();
worker->Init(&ToJpegBufferAsync, closure);
worker->Queue();
return env.Undefined();
}
#endif
return env.Undefined();
}
/*
* Canvas::StreamPNG callback.
*/
static cairo_status_t
streamPNG(void *c, const uint8_t *data, unsigned len) {
PngClosure* closure = (PngClosure*) c;
Napi::Env env = closure->canvas->env;
Napi::HandleScope scope(env);
Napi::AsyncContext async(env, "canvas:StreamPNG");
Napi::Value buf = Napi::Buffer<uint8_t>::Copy(env, data, len);
closure->cb.MakeCallback(env.Global(), { env.Null(), buf, Napi::Number::New(env, len) }, async);
return CAIRO_STATUS_SUCCESS;
}
/*
* Stream PNG data synchronously. TODO async
* StreamPngSync(this, options: {palette?: Uint8ClampedArray, backgroundIndex?: uint32, compressionLevel: uint32, filters: uint32})
*/
void
Canvas::StreamPNGSync(const Napi::CallbackInfo& info) {
if (!info[0].IsFunction()) {
Napi::TypeError::New(env, "callback function required").ThrowAsJavaScriptException();
return;
}
PngClosure closure(this);
parsePNGArgs(info[1], closure);
closure.cb = Napi::Persistent(info[0].As<Napi::Function>());
cairo_status_t status = canvas_write_to_png_stream(surface(), streamPNG, &closure);
if (!env.IsExceptionPending()) {
if (status) {
closure.cb.Call(env.Global(), { CairoError(status).Value() });
} else {
closure.cb.Call(env.Global(), { env.Null(), env.Null(), Napi::Number::New(env, 0) });
}
}
}
struct PdfStreamInfo {
Napi::Function fn;
uint32_t len;
uint8_t* data;
};
/*
* Canvas::StreamPDF callback.
*/
static cairo_status_t
streamPDF(void *c, const uint8_t *data, unsigned len) {
PdfStreamInfo* streaminfo = static_cast<PdfStreamInfo*>(c);
Napi::Env env = streaminfo->fn.Env();
Napi::HandleScope scope(env);
Napi::AsyncContext async(env, "canvas:StreamPDF");
// TODO this is technically wrong, we're returning a pointer to the data in a
// vector in a class with automatic storage duration. If the canvas goes out
// of scope while we're in the handler, a use-after-free could happen.
Napi::Value buf = Napi::Buffer<uint8_t>::New(env, (uint8_t *)(data), len);
streaminfo->fn.MakeCallback(env.Global(), { env.Null(), buf, Napi::Number::New(env, len) }, async);
return CAIRO_STATUS_SUCCESS;
}
cairo_status_t canvas_write_to_pdf_stream(cairo_surface_t *surface, cairo_write_func_t write_func, PdfStreamInfo* streaminfo) {
size_t whole_chunks = streaminfo->len / PAGE_SIZE;
size_t remainder = streaminfo->len - whole_chunks * PAGE_SIZE;
for (size_t i = 0; i < whole_chunks; ++i) {
write_func(streaminfo, &streaminfo->data[i * PAGE_SIZE], PAGE_SIZE);
}
if (remainder) {
write_func(streaminfo, &streaminfo->data[whole_chunks * PAGE_SIZE], remainder);
}
return CAIRO_STATUS_SUCCESS;
}
/*
* Stream PDF data synchronously.
*/
void
Canvas::StreamPDFSync(const Napi::CallbackInfo& info) {
if (!info[0].IsFunction()) {
Napi::TypeError::New(env, "callback function required").ThrowAsJavaScriptException();
return;
}
if (backend()->getName() != "pdf") {
Napi::TypeError::New(env, "wrong canvas type").ThrowAsJavaScriptException();
return;
}
#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0)
if (info[1].IsObject()) {
setPdfMetadata(this, info[1].As<Napi::Object>());
}
#endif
cairo_surface_finish(surface());
PdfSvgClosure* closure = static_cast<PdfBackend*>(backend())->closure();
Napi::Function fn = info[0].As<Napi::Function>();
PdfStreamInfo streaminfo;
streaminfo.fn = fn;
streaminfo.data = &closure->vec[0];
streaminfo.len = closure->vec.size();
cairo_status_t status = canvas_write_to_pdf_stream(surface(), streamPDF, &streaminfo);
if (!env.IsExceptionPending()) {
if (status) {
fn.Call(env.Global(), { CairoError(status).Value() });
} else {
fn.Call(env.Global(), { env.Null(), env.Null(), Napi::Number::New(env, 0) });
}
}
}
/*
* Stream JPEG data synchronously.
*/
#ifdef HAVE_JPEG
static uint32_t getSafeBufSize(Canvas* canvas) {
// Don't allow the buffer size to exceed the size of the canvas (#674)
// TODO not sure if this is really correct, but it fixed #674
return (std::min)(canvas->getWidth() * canvas->getHeight() * 4, static_cast<int>(PAGE_SIZE));
}
void
Canvas::StreamJPEGSync(const Napi::CallbackInfo& info) {
if (!info[1].IsFunction()) {
Napi::TypeError::New(env, "callback function required").ThrowAsJavaScriptException();
return;
}
JpegClosure closure(this);
parseJPEGArgs(info[0], closure);
closure.cb = Napi::Persistent(info[1].As<Napi::Function>());
uint32_t bufsize = getSafeBufSize(this);
write_to_jpeg_stream(surface(), bufsize, &closure);
}
#endif
char *
str_value(Napi::Maybe<Napi::Value> maybe, const char *fallback, bool can_be_number) {
Napi::Value val;
if (maybe.UnwrapTo(&val)) {
if (val.IsString() || (can_be_number && val.IsNumber())) {
Napi::String strVal;
if (val.ToString().UnwrapTo(&strVal)) return strdup(strVal.Utf8Value().c_str());
} else if (fallback) {
return strdup(fallback);
}
}
return NULL;
}
void
Canvas::RegisterFont(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (!info[0].IsString()) {
Napi::Error::New(env, "Wrong argument type").ThrowAsJavaScriptException();
return;
} else if (!info[1].IsObject()) {
Napi::Error::New(env, GENERIC_FACE_ERROR).ThrowAsJavaScriptException();
return;
}
std::string filePath = info[0].As<Napi::String>();
PangoFontDescription *sys_desc = get_pango_font_description((unsigned char *)(filePath.c_str()));
if (!sys_desc) {
Napi::Error::New(env, "Could not parse font file").ThrowAsJavaScriptException();
return;
}
PangoFontDescription *user_desc = pango_font_description_new();
// now check the attrs, there are many ways to be wrong
Napi::Object js_user_desc = info[1].As<Napi::Object>();
// TODO: use FontParser on these values just like the FontFace API works
char *family = str_value(js_user_desc.Get("family"), NULL, false);
char *weight = str_value(js_user_desc.Get("weight"), "normal", true);
char *style = str_value(js_user_desc.Get("style"), "normal", false);
if (family && weight && style) {
pango_font_description_set_weight(user_desc, Canvas::GetWeightFromCSSString(weight));
pango_font_description_set_style(user_desc, Canvas::GetStyleFromCSSString(style));
pango_font_description_set_family(user_desc, family);
auto found = std::find_if(font_face_list.begin(), font_face_list.end(), [&](FontFace& f) {
return pango_font_description_equal(f.sys_desc, sys_desc);
});
if (found != font_face_list.end()) {
pango_font_description_free(found->user_desc);
found->user_desc = user_desc;
} else if (register_font((unsigned char *) filePath.c_str())) {
FontFace face;
face.user_desc = user_desc;
face.sys_desc = sys_desc;
strncpy((char *)face.file_path, (char *) filePath.c_str(), 1023);
font_face_list.push_back(face);
} else {
pango_font_description_free(user_desc);
Napi::Error::New(env, "Could not load font to the system's font host").ThrowAsJavaScriptException();
}
} else {
pango_font_description_free(user_desc);
if (!env.IsExceptionPending()) {
Napi::Error::New(env, GENERIC_FACE_ERROR).ThrowAsJavaScriptException();
}
}
free(family);
free(weight);
free(style);
fontSerial++;
}
void
Canvas::DeregisterAllFonts(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
// Unload all fonts from pango to free up memory
bool success = true;
std::for_each(font_face_list.begin(), font_face_list.end(), [&](FontFace& f) {
if (!deregister_font( (unsigned char *)f.file_path )) success = false;
pango_font_description_free(f.user_desc);
pango_font_description_free(f.sys_desc);
});
font_face_list.clear();
fontSerial++;
if (!success) Napi::Error::New(env, "Could not deregister one or more fonts").ThrowAsJavaScriptException();
}
/*
* Do not use! This is only exported for testing
*/
Napi::Value
Canvas::ParseFont(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() != 1) return env.Undefined();
Napi::String str;
if (!info[0].ToString().UnwrapTo(&str)) return env.Undefined();
bool ok;
auto props = FontParser::parse(str, &ok);
if (!ok) return env.Undefined();
Napi::Object obj = Napi::Object::New(env);
obj.Set("size", Napi::Number::New(env, props.fontSize));
Napi::Array families = Napi::Array::New(env);
obj.Set("families", families);
unsigned int index = 0;
for (auto& family : props.fontFamily) {
families[index++] = Napi::String::New(env, family);
}
obj.Set("weight", Napi::Number::New(env, props.fontWeight));
obj.Set("variant", Napi::Number::New(env, static_cast<int>(props.fontVariant)));
obj.Set("style", Napi::Number::New(env, static_cast<int>(props.fontStyle)));
return obj;
}
/*
* Get a PangoStyle from a CSS string (like "italic")
*/
PangoStyle
Canvas::GetStyleFromCSSString(const char *style) {
PangoStyle s = PANGO_STYLE_NORMAL;
if (strlen(style) > 0) {
if (0 == strcmp("italic", style)) {
s = PANGO_STYLE_ITALIC;
} else if (0 == strcmp("oblique", style)) {
s = PANGO_STYLE_OBLIQUE;
}
}
return s;
}
/*
* Get a PangoWeight from a CSS string ("bold", "100", etc)
*/
PangoWeight
Canvas::GetWeightFromCSSString(const char *weight) {
PangoWeight w = PANGO_WEIGHT_NORMAL;
if (strlen(weight) > 0) {
if (0 == strcmp("bold", weight)) {
w = PANGO_WEIGHT_BOLD;
} else if (0 == strcmp("100", weight)) {
w = PANGO_WEIGHT_THIN;
} else if (0 == strcmp("200", weight)) {
w = PANGO_WEIGHT_ULTRALIGHT;
} else if (0 == strcmp("300", weight)) {
w = PANGO_WEIGHT_LIGHT;
} else if (0 == strcmp("400", weight)) {
w = PANGO_WEIGHT_NORMAL;
} else if (0 == strcmp("500", weight)) {
w = PANGO_WEIGHT_MEDIUM;
} else if (0 == strcmp("600", weight)) {
w = PANGO_WEIGHT_SEMIBOLD;
} else if (0 == strcmp("700", weight)) {
w = PANGO_WEIGHT_BOLD;
} else if (0 == strcmp("800", weight)) {
w = PANGO_WEIGHT_ULTRABOLD;
} else if (0 == strcmp("900", weight)) {
w = PANGO_WEIGHT_HEAVY;
}
}
return w;
}
/*
* Given a user description, return a description that will select the
* font either from the system or @font-face
*/
PangoFontDescription *
Canvas::ResolveFontDescription(const PangoFontDescription *desc) {
// One of the user-specified families could map to multiple SFNT family names
// if someone registered two different fonts under the same family name.
// https://drafts.csswg.org/css-fonts-3/#font-style-matching
FontFace best;
istringstream families(pango_font_description_get_family(desc));
unordered_set<string> seen_families;
string resolved_families;
bool first = true;
for (string family; getline(families, family, ','); ) {
string renamed_families;
for (auto& ff : font_face_list) {
string pangofamily = string(pango_font_description_get_family(ff.user_desc));
if (streq_casein(family, pangofamily)) {
const char* sys_desc_family_name = pango_font_description_get_family(ff.sys_desc);
bool unseen = seen_families.find(sys_desc_family_name) == seen_families.end();
bool better = best.user_desc == nullptr || pango_font_description_better_match(desc, best.user_desc, ff.user_desc);
// Avoid sending duplicate SFNT font names due to a bug in Pango for macOS:
// https://bugzilla.gnome.org/show_bug.cgi?id=762873
if (unseen) {
seen_families.insert(sys_desc_family_name);
if (better) {
renamed_families = string(sys_desc_family_name) + (renamed_families.size() ? "," : "") + renamed_families;
} else {
renamed_families = renamed_families + (renamed_families.size() ? "," : "") + sys_desc_family_name;
}
}
if (first && better) best = ff;
}
}
if (resolved_families.size()) resolved_families += ',';
resolved_families += renamed_families.size() ? renamed_families : family;
first = false;
}
PangoFontDescription* ret = pango_font_description_copy(best.sys_desc ? best.sys_desc : desc);
pango_font_description_set_family(ret, resolved_families.c_str());
return ret;
}
/*
* Re-alloc the surface, destroying the previous.
*/
void
Canvas::resurface(Napi::Object This) {
Napi::HandleScope scope(env);
Napi::Value context;
if (This.Get("context").UnwrapTo(&context) && context.IsObject()) {
backend()->recreateSurface();
// Reset context
Context2d *context2d = Context2d::Unwrap(context.As<Napi::Object>());
cairo_t *prev = context2d->context();
context2d->setContext(createCairoContext());
context2d->resetState();
cairo_destroy(prev);
}
}
/**
* Wrapper around cairo_create()
* (do not call cairo_create directly, call this instead)
*/
cairo_t*
Canvas::createCairoContext() {
cairo_t* ret = cairo_create(surface());
cairo_set_line_width(ret, 1); // Cairo defaults to 2
return ret;
}
/*
* Construct an Error from the given cairo status.
*/
Napi::Error
Canvas::CairoError(cairo_status_t status) {
return Napi::Error::New(env, cairo_status_to_string(status));
}

View File

@@ -0,0 +1 @@
module.exports={C:{"34":0.00259,"68":0.00259,"82":0.00259,"105":0.00518,"115":0.11137,"121":0.00259,"123":0.00259,"125":0.00259,"128":0.04921,"129":0.00259,"131":0.00259,"134":0.01036,"135":0.12691,"136":0.32375,_:"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 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 69 70 71 72 73 74 75 76 77 78 79 80 81 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 106 107 108 109 110 111 112 113 114 116 117 118 119 120 122 124 126 127 130 132 133 137 138 139 140 3.5 3.6"},D:{"34":0.00259,"38":0.00259,"39":0.00259,"40":0.00518,"41":0.00259,"42":0.00259,"43":0.00259,"44":0.00259,"45":0.00259,"46":0.00518,"47":0.00259,"48":0.00259,"49":0.01036,"50":0.00518,"51":0.00259,"52":0.00259,"53":0.00518,"54":0.00259,"55":0.00777,"56":0.00518,"57":0.00259,"58":0.00518,"59":0.00518,"60":0.00259,"65":0.00259,"66":0.00259,"68":0.00259,"69":0.00777,"70":0.01036,"72":0.00259,"73":0.00518,"74":0.00518,"75":0.00259,"77":0.00259,"78":0.00259,"79":0.16576,"80":0.00259,"81":0.00259,"83":0.03626,"84":0.00259,"85":0.00259,"86":0.01036,"87":0.08806,"88":0.01295,"89":0.02072,"90":0.01036,"91":0.00518,"92":0.00259,"94":0.05439,"95":0.00259,"97":0.00259,"98":0.00777,"99":0.00259,"100":0.01554,"101":0.00518,"102":0.00777,"103":0.00777,"104":0.00259,"105":0.00259,"106":0.0259,"107":0.00518,"108":0.03108,"109":2.22999,"110":0.02331,"111":0.02331,"112":0.00777,"113":0.00518,"114":0.00777,"115":0.00777,"116":0.01295,"117":0.00259,"118":0.02072,"119":0.01554,"120":0.24605,"121":0.01813,"122":0.06216,"123":0.02072,"124":0.01813,"125":0.13727,"126":0.04921,"127":0.02072,"128":0.03367,"129":0.03367,"130":0.0518,"131":0.13986,"132":0.20202,"133":5.15928,"134":9.10126,"135":0.01554,_:"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 35 36 37 61 62 63 64 67 71 76 93 96 136 137 138"},F:{"36":0.00518,"40":0.00259,"46":0.02331,"65":0.00259,"74":0.00259,"79":0.03108,"81":0.00259,"82":0.00259,"83":0.01036,"84":0.01295,"85":0.0518,"86":0.00259,"87":0.04403,"88":0.01036,"95":0.15281,"116":0.21756,"117":0.72779,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 37 38 39 41 42 43 44 45 47 48 49 50 51 52 53 54 55 56 57 58 60 62 63 64 66 67 68 69 70 71 72 73 75 76 77 78 80 89 90 91 92 93 94 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"18":0.00259,"89":0.00259,"92":0.01295,"107":0.00259,"109":0.01295,"114":0.01295,"115":0.00259,"122":0.00259,"125":0.00259,"126":0.00259,"127":0.00518,"128":0.00777,"129":0.00518,"130":0.00518,"131":0.01554,"132":0.01554,"133":0.4662,"134":1.03341,_:"12 13 14 15 16 17 79 80 81 83 84 85 86 87 88 90 91 93 94 95 96 97 98 99 100 101 102 103 104 105 106 108 110 111 112 113 116 117 118 119 120 121 123 124"},E:{"14":0.00259,_:"0 4 5 6 7 8 9 10 11 12 13 15 3.1 3.2 6.1 7.1 9.1 10.1 11.1 12.1 15.1 15.2-15.3 15.4 15.5 16.0 16.2","5.1":0.00777,"13.1":0.00518,"14.1":0.01295,"15.6":0.01813,"16.1":0.00518,"16.3":0.00518,"16.4":0.00518,"16.5":0.00518,"16.6":0.06734,"17.0":0.08806,"17.1":0.01036,"17.2":0.00518,"17.3":0.00777,"17.4":0.01036,"17.5":0.01554,"17.6":0.05698,"18.0":0.01295,"18.1":0.03626,"18.2":0.0259,"18.3":0.41958,"18.4":0.00777},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00201,"5.0-5.1":0,"6.0-6.1":0.00603,"7.0-7.1":0.00402,"8.1-8.4":0,"9.0-9.2":0.00301,"9.3":0.01407,"10.0-10.2":0.001,"10.3":0.02311,"11.0-11.2":0.10649,"11.3-11.4":0.00703,"12.0-12.1":0.00402,"12.2-12.5":0.09946,"13.0-13.1":0.00201,"13.2":0.00301,"13.3":0.00402,"13.4-13.7":0.01407,"14.0-14.4":0.03516,"14.5-14.8":0.0422,"15.0-15.1":0.02311,"15.2-15.3":0.02311,"15.4":0.02813,"15.5":0.03215,"15.6-15.8":0.39584,"16.0":0.05626,"16.1":0.11554,"16.2":0.06028,"16.3":0.10448,"16.4":0.02311,"16.5":0.0432,"16.6-16.7":0.46918,"17.0":0.02813,"17.1":0.05023,"17.2":0.03818,"17.3":0.05325,"17.4":0.10649,"17.5":0.2371,"17.6-17.7":0.68819,"18.0":0.19289,"18.1":0.63093,"18.2":0.28231,"18.3":5.90037,"18.4":0.08741},P:{"4":0.47754,"20":0.03048,"21":0.04064,"22":0.03048,"23":0.12192,"24":0.0508,"25":0.1016,"26":0.14224,"27":2.56041,"5.0-5.4":0.02032,"6.2-6.4":0.0508,"7.2-7.4":0.1016,_:"8.2 9.2 10.1 11.1-11.2 12.0 14.0 15.0","13.0":0.01016,"16.0":0.01016,"17.0":0.03048,"18.0":0.01016,"19.0":0.01016},I:{"0":0.03697,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0.00001,"4.4":0,"4.4.3-4.4.4":0.00004},K:{"0":1.0669,_:"10 11 12 11.1 11.5 12.1"},A:{"8":0.01295,"11":0.02072,_:"6 7 9 10 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.27413},Q:{_:"14.9"},O:{"0":0.11114},H:{"0":0},L:{"0":59.81202}};

View File

@@ -0,0 +1,3 @@
const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq

View File

@@ -0,0 +1,9 @@
import ws from "./ws";
const handler = {
scheme: "wss",
domainHost: ws.domainHost,
parse: ws.parse,
serialize: ws.serialize
};
export default handler;
//# sourceMappingURL=wss.js.map

View File

@@ -0,0 +1,11 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useOutlineContext;
const react_1 = require("react");
const OutlineContext_js_1 = __importDefault(require("../../OutlineContext.js"));
function useOutlineContext() {
return (0, react_1.useContext)(OutlineContext_js_1.default);
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"A B","2":"K D E mC","132":"F"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"nC LC","260":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB qC rC"},D:{"1":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC"},E:{"1":"PB K D E F A B C L M G tC uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","2":"J sC SC"},F:{"1":"0 1 2 3 4 5 6 7 8 G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","2":"F B C 4C 5C 6C 7C FC kC 8C GC"},G:{"16":"E SC 9C lC AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC"},H:{"2":"WD"},I:{"16":"LC J I XD YD ZD aD lC bD cD"},J:{"16":"D A"},K:{"1":"H","16":"A B C FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"B","2":"A"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD","16":"J"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:5,C:"Resource Hints: dns-prefetch",D:true};

View File

@@ -0,0 +1,831 @@
import { GeneratorOptions } from "@babel/generator";
import { ParserOptions } from "@babel/parser";
import template from "@babel/template";
import traverse, { Hub, NodePath, Scope, Visitor } from "@babel/traverse";
import * as t from "@babel/types";
export { GeneratorOptions, NodePath, ParserOptions, t as types, template, traverse, Visitor };
export type Node = t.Node;
export type ParseResult = ReturnType<typeof import("@babel/parser").parse>;
export const version: string;
export const DEFAULT_EXTENSIONS: [".js", ".jsx", ".es6", ".es", ".mjs"];
/**
* Source map standard format as to revision 3
* @see {@link https://sourcemaps.info/spec.html}
* @see {@link https://github.com/mozilla/source-map/blob/HEAD/source-map.d.ts}
*/
interface InputSourceMap {
version: number;
sources: string[];
names: string[];
sourceRoot?: string | undefined;
sourcesContent?: string[] | undefined;
mappings: string;
file: string;
}
export interface TransformOptions {
/**
* Specify which assumptions it can make about your code, to better optimize the compilation result. **NOTE**: This replaces the various `loose` options in plugins in favor of
* top-level options that can apply to multiple plugins
*
* @see https://babeljs.io/docs/en/assumptions
*/
assumptions?: { [name: string]: boolean } | null | undefined;
/**
* Include the AST in the returned object
*
* Default: `false`
*/
ast?: boolean | null | undefined;
/**
* Attach a comment after all non-user injected code
*
* Default: `null`
*/
auxiliaryCommentAfter?: string | null | undefined;
/**
* Attach a comment before all non-user injected code
*
* Default: `null`
*/
auxiliaryCommentBefore?: string | null | undefined;
/**
* Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of.
*
* Default: `"."`
*/
root?: string | null | undefined;
/**
* This option, combined with the "root" value, defines how Babel chooses its project root.
* The different modes define different ways that Babel can process the "root" value to get
* the final project root.
*
* @see https://babeljs.io/docs/en/next/options#rootmode
*/
rootMode?: "root" | "upward" | "upward-optional" | undefined;
/**
* The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files.
*
* Default: `undefined`
*/
configFile?: string | boolean | null | undefined;
/**
* Specify whether or not to use .babelrc and
* .babelignore files.
*
* Default: `true`
*/
babelrc?: boolean | null | undefined;
/**
* Specify which packages should be search for .babelrc files when they are being compiled. `true` to always search, or a path string or an array of paths to packages to search
* inside of. Defaults to only searching the "root" package.
*
* Default: `(root)`
*/
babelrcRoots?: boolean | MatchPattern | MatchPattern[] | null | undefined;
/**
* Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json.
* This is useful for projects that use a browserslist config for files that won't be compiled with Babel.
*
* If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies
* this option, or to `cwd` when it's passed as part of the programmatic options.
*
* Default: `true`
*/
browserslistConfigFile?: boolean | null | undefined;
/**
* The Browserslist environment to use.
*
* Default: `undefined`
*/
browserslistEnv?: string | null | undefined;
/**
* By default `babel.transformFromAst` will clone the input AST to avoid mutations.
* Specifying `cloneInputAst: false` can improve parsing performance if the input AST is not used elsewhere.
*
* Default: `true`
*/
cloneInputAst?: boolean | null | undefined;
/**
* Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"`
*
* Default: env vars
*/
envName?: string | undefined;
/**
* If any of patterns match, the current configuration object is considered inactive and is ignored during config processing.
*/
exclude?: MatchPattern | MatchPattern[] | undefined;
/**
* Enable code generation
*
* Default: `true`
*/
code?: boolean | null | undefined;
/**
* Output comments in generated output
*
* Default: `true`
*/
comments?: boolean | null | undefined;
/**
* Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB
*
* Default: `"auto"`
*/
compact?: boolean | "auto" | null | undefined;
/**
* The working directory that Babel's programmatic options are loaded relative to.
*
* Default: `"."`
*/
cwd?: string | null | undefined;
/**
* Utilities may pass a caller object to identify themselves to Babel and
* pass capability-related flags for use by configs, presets and plugins.
*
* @see https://babeljs.io/docs/en/next/options#caller
*/
caller?: TransformCaller | undefined;
/**
* This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }`
* which will use those options when the `envName` is `production`
*
* Default: `{}`
*/
env?: { [index: string]: TransformOptions | null | undefined } | null | undefined;
/**
* A path to a `.babelrc` file to extend
*
* Default: `null`
*/
extends?: string | null | undefined;
/**
* Filename for use in errors etc
*
* Default: `"unknown"`
*/
filename?: string | null | undefined;
/**
* Filename relative to `sourceRoot`
*
* Default: `(filename)`
*/
filenameRelative?: string | null | undefined;
/**
* An object containing the options to be passed down to the babel code generator, @babel/generator
*
* Default: `{}`
*/
generatorOpts?: GeneratorOptions | null | undefined;
/**
* Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used
*
* Default: `null`
*/
getModuleId?: ((moduleName: string) => string | null | undefined) | null | undefined;
/**
* ANSI highlight syntax error code frames
*
* Default: `true`
*/
highlightCode?: boolean | null | undefined;
/**
* Opposite to the `only` option. `ignore` is disregarded if `only` is specified
*
* Default: `null`
*/
ignore?: MatchPattern[] | null | undefined;
/**
* This option is a synonym for "test"
*/
include?: MatchPattern | MatchPattern[] | undefined;
/**
* A source map object that the output source map will be based on
*
* Default: `null`
*/
inputSourceMap?: InputSourceMap | null | undefined;
/**
* Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe)
*
* Default: `false`
*/
minified?: boolean | null | undefined;
/**
* Specify a custom name for module ids
*
* Default: `null`
*/
moduleId?: string | null | undefined;
/**
* If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules)
*
* Default: `false`
*/
moduleIds?: boolean | null | undefined;
/**
* Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions
*
* Default: `(sourceRoot)`
*/
moduleRoot?: string | null | undefined;
/**
* A glob, regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile
* a non-matching file it's returned verbatim
*
* Default: `null`
*/
only?: MatchPattern[] | null | undefined;
/**
* Allows users to provide an array of options that will be merged into the current configuration one at a time.
* This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply
*/
overrides?: TransformOptions[] | undefined;
/**
* An object containing the options to be passed down to the babel parser, @babel/parser
*
* Default: `{}`
*/
parserOpts?: ParserOptions | null | undefined;
/**
* List of plugins to load and use
*
* Default: `[]`
*/
plugins?: PluginItem[] | null | undefined;
/**
* List of presets (a set of plugins) to load and use
*
* Default: `[]`
*/
presets?: PluginItem[] | null | undefined;
/**
* Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE**: This will not retain the columns)
*
* Default: `false`
*/
retainLines?: boolean | null | undefined;
/**
* An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comment` option when used
*
* Default: `null`
*/
shouldPrintComment?: ((commentContents: string) => boolean) | null | undefined;
/**
* Set `sources[0]` on returned source map
*
* Default: `(filenameRelative)`
*/
sourceFileName?: string | null | undefined;
/**
* If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"`
* then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!**
*
* Default: `false`
*/
sourceMaps?: boolean | "inline" | "both" | null | undefined;
/**
* The root from which all sources are relative
*
* Default: `(moduleRoot)`
*/
sourceRoot?: string | null | undefined;
/**
* Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to guess, based on the presence of ES6
* `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`.
*
* Default: `("module")`
*/
sourceType?: "script" | "module" | "unambiguous" | null | undefined;
/**
* If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing.
*/
test?: MatchPattern | MatchPattern[] | undefined;
/**
* Describes the environments you support/target for your project.
* This can either be a [browserslist-compatible](https://github.com/ai/browserslist) query (with [caveats](https://babeljs.io/docs/en/babel-preset-env#ineffective-browserslist-queries))
*
* Default: `{}`
*/
targets?:
| string
| string[]
| {
esmodules?: boolean;
node?: Omit<string, "current"> | "current" | true;
safari?: Omit<string, "tp"> | "tp";
browsers?: string | string[];
android?: string;
chrome?: string;
deno?: string;
edge?: string;
electron?: string;
firefox?: string;
ie?: string;
ios?: string;
opera?: string;
rhino?: string;
samsung?: string;
};
/**
* An optional callback that can be used to wrap visitor methods. **NOTE**: This is useful for things like introspection, and not really needed for implementing anything. Called as
* `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`.
*/
wrapPluginVisitorMethod?:
| ((
pluginAlias: string,
visitorType: "enter" | "exit",
callback: (path: NodePath, state: any) => void,
) => (path: NodePath, state: any) => void)
| null
| undefined;
}
export interface TransformCaller {
// the only required property
name: string;
// e.g. set to true by `babel-loader` and false by `babel-jest`
supportsStaticESM?: boolean | undefined;
supportsDynamicImport?: boolean | undefined;
supportsExportNamespaceFrom?: boolean | undefined;
supportsTopLevelAwait?: boolean | undefined;
// augment this with a "declare module '@babel/core' { ... }" if you need more keys
}
export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any;
export interface MatchPatternContext {
envName: string;
dirname: string;
caller: TransformCaller | undefined;
}
export type MatchPattern = string | RegExp | ((filename: string | undefined, context: MatchPatternContext) => boolean);
/**
* Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
*/
export function transform(code: string, callback: FileResultCallback): void;
/**
* Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
*/
export function transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
/**
* Here for backward-compatibility. Ideally use `transformSync` if you want a synchronous API.
*/
export function transform(code: string, opts?: TransformOptions): BabelFileResult | null;
/**
* Transforms the passed in code. Returning an object with the generated code, source map, and AST.
*/
export function transformSync(code: string, opts?: TransformOptions): BabelFileResult | null;
/**
* Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.
*/
export function transformAsync(code: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
/**
* Asynchronously transforms the entire contents of a file.
*/
export function transformFile(filename: string, callback: FileResultCallback): void;
/**
* Asynchronously transforms the entire contents of a file.
*/
export function transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback): void;
/**
* Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`.
*/
export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult | null;
/**
* Asynchronously transforms the entire contents of a file.
*/
export function transformFileAsync(filename: string, opts?: TransformOptions): Promise<BabelFileResult | null>;
/**
* Given an AST, transform it.
*/
export function transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback): void;
/**
* Given an AST, transform it.
*/
export function transformFromAst(
ast: Node,
code: string | undefined,
opts: TransformOptions | undefined,
callback: FileResultCallback,
): void;
/**
* Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API.
*/
export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult | null;
/**
* Given an AST, transform it.
*/
export function transformFromAstAsync(
ast: Node,
code?: string,
opts?: TransformOptions,
): Promise<BabelFileResult | null>;
// A babel plugin is a simple function which must return an object matching
// the following interface. Babel will throw if it finds unknown properties.
// The list of allowed plugin keys is here:
// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71
export interface PluginObj<S = PluginPass> {
name?: string | undefined;
manipulateOptions?(opts: any, parserOpts: any): void;
pre?(this: S, file: BabelFile): void;
visitor: Visitor<S>;
post?(this: S, file: BabelFile): void;
inherits?: any;
}
export interface BabelFile {
ast: t.File;
opts: TransformOptions;
hub: Hub;
metadata: object;
path: NodePath<t.Program>;
scope: Scope;
inputMap: object | null;
code: string;
}
export interface PluginPass {
file: BabelFile;
key: string;
opts: object;
cwd: string;
filename: string | undefined;
get(key: unknown): any;
set(key: unknown, value: unknown): void;
[key: string]: unknown;
}
export interface BabelFileResult {
ast?: t.File | null | undefined;
code?: string | null | undefined;
ignored?: boolean | undefined;
map?:
| {
version: number;
sources: string[];
names: string[];
sourceRoot?: string | undefined;
sourcesContent?: string[] | undefined;
mappings: string;
file: string;
}
| null
| undefined;
metadata?: BabelFileMetadata | undefined;
}
export interface BabelFileMetadata {
usedHelpers: string[];
marked: Array<{
type: string;
message: string;
loc: object;
}>;
modules: BabelFileModulesMetadata;
}
export interface BabelFileModulesMetadata {
imports: object[];
exports: {
exported: object[];
specifiers: object[];
};
}
export type FileParseCallback = (err: Error | null, result: ParseResult | null) => any;
/**
* Given some code, parse it using Babel's standard behavior.
* Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
*/
export function parse(code: string, callback: FileParseCallback): void;
/**
* Given some code, parse it using Babel's standard behavior.
* Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
*/
export function parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback): void;
/**
* Given some code, parse it using Babel's standard behavior.
* Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
*/
export function parse(code: string, options?: TransformOptions): ParseResult | null;
/**
* Given some code, parse it using Babel's standard behavior.
* Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
*/
export function parseSync(code: string, options?: TransformOptions): ParseResult | null;
/**
* Given some code, parse it using Babel's standard behavior.
* Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.
*/
export function parseAsync(code: string, options?: TransformOptions): Promise<ParseResult | null>;
/**
* Resolve Babel's options fully, resulting in an options object where:
*
* * opts.plugins is a full list of Plugin instances.
* * opts.presets is empty and all presets are flattened into opts.
* * It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel
* will not make a second attempt to load config files.
*
* Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to
* use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to
* invalidate properly, but it is the best we have at the moment.
*/
export function loadOptions(options?: TransformOptions): object | null;
/**
* To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and
* presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it
* as then see fit and pass it back to Babel again.
*
* * `babelrc: string | void` - The path of the `.babelrc` file, if there was one.
* * `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
* * `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back
* to Babel again.
* * `plugins: Array<ConfigItem>` - See below.
* * `presets: Array<ConfigItem>` - See below.
* * It can be safely passed back to Babel. Fields like `babelrc` have been set to false so that later calls to
* Babel will not make a second attempt to load config files.
*
* `ConfigItem` instances expose properties to introspect the values, but each item should be treated as
* immutable. If changes are desired, the item should be removed from the list and replaced with either a normal
* Babel config value, or with a replacement item created by `babel.createConfigItem`. See that function for
* information about `ConfigItem` fields.
*/
export function loadPartialConfig(options?: TransformOptions): Readonly<PartialConfig> | null;
export function loadPartialConfigAsync(options?: TransformOptions): Promise<Readonly<PartialConfig> | null>;
export interface PartialConfig {
options: TransformOptions;
babelrc?: string | undefined;
babelignore?: string | undefined;
config?: string | undefined;
hasFilesystemConfig: () => boolean;
}
export interface ConfigItem {
/**
* The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
*/
name?: string | undefined;
/**
* The resolved value of the plugin.
*/
value: object | ((...args: any[]) => any);
/**
* The options object passed to the plugin.
*/
options?: object | false | undefined;
/**
* The path that the options are relative to.
*/
dirname: string;
/**
* Information about the plugin's file, if Babel knows it.
* *
*/
file?:
| {
/**
* The file that the user requested, e.g. `"@babel/env"`
*/
request: string;
/**
* The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`
*/
resolved: string;
}
| null
| undefined;
}
export type PluginOptions = object | undefined | false;
export type PluginTarget = string | object | ((...args: any[]) => any);
export type PluginItem =
| ConfigItem
| PluginObj<any>
| PluginTarget
| [PluginTarget, PluginOptions]
| [PluginTarget, PluginOptions, string | undefined];
export function resolvePlugin(name: string, dirname: string): string | null;
export function resolvePreset(name: string, dirname: string): string | null;
export interface CreateConfigItemOptions {
dirname?: string | undefined;
type?: "preset" | "plugin" | undefined;
}
/**
* Allows build tooling to create and cache config items up front. If this function is called multiple times for a
* given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected
* plugins and presets to inject, pre-constructing the config items would be recommended.
*/
export function createConfigItem(
value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined],
options?: CreateConfigItemOptions,
): ConfigItem;
// NOTE: the documentation says the ConfigAPI also exposes @babel/core's exports, but it actually doesn't
/**
* @see https://babeljs.io/docs/en/next/config-files#config-function-api
*/
export interface ConfigAPI {
/**
* The version string for the Babel version that is loading the config file.
*
* @see https://babeljs.io/docs/en/next/config-files#apiversion
*/
version: string;
/**
* @see https://babeljs.io/docs/en/next/config-files#apicache
*/
cache: SimpleCacheConfigurator;
/**
* @see https://babeljs.io/docs/en/next/config-files#apienv
*/
env: EnvFunction;
// undocumented; currently hardcoded to return 'false'
// async(): boolean
/**
* This API is used as a way to access the `caller` data that has been passed to Babel.
* Since many instances of Babel may be running in the same process with different `caller` values,
* this API is designed to automatically configure `api.cache`, the same way `api.env()` does.
*
* The `caller` value is available as the first parameter of the callback function.
* It is best used with something like this to toggle configuration behavior
* based on a specific environment:
*
* @example
* function isBabelRegister(caller?: { name: string }) {
* return !!(caller && caller.name === "@babel/register")
* }
* api.caller(isBabelRegister)
*
* @see https://babeljs.io/docs/en/next/config-files#apicallercb
*/
caller<T extends SimpleCacheKey>(callerCallback: (caller: TransformOptions["caller"]) => T): T;
/**
* While `api.version` can be useful in general, it's sometimes nice to just declare your version.
* This API exposes a simple way to do that with:
*
* @example
* api.assertVersion(7) // major version only
* api.assertVersion("^7.2")
*
* @see https://babeljs.io/docs/en/next/config-files#apiassertversionrange
*/
assertVersion(versionRange: number | string): boolean;
// NOTE: this is an undocumented reexport from "@babel/parser" but it's missing from its types
// tokTypes: typeof tokTypes
}
/**
* JS configs are great because they can compute a config on the fly,
* but the downside there is that it makes caching harder.
* Babel wants to avoid re-executing the config function every time a file is compiled,
* because then it would also need to re-execute any plugin and preset functions
* referenced in that config.
*
* To avoid this, Babel expects users of config functions to tell it how to manage caching
* within a config file.
*
* @see https://babeljs.io/docs/en/next/config-files#apicache
*/
export interface SimpleCacheConfigurator {
// there is an undocumented call signature that is a shorthand for forever()/never()/using().
// (ever: boolean): void
// <T extends SimpleCacheKey>(callback: CacheCallback<T>): T
/**
* Permacache the computed config and never call the function again.
*/
forever(): void;
/**
* Do not cache this config, and re-execute the function every time.
*/
never(): void;
/**
* Any time the using callback returns a value other than the one that was expected,
* the overall config function will be called again and a new entry will be added to the cache.
*
* @example
* api.cache.using(() => process.env.NODE_ENV)
*/
using<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T;
/**
* Any time the using callback returns a value other than the one that was expected,
* the overall config function will be called again and all entries in the cache will
* be replaced with the result.
*
* @example
* api.cache.invalidate(() => process.env.NODE_ENV)
*/
invalidate<T extends SimpleCacheKey>(callback: SimpleCacheCallback<T>): T;
}
// https://github.com/babel/babel/blob/v7.3.3/packages/babel-core/src/config/caching.js#L231
export type SimpleCacheKey = string | boolean | number | null | undefined;
export type SimpleCacheCallback<T extends SimpleCacheKey> = () => T;
/**
* Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function
* meant specifically for that. This API is used as a quick way to check the `"envName"` that Babel
* was loaded with, which takes `NODE_ENV` into account if no other overriding environment is set.
*
* @see https://babeljs.io/docs/en/next/config-files#apienv
*/
export interface EnvFunction {
/**
* @returns the current `envName` string
*/
(): string;
/**
* @returns `true` if the `envName` is `===` any of the given strings
*/
(envName: string | readonly string[]): boolean;
// the official documentation is misleading for this one...
// this just passes the callback to `cache.using` but with an additional argument.
// it returns its result instead of necessarily returning a boolean.
<T extends SimpleCacheKey>(envCallback: (envName: NonNullable<TransformOptions["envName"]>) => T): T;
}
export type ConfigFunction = (api: ConfigAPI) => TransformOptions;
export as namespace babel;

View File

@@ -0,0 +1,452 @@
// @ts-self-types="./index.d.ts"
/**
* @fileoverview Merge Strategy
*/
//-----------------------------------------------------------------------------
// Class
//-----------------------------------------------------------------------------
/**
* Container class for several different merge strategies.
*/
class MergeStrategy {
/**
* Merges two keys by overwriting the first with the second.
* @param {*} value1 The value from the first object key.
* @param {*} value2 The value from the second object key.
* @returns {*} The second value.
*/
static overwrite(value1, value2) {
return value2;
}
/**
* Merges two keys by replacing the first with the second only if the
* second is defined.
* @param {*} value1 The value from the first object key.
* @param {*} value2 The value from the second object key.
* @returns {*} The second value if it is defined.
*/
static replace(value1, value2) {
if (typeof value2 !== "undefined") {
return value2;
}
return value1;
}
/**
* Merges two properties by assigning properties from the second to the first.
* @param {*} value1 The value from the first object key.
* @param {*} value2 The value from the second object key.
* @returns {*} A new object containing properties from both value1 and
* value2.
*/
static assign(value1, value2) {
return Object.assign({}, value1, value2);
}
}
/**
* @fileoverview Validation Strategy
*/
//-----------------------------------------------------------------------------
// Class
//-----------------------------------------------------------------------------
/**
* Container class for several different validation strategies.
*/
class ValidationStrategy {
/**
* Validates that a value is an array.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static array(value) {
if (!Array.isArray(value)) {
throw new TypeError("Expected an array.");
}
}
/**
* Validates that a value is a boolean.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static boolean(value) {
if (typeof value !== "boolean") {
throw new TypeError("Expected a Boolean.");
}
}
/**
* Validates that a value is a number.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static number(value) {
if (typeof value !== "number") {
throw new TypeError("Expected a number.");
}
}
/**
* Validates that a value is a object.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static object(value) {
if (!value || typeof value !== "object") {
throw new TypeError("Expected an object.");
}
}
/**
* Validates that a value is a object or null.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "object?"(value) {
if (typeof value !== "object") {
throw new TypeError("Expected an object or null.");
}
}
/**
* Validates that a value is a string.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static string(value) {
if (typeof value !== "string") {
throw new TypeError("Expected a string.");
}
}
/**
* Validates that a value is a non-empty string.
* @param {*} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "string!"(value) {
if (typeof value !== "string" || value.length === 0) {
throw new TypeError("Expected a non-empty string.");
}
}
}
/**
* @fileoverview Object Schema
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("./types.ts").ObjectDefinition} ObjectDefinition */
/** @typedef {import("./types.ts").PropertyDefinition} PropertyDefinition */
//-----------------------------------------------------------------------------
// Private
//-----------------------------------------------------------------------------
/**
* Validates a schema strategy.
* @param {string} name The name of the key this strategy is for.
* @param {PropertyDefinition} definition The strategy for the object key.
* @returns {void}
* @throws {Error} When the strategy is missing a name.
* @throws {Error} When the strategy is missing a merge() method.
* @throws {Error} When the strategy is missing a validate() method.
*/
function validateDefinition(name, definition) {
let hasSchema = false;
if (definition.schema) {
if (typeof definition.schema === "object") {
hasSchema = true;
} else {
throw new TypeError("Schema must be an object.");
}
}
if (typeof definition.merge === "string") {
if (!(definition.merge in MergeStrategy)) {
throw new TypeError(
`Definition for key "${name}" missing valid merge strategy.`,
);
}
} else if (!hasSchema && typeof definition.merge !== "function") {
throw new TypeError(
`Definition for key "${name}" must have a merge property.`,
);
}
if (typeof definition.validate === "string") {
if (!(definition.validate in ValidationStrategy)) {
throw new TypeError(
`Definition for key "${name}" missing valid validation strategy.`,
);
}
} else if (!hasSchema && typeof definition.validate !== "function") {
throw new TypeError(
`Definition for key "${name}" must have a validate() method.`,
);
}
}
//-----------------------------------------------------------------------------
// Errors
//-----------------------------------------------------------------------------
/**
* Error when an unexpected key is found.
*/
class UnexpectedKeyError extends Error {
/**
* Creates a new instance.
* @param {string} key The key that was unexpected.
*/
constructor(key) {
super(`Unexpected key "${key}" found.`);
}
}
/**
* Error when a required key is missing.
*/
class MissingKeyError extends Error {
/**
* Creates a new instance.
* @param {string} key The key that was missing.
*/
constructor(key) {
super(`Missing required key "${key}".`);
}
}
/**
* Error when a key requires other keys that are missing.
*/
class MissingDependentKeysError extends Error {
/**
* Creates a new instance.
* @param {string} key The key that was unexpected.
* @param {Array<string>} requiredKeys The keys that are required.
*/
constructor(key, requiredKeys) {
super(`Key "${key}" requires keys "${requiredKeys.join('", "')}".`);
}
}
/**
* Wrapper error for errors occuring during a merge or validate operation.
*/
class WrapperError extends Error {
/**
* Creates a new instance.
* @param {string} key The object key causing the error.
* @param {Error} source The source error.
*/
constructor(key, source) {
super(`Key "${key}": ${source.message}`, { cause: source });
// copy over custom properties that aren't represented
for (const sourceKey of Object.keys(source)) {
if (!(sourceKey in this)) {
this[sourceKey] = source[sourceKey];
}
}
}
}
//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------
/**
* Represents an object validation/merging schema.
*/
class ObjectSchema {
/**
* Track all definitions in the schema by key.
* @type {Map<string, PropertyDefinition>}
*/
#definitions = new Map();
/**
* Separately track any keys that are required for faster validtion.
* @type {Map<string, PropertyDefinition>}
*/
#requiredKeys = new Map();
/**
* Creates a new instance.
* @param {ObjectDefinition} definitions The schema definitions.
*/
constructor(definitions) {
if (!definitions) {
throw new Error("Schema definitions missing.");
}
// add in all strategies
for (const key of Object.keys(definitions)) {
validateDefinition(key, definitions[key]);
// normalize merge and validate methods if subschema is present
if (typeof definitions[key].schema === "object") {
const schema = new ObjectSchema(definitions[key].schema);
definitions[key] = {
...definitions[key],
merge(first = {}, second = {}) {
return schema.merge(first, second);
},
validate(value) {
ValidationStrategy.object(value);
schema.validate(value);
},
};
}
// normalize the merge method in case there's a string
if (typeof definitions[key].merge === "string") {
definitions[key] = {
...definitions[key],
merge: MergeStrategy[
/** @type {string} */ (definitions[key].merge)
],
};
}
// normalize the validate method in case there's a string
if (typeof definitions[key].validate === "string") {
definitions[key] = {
...definitions[key],
validate:
ValidationStrategy[
/** @type {string} */ (definitions[key].validate)
],
};
}
this.#definitions.set(key, definitions[key]);
if (definitions[key].required) {
this.#requiredKeys.set(key, definitions[key]);
}
}
}
/**
* Determines if a strategy has been registered for the given object key.
* @param {string} key The object key to find a strategy for.
* @returns {boolean} True if the key has a strategy registered, false if not.
*/
hasKey(key) {
return this.#definitions.has(key);
}
/**
* Merges objects together to create a new object comprised of the keys
* of the all objects. Keys are merged based on the each key's merge
* strategy.
* @param {...Object} objects The objects to merge.
* @returns {Object} A new object with a mix of all objects' keys.
* @throws {Error} If any object is invalid.
*/
merge(...objects) {
// double check arguments
if (objects.length < 2) {
throw new TypeError("merge() requires at least two arguments.");
}
if (
objects.some(
object => object === null || typeof object !== "object",
)
) {
throw new TypeError("All arguments must be objects.");
}
return objects.reduce((result, object) => {
this.validate(object);
for (const [key, strategy] of this.#definitions) {
try {
if (key in result || key in object) {
const merge = /** @type {Function} */ (strategy.merge);
const value = merge.call(
this,
result[key],
object[key],
);
if (value !== undefined) {
result[key] = value;
}
}
} catch (ex) {
throw new WrapperError(key, ex);
}
}
return result;
}, {});
}
/**
* Validates an object's keys based on the validate strategy for each key.
* @param {Object} object The object to validate.
* @returns {void}
* @throws {Error} When the object is invalid.
*/
validate(object) {
// check existing keys first
for (const key of Object.keys(object)) {
// check to see if the key is defined
if (!this.hasKey(key)) {
throw new UnexpectedKeyError(key);
}
// validate existing keys
const definition = this.#definitions.get(key);
// first check to see if any other keys are required
if (Array.isArray(definition.requires)) {
if (
!definition.requires.every(otherKey => otherKey in object)
) {
throw new MissingDependentKeysError(
key,
definition.requires,
);
}
}
// now apply remaining validation strategy
try {
const validate = /** @type {Function} */ (definition.validate);
validate.call(definition, object[key]);
} catch (ex) {
throw new WrapperError(key, ex);
}
}
// ensure required keys aren't missing
for (const [key] of this.#requiredKeys) {
if (!(key in object)) {
throw new MissingKeyError(key);
}
}
}
}
export { MergeStrategy, ObjectSchema, ValidationStrategy };

View File

@@ -0,0 +1 @@
{"version":3,"names":["_assertThisInitialized","self","ReferenceError"],"sources":["../../src/helpers/assertThisInitialized.ts"],"sourcesContent":["/* @minVersion 7.0.0-beta.0 */\n\nexport default function _assertThisInitialized<T>(self: T | undefined): T {\n if (self === void 0) {\n throw new ReferenceError(\n \"this hasn't been initialised - super() hasn't been called\",\n );\n }\n return self;\n}\n"],"mappings":";;;;;;AAEe,SAASA,sBAAsBA,CAAIC,IAAmB,EAAK;EACxE,IAAIA,IAAI,KAAK,KAAK,CAAC,EAAE;IACnB,MAAM,IAAIC,cAAc,CACtB,2DACF,CAAC;EACH;EACA,OAAOD,IAAI;AACb","ignoreList":[]}