initial commit
This commit is contained in:
116
node_modules/unctx/dist/index.cjs
generated
vendored
Normal file
116
node_modules/unctx/dist/index.cjs
generated
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
'use strict';
|
||||
|
||||
function createContext() {
|
||||
let currentInstance;
|
||||
let isSingleton = false;
|
||||
const checkConflict = (instance) => {
|
||||
if (currentInstance && currentInstance !== instance) {
|
||||
throw new Error("Context conflict");
|
||||
}
|
||||
};
|
||||
return {
|
||||
use: () => {
|
||||
if (currentInstance === void 0) {
|
||||
throw new Error("Context is not available");
|
||||
}
|
||||
return currentInstance;
|
||||
},
|
||||
tryUse: () => {
|
||||
return currentInstance;
|
||||
},
|
||||
set: (instance, replace) => {
|
||||
if (!replace) {
|
||||
checkConflict(instance);
|
||||
}
|
||||
currentInstance = instance;
|
||||
isSingleton = true;
|
||||
},
|
||||
unset: () => {
|
||||
currentInstance = void 0;
|
||||
isSingleton = false;
|
||||
},
|
||||
call: (instance, callback) => {
|
||||
checkConflict(instance);
|
||||
currentInstance = instance;
|
||||
try {
|
||||
return callback();
|
||||
} finally {
|
||||
if (!isSingleton) {
|
||||
currentInstance = void 0;
|
||||
}
|
||||
}
|
||||
},
|
||||
async callAsync(instance, callback) {
|
||||
currentInstance = instance;
|
||||
const onRestore = () => {
|
||||
currentInstance = instance;
|
||||
};
|
||||
const onLeave = () => currentInstance === instance ? onRestore : void 0;
|
||||
asyncHandlers.add(onLeave);
|
||||
try {
|
||||
const r = callback();
|
||||
if (!isSingleton) {
|
||||
currentInstance = void 0;
|
||||
}
|
||||
return await r;
|
||||
} finally {
|
||||
asyncHandlers.delete(onLeave);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function createNamespace() {
|
||||
const contexts = {};
|
||||
return {
|
||||
get(key) {
|
||||
if (!contexts[key]) {
|
||||
contexts[key] = createContext();
|
||||
}
|
||||
contexts[key];
|
||||
return contexts[key];
|
||||
}
|
||||
};
|
||||
}
|
||||
const _globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
|
||||
const globalKey = "__unctx__";
|
||||
const defaultNamespace = _globalThis[globalKey] || (_globalThis[globalKey] = createNamespace());
|
||||
const getContext = (key) => defaultNamespace.get(key);
|
||||
const useContext = (key) => getContext(key).use;
|
||||
const asyncHandlersKey = "__unctx_async_handlers__";
|
||||
const asyncHandlers = _globalThis[asyncHandlersKey] || (_globalThis[asyncHandlersKey] = /* @__PURE__ */ new Set());
|
||||
function executeAsync(function_) {
|
||||
const restores = [];
|
||||
for (const leaveHandler of asyncHandlers) {
|
||||
const restore2 = leaveHandler();
|
||||
if (restore2) {
|
||||
restores.push(restore2);
|
||||
}
|
||||
}
|
||||
const restore = () => {
|
||||
for (const restore2 of restores) {
|
||||
restore2();
|
||||
}
|
||||
};
|
||||
let awaitable = function_();
|
||||
if (awaitable && typeof awaitable === "object" && "catch" in awaitable) {
|
||||
awaitable = awaitable.catch((error) => {
|
||||
restore();
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return [awaitable, restore];
|
||||
}
|
||||
function withAsyncContext(function_, transformed) {
|
||||
if (!transformed) {
|
||||
console.warn("[unctx] `withAsyncContext` needs transformation for async context support in", function_, "\n", function_.toString());
|
||||
}
|
||||
return function_;
|
||||
}
|
||||
|
||||
exports.createContext = createContext;
|
||||
exports.createNamespace = createNamespace;
|
||||
exports.defaultNamespace = defaultNamespace;
|
||||
exports.executeAsync = executeAsync;
|
||||
exports.getContext = getContext;
|
||||
exports.useContext = useContext;
|
||||
exports.withAsyncContext = withAsyncContext;
|
||||
42
node_modules/unctx/dist/index.d.ts
generated
vendored
Normal file
42
node_modules/unctx/dist/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
interface UseContext<T> {
|
||||
/**
|
||||
* Get the current context. Throws if no context is set.
|
||||
*/
|
||||
use: () => T;
|
||||
/**
|
||||
* Get the current context. Returns `null` when no context is set.
|
||||
*/
|
||||
tryUse: () => T | null;
|
||||
/**
|
||||
* Set the context as Singleton Pattern.
|
||||
*/
|
||||
set: (instance?: T, replace?: Boolean) => void;
|
||||
/**
|
||||
* Clear current context.
|
||||
*/
|
||||
unset: () => void;
|
||||
/**
|
||||
* Exclude a synchronous function with the provided context.
|
||||
*/
|
||||
call: <R>(instance: T, callback: () => R) => R;
|
||||
/**
|
||||
* Exclude an asynchronous function with the provided context.
|
||||
* Requires installing the transform plugin to work properly.
|
||||
*/
|
||||
callAsync: <R>(instance: T, callback: () => R | Promise<R>) => Promise<R>;
|
||||
}
|
||||
declare function createContext<T = any>(): UseContext<T>;
|
||||
interface ContextNamespace {
|
||||
get: <T>(key: string) => UseContext<T>;
|
||||
}
|
||||
declare function createNamespace<T = any>(): {
|
||||
get(key: any): UseContext<T>;
|
||||
};
|
||||
declare const defaultNamespace: ContextNamespace;
|
||||
declare const getContext: <T>(key: string) => UseContext<T>;
|
||||
declare const useContext: <T>(key: string) => () => T;
|
||||
type AsyncFunction<T> = () => Promise<T>;
|
||||
declare function executeAsync<T>(function_: AsyncFunction<T>): [Promise<T>, () => void];
|
||||
declare function withAsyncContext<T = any>(function_: AsyncFunction<T>, transformed?: boolean): AsyncFunction<T>;
|
||||
|
||||
export { ContextNamespace, UseContext, createContext, createNamespace, defaultNamespace, executeAsync, getContext, useContext, withAsyncContext };
|
||||
108
node_modules/unctx/dist/index.mjs
generated
vendored
Normal file
108
node_modules/unctx/dist/index.mjs
generated
vendored
Normal file
@@ -0,0 +1,108 @@
|
||||
function createContext() {
|
||||
let currentInstance;
|
||||
let isSingleton = false;
|
||||
const checkConflict = (instance) => {
|
||||
if (currentInstance && currentInstance !== instance) {
|
||||
throw new Error("Context conflict");
|
||||
}
|
||||
};
|
||||
return {
|
||||
use: () => {
|
||||
if (currentInstance === void 0) {
|
||||
throw new Error("Context is not available");
|
||||
}
|
||||
return currentInstance;
|
||||
},
|
||||
tryUse: () => {
|
||||
return currentInstance;
|
||||
},
|
||||
set: (instance, replace) => {
|
||||
if (!replace) {
|
||||
checkConflict(instance);
|
||||
}
|
||||
currentInstance = instance;
|
||||
isSingleton = true;
|
||||
},
|
||||
unset: () => {
|
||||
currentInstance = void 0;
|
||||
isSingleton = false;
|
||||
},
|
||||
call: (instance, callback) => {
|
||||
checkConflict(instance);
|
||||
currentInstance = instance;
|
||||
try {
|
||||
return callback();
|
||||
} finally {
|
||||
if (!isSingleton) {
|
||||
currentInstance = void 0;
|
||||
}
|
||||
}
|
||||
},
|
||||
async callAsync(instance, callback) {
|
||||
currentInstance = instance;
|
||||
const onRestore = () => {
|
||||
currentInstance = instance;
|
||||
};
|
||||
const onLeave = () => currentInstance === instance ? onRestore : void 0;
|
||||
asyncHandlers.add(onLeave);
|
||||
try {
|
||||
const r = callback();
|
||||
if (!isSingleton) {
|
||||
currentInstance = void 0;
|
||||
}
|
||||
return await r;
|
||||
} finally {
|
||||
asyncHandlers.delete(onLeave);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function createNamespace() {
|
||||
const contexts = {};
|
||||
return {
|
||||
get(key) {
|
||||
if (!contexts[key]) {
|
||||
contexts[key] = createContext();
|
||||
}
|
||||
contexts[key];
|
||||
return contexts[key];
|
||||
}
|
||||
};
|
||||
}
|
||||
const _globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
|
||||
const globalKey = "__unctx__";
|
||||
const defaultNamespace = _globalThis[globalKey] || (_globalThis[globalKey] = createNamespace());
|
||||
const getContext = (key) => defaultNamespace.get(key);
|
||||
const useContext = (key) => getContext(key).use;
|
||||
const asyncHandlersKey = "__unctx_async_handlers__";
|
||||
const asyncHandlers = _globalThis[asyncHandlersKey] || (_globalThis[asyncHandlersKey] = /* @__PURE__ */ new Set());
|
||||
function executeAsync(function_) {
|
||||
const restores = [];
|
||||
for (const leaveHandler of asyncHandlers) {
|
||||
const restore2 = leaveHandler();
|
||||
if (restore2) {
|
||||
restores.push(restore2);
|
||||
}
|
||||
}
|
||||
const restore = () => {
|
||||
for (const restore2 of restores) {
|
||||
restore2();
|
||||
}
|
||||
};
|
||||
let awaitable = function_();
|
||||
if (awaitable && typeof awaitable === "object" && "catch" in awaitable) {
|
||||
awaitable = awaitable.catch((error) => {
|
||||
restore();
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return [awaitable, restore];
|
||||
}
|
||||
function withAsyncContext(function_, transformed) {
|
||||
if (!transformed) {
|
||||
console.warn("[unctx] `withAsyncContext` needs transformation for async context support in", function_, "\n", function_.toString());
|
||||
}
|
||||
return function_;
|
||||
}
|
||||
|
||||
export { createContext, createNamespace, defaultNamespace, executeAsync, getContext, useContext, withAsyncContext };
|
||||
27
node_modules/unctx/dist/plugin.cjs
generated
vendored
Normal file
27
node_modules/unctx/dist/plugin.cjs
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
const unplugin = require('unplugin');
|
||||
const transform = require('./transform.cjs');
|
||||
require('acorn');
|
||||
require('magic-string');
|
||||
require('estree-walker');
|
||||
|
||||
const unctxPlugin = unplugin.createUnplugin((options = {}) => {
|
||||
const transformer = transform.createTransformer(options);
|
||||
return {
|
||||
name: "unctx:transfrom",
|
||||
enforce: "post",
|
||||
transformInclude: options.transformInclude,
|
||||
transform(code, id) {
|
||||
const result = transformer.transform(code);
|
||||
if (result) {
|
||||
return {
|
||||
code: result.code,
|
||||
map: result.magicString.generateMap({ source: id, includeContent: true })
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
exports.unctxPlugin = unctxPlugin;
|
||||
10
node_modules/unctx/dist/plugin.d.ts
generated
vendored
Normal file
10
node_modules/unctx/dist/plugin.d.ts
generated
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
import * as unplugin from 'unplugin';
|
||||
import { TransformerOptions } from './transform.js';
|
||||
import 'magic-string';
|
||||
|
||||
interface UnctxPluginOptions extends TransformerOptions {
|
||||
transformInclude?: (id: string) => boolean;
|
||||
}
|
||||
declare const unctxPlugin: unplugin.UnpluginInstance<UnctxPluginOptions, false>;
|
||||
|
||||
export { UnctxPluginOptions, unctxPlugin };
|
||||
25
node_modules/unctx/dist/plugin.mjs
generated
vendored
Normal file
25
node_modules/unctx/dist/plugin.mjs
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
import { createUnplugin } from 'unplugin';
|
||||
import { createTransformer } from './transform.mjs';
|
||||
import 'acorn';
|
||||
import 'magic-string';
|
||||
import 'estree-walker';
|
||||
|
||||
const unctxPlugin = createUnplugin((options = {}) => {
|
||||
const transformer = createTransformer(options);
|
||||
return {
|
||||
name: "unctx:transfrom",
|
||||
enforce: "post",
|
||||
transformInclude: options.transformInclude,
|
||||
transform(code, id) {
|
||||
const result = transformer.transform(code);
|
||||
if (result) {
|
||||
return {
|
||||
code: result.code,
|
||||
map: result.magicString.generateMap({ source: id, includeContent: true })
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export { unctxPlugin };
|
||||
126
node_modules/unctx/dist/transform.cjs
generated
vendored
Normal file
126
node_modules/unctx/dist/transform.cjs
generated
vendored
Normal file
@@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
const acorn = require('acorn');
|
||||
const MagicString = require('magic-string');
|
||||
const estreeWalker = require('estree-walker');
|
||||
|
||||
function _interopNamespaceDefault(e) {
|
||||
const n = Object.create(null);
|
||||
if (e) {
|
||||
for (const k in e) {
|
||||
n[k] = e[k];
|
||||
}
|
||||
}
|
||||
n.default = e;
|
||||
return n;
|
||||
}
|
||||
|
||||
const acorn__namespace = /*#__PURE__*/_interopNamespaceDefault(acorn);
|
||||
|
||||
function createTransformer(options = {}) {
|
||||
options = {
|
||||
asyncFunctions: ["withAsyncContext"],
|
||||
helperModule: "unctx",
|
||||
helperName: "executeAsync",
|
||||
...options
|
||||
};
|
||||
const matchRE = new RegExp(`\\b(${options.asyncFunctions.join("|")})\\(`);
|
||||
function shouldTransform(code) {
|
||||
return typeof code === "string" && matchRE.test(code);
|
||||
}
|
||||
function transform(code, options_ = {}) {
|
||||
if (!options_.force && !shouldTransform(code)) {
|
||||
return;
|
||||
}
|
||||
const ast = acorn__namespace.parse(code, {
|
||||
sourceType: "module",
|
||||
ecmaVersion: "latest",
|
||||
locations: true
|
||||
});
|
||||
const s = new MagicString(code);
|
||||
const lines = code.split("\n");
|
||||
let detected = false;
|
||||
estreeWalker.walk(ast, {
|
||||
enter(node) {
|
||||
if (node.type === "CallExpression") {
|
||||
const functionName = _getFunctionName(node.callee);
|
||||
if (options.asyncFunctions.includes(functionName)) {
|
||||
transformFunctionBody(node);
|
||||
if (functionName !== "callAsync") {
|
||||
const lastArgument = node.arguments[node.arguments.length - 1];
|
||||
if (lastArgument) {
|
||||
s.appendRight(toIndex(lastArgument.loc.end), ",1");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!detected) {
|
||||
return;
|
||||
}
|
||||
s.appendLeft(0, `import { ${options.helperName} as __executeAsync } from "${options.helperModule}";`);
|
||||
return {
|
||||
code: s.toString(),
|
||||
magicString: s
|
||||
};
|
||||
function toIndex(pos) {
|
||||
return lines.slice(0, pos.line - 1).join("\n").length + pos.column + 1;
|
||||
}
|
||||
function transformFunctionBody(node) {
|
||||
for (const function_ of node.arguments) {
|
||||
if (function_.type !== "ArrowFunctionExpression" && function_.type !== "FunctionExpression") {
|
||||
continue;
|
||||
}
|
||||
if (!function_.async) {
|
||||
continue;
|
||||
}
|
||||
const body = function_.body;
|
||||
let injectVariable = false;
|
||||
estreeWalker.walk(body, {
|
||||
enter(node2, parent) {
|
||||
if (node2.type === "AwaitExpression") {
|
||||
detected = true;
|
||||
injectVariable = true;
|
||||
injectForNode(node2, parent);
|
||||
}
|
||||
if (node2.type === "ArrowFunctionExpression" || node2.type === "FunctionExpression" || node2.type === "FunctionDeclaration") {
|
||||
return this.skip();
|
||||
}
|
||||
}
|
||||
});
|
||||
if (injectVariable) {
|
||||
s.appendLeft(
|
||||
toIndex(body.loc.start) + 1,
|
||||
"let __temp, __restore;"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
function injectForNode(node, parent) {
|
||||
const body = code.slice(
|
||||
toIndex(node.argument.loc.start),
|
||||
toIndex(node.argument.loc.end)
|
||||
);
|
||||
const isStatement = parent?.type === "ExpressionStatement";
|
||||
s.overwrite(
|
||||
toIndex(node.loc.start),
|
||||
toIndex(node.loc.end),
|
||||
isStatement ? `;(([__temp,__restore]=__executeAsync(()=>${body})),await __temp,__restore());` : `(([__temp,__restore]=__executeAsync(()=>${body})),__temp=await __temp,__restore(),__temp)`
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
transform,
|
||||
shouldTransform
|
||||
};
|
||||
}
|
||||
function _getFunctionName(node) {
|
||||
if (node.type === "Identifier") {
|
||||
return node.name;
|
||||
} else if (node.type === "MemberExpression") {
|
||||
return _getFunctionName(node.property);
|
||||
}
|
||||
}
|
||||
|
||||
exports.createTransformer = createTransformer;
|
||||
29
node_modules/unctx/dist/transform.d.ts
generated
vendored
Normal file
29
node_modules/unctx/dist/transform.d.ts
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
import MagicString from 'magic-string';
|
||||
|
||||
interface TransformerOptions {
|
||||
/**
|
||||
* The function names to be transformed.
|
||||
*
|
||||
* @default ['withAsyncContext', 'callAsync']
|
||||
*/
|
||||
asyncFunctions?: string[];
|
||||
/**
|
||||
* @default 'unctx'
|
||||
*/
|
||||
helperModule?: string;
|
||||
/**
|
||||
* @default 'executeAsync'
|
||||
*/
|
||||
helperName?: string;
|
||||
}
|
||||
declare function createTransformer(options?: TransformerOptions): {
|
||||
transform: (code: string, options_?: {
|
||||
force?: false;
|
||||
}) => {
|
||||
code: string;
|
||||
magicString: MagicString;
|
||||
};
|
||||
shouldTransform: (code: string) => boolean;
|
||||
};
|
||||
|
||||
export { TransformerOptions, createTransformer };
|
||||
111
node_modules/unctx/dist/transform.mjs
generated
vendored
Normal file
111
node_modules/unctx/dist/transform.mjs
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
import * as acorn from 'acorn';
|
||||
import MagicString from 'magic-string';
|
||||
import { walk } from 'estree-walker';
|
||||
|
||||
function createTransformer(options = {}) {
|
||||
options = {
|
||||
asyncFunctions: ["withAsyncContext"],
|
||||
helperModule: "unctx",
|
||||
helperName: "executeAsync",
|
||||
...options
|
||||
};
|
||||
const matchRE = new RegExp(`\\b(${options.asyncFunctions.join("|")})\\(`);
|
||||
function shouldTransform(code) {
|
||||
return typeof code === "string" && matchRE.test(code);
|
||||
}
|
||||
function transform(code, options_ = {}) {
|
||||
if (!options_.force && !shouldTransform(code)) {
|
||||
return;
|
||||
}
|
||||
const ast = acorn.parse(code, {
|
||||
sourceType: "module",
|
||||
ecmaVersion: "latest",
|
||||
locations: true
|
||||
});
|
||||
const s = new MagicString(code);
|
||||
const lines = code.split("\n");
|
||||
let detected = false;
|
||||
walk(ast, {
|
||||
enter(node) {
|
||||
if (node.type === "CallExpression") {
|
||||
const functionName = _getFunctionName(node.callee);
|
||||
if (options.asyncFunctions.includes(functionName)) {
|
||||
transformFunctionBody(node);
|
||||
if (functionName !== "callAsync") {
|
||||
const lastArgument = node.arguments[node.arguments.length - 1];
|
||||
if (lastArgument) {
|
||||
s.appendRight(toIndex(lastArgument.loc.end), ",1");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!detected) {
|
||||
return;
|
||||
}
|
||||
s.appendLeft(0, `import { ${options.helperName} as __executeAsync } from "${options.helperModule}";`);
|
||||
return {
|
||||
code: s.toString(),
|
||||
magicString: s
|
||||
};
|
||||
function toIndex(pos) {
|
||||
return lines.slice(0, pos.line - 1).join("\n").length + pos.column + 1;
|
||||
}
|
||||
function transformFunctionBody(node) {
|
||||
for (const function_ of node.arguments) {
|
||||
if (function_.type !== "ArrowFunctionExpression" && function_.type !== "FunctionExpression") {
|
||||
continue;
|
||||
}
|
||||
if (!function_.async) {
|
||||
continue;
|
||||
}
|
||||
const body = function_.body;
|
||||
let injectVariable = false;
|
||||
walk(body, {
|
||||
enter(node2, parent) {
|
||||
if (node2.type === "AwaitExpression") {
|
||||
detected = true;
|
||||
injectVariable = true;
|
||||
injectForNode(node2, parent);
|
||||
}
|
||||
if (node2.type === "ArrowFunctionExpression" || node2.type === "FunctionExpression" || node2.type === "FunctionDeclaration") {
|
||||
return this.skip();
|
||||
}
|
||||
}
|
||||
});
|
||||
if (injectVariable) {
|
||||
s.appendLeft(
|
||||
toIndex(body.loc.start) + 1,
|
||||
"let __temp, __restore;"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
function injectForNode(node, parent) {
|
||||
const body = code.slice(
|
||||
toIndex(node.argument.loc.start),
|
||||
toIndex(node.argument.loc.end)
|
||||
);
|
||||
const isStatement = parent?.type === "ExpressionStatement";
|
||||
s.overwrite(
|
||||
toIndex(node.loc.start),
|
||||
toIndex(node.loc.end),
|
||||
isStatement ? `;(([__temp,__restore]=__executeAsync(()=>${body})),await __temp,__restore());` : `(([__temp,__restore]=__executeAsync(()=>${body})),__temp=await __temp,__restore(),__temp)`
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
transform,
|
||||
shouldTransform
|
||||
};
|
||||
}
|
||||
function _getFunctionName(node) {
|
||||
if (node.type === "Identifier") {
|
||||
return node.name;
|
||||
} else if (node.type === "MemberExpression") {
|
||||
return _getFunctionName(node.property);
|
||||
}
|
||||
}
|
||||
|
||||
export { createTransformer };
|
||||
Reference in New Issue
Block a user