penambahan web socket

This commit is contained in:
2025-09-18 19:01:22 +07:00
parent 1d053646a9
commit d7bb2eb5bb
15070 changed files with 2402916 additions and 0 deletions

No files matched your search

+266
View File
@@ -0,0 +1,266 @@
'use strict';
function genString(input, options = {}) {
const str = JSON.stringify(input);
if (!options.singleQuotes) {
return str;
}
return `'${escapeString(str).slice(1, -1)}'`;
}
const NEEDS_ESCAPE_RE = /[\n\r'\\\u2028\u2029]/;
const QUOTE_NEWLINE_RE = /([\n\r'\u2028\u2029])/g;
const BACKSLASH_RE = /\\/g;
function escapeString(id) {
if (!NEEDS_ESCAPE_RE.test(id)) {
return id;
}
return id.replace(BACKSLASH_RE, "\\\\").replace(QUOTE_NEWLINE_RE, "\\$1");
}
function genSafeVariableName(name) {
if (reservedNames.has(name)) {
return `_${name}`;
}
return name.replace(/^\d/, (r) => `_${r}`).replace(/\W/g, (r) => "_" + r.charCodeAt(0));
}
const reservedNames = /* @__PURE__ */ new Set([
"Infinity",
"NaN",
"arguments",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"static",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"undefined",
"var",
"void",
"while",
"with",
"yield"
]);
function _genStatement(type, specifier, names, options = {}) {
const specifierString = genString(specifier, options);
if (!names) {
return `${type} ${specifierString};`;
}
const nameArray = Array.isArray(names);
const _names = (nameArray ? names : [names]).map((index) => {
if (typeof index === "string") {
return { name: index };
}
if (index.name === index.as) {
index = { name: index.name };
}
return index;
});
const namesString = _names.map((index) => index.as ? `${index.name} as ${index.as}` : index.name).join(", ");
if (nameArray) {
return `${type} { ${namesString} } from ${genString(
specifier,
options
)}${_genImportAttributes(type, options)};`;
}
return `${type} ${namesString} from ${genString(
specifier,
options
)}${_genImportAttributes(type, options)};`;
}
function _genImportAttributes(type, options) {
if (type === "import type" || type === "export type") {
return "";
}
if (typeof options.attributes?.type === "string") {
return ` with { type: ${genString(options.attributes.type)} }`;
}
if (typeof options.assert?.type === "string") {
return ` assert { type: ${genString(options.assert.type)} }`;
}
return "";
}
function genImport(specifier, imports, options = {}) {
return _genStatement("import", specifier, imports, options);
}
function genTypeImport(specifier, imports, options = {}) {
return _genStatement("import type", specifier, imports, options);
}
function genExport(specifier, exports, options = {}) {
return _genStatement("export", specifier, exports, options);
}
function genDynamicImport(specifier, options = {}) {
const commentString = options.comment ? ` /* ${options.comment} */` : "";
const wrapperString = options.wrapper === false ? "" : "() => ";
const ineropString = options.interopDefault ? ".then(m => m.default || m)" : "";
const optionsString = _genDynamicImportAttributes(options);
return `${wrapperString}import(${genString(
specifier,
options
)}${commentString}${optionsString})${ineropString}`;
}
function _genDynamicImportAttributes(options = {}) {
if (typeof options.assert?.type === "string") {
return `, { assert: { type: ${genString(options.assert.type)} } }`;
}
if (typeof options.attributes?.type === "string") {
return `, { with: { type: ${genString(options.attributes.type)} } }`;
}
return "";
}
function wrapInDelimiters(lines, indent = "", delimiters = "{}", withComma = true) {
if (lines.length === 0) {
return delimiters;
}
const [start, end] = delimiters;
return `${start}
` + lines.join(withComma ? ",\n" : "\n") + `
${indent}${end}`;
}
const VALID_IDENTIFIER_RE = /^[$_]?([A-Z_a-z]\w*|\d)$/;
function genObjectKey(key) {
return VALID_IDENTIFIER_RE.test(key) ? key : genString(key);
}
function genObjectFromRaw(object, indent = "", options = {}) {
return genObjectFromRawEntries(Object.entries(object), indent, options);
}
function genObjectFromValues(obj, indent = "", options = {}) {
return genObjectFromRaw(obj, indent, { preserveTypes: true, ...options });
}
function genArrayFromRaw(array, indent = "", options = {}) {
const newIdent = indent + " ";
return wrapInDelimiters(
array.map((index) => `${newIdent}${genRawValue(index, newIdent, options)}`),
indent,
"[]"
);
}
function genObjectFromRawEntries(array, indent = "", options = {}) {
const newIdent = indent + " ";
return wrapInDelimiters(
array.map(
([key, value]) => `${newIdent}${genObjectKey(key)}: ${genRawValue(value, newIdent, options)}`
),
indent,
"{}"
);
}
function genRawValue(value, indent = "", options = {}) {
if (value === void 0) {
return "undefined";
}
if (value === null) {
return "null";
}
if (Array.isArray(value)) {
return genArrayFromRaw(value, indent, options);
}
if (value && typeof value === "object") {
return genObjectFromRaw(value, indent, options);
}
if (options.preserveTypes && typeof value !== "function") {
return JSON.stringify(value);
}
return value.toString();
}
function genTypeExport(specifier, imports, options = {}) {
return _genStatement("export type", specifier, imports, options);
}
function genInlineTypeImport(specifier, name = "default", options = {}) {
return `typeof ${genDynamicImport(specifier, {
...options,
wrapper: false
})}.${name}`;
}
function genTypeObject(object, indent = "") {
const newIndent = indent + " ";
return wrapInDelimiters(
Object.entries(object).map(([key, value]) => {
const [, k = key, optional = ""] = key.match(/^(.*[^?])(\?)?$/) || [];
if (typeof value === "string") {
return `${newIndent}${genObjectKey(k)}${optional}: ${value}`;
}
return `${newIndent}${genObjectKey(k)}${optional}: ${genTypeObject(
value,
newIndent
)}`;
}),
indent,
"{}",
false
);
}
function genInterface(name, contents, options = {}, indent = "") {
const result = [
options.export && "export",
`interface ${name}`,
options.extends && `extends ${Array.isArray(options.extends) ? options.extends.join(", ") : options.extends}`,
contents ? genTypeObject(contents, indent) : "{}"
].filter(Boolean).join(" ");
return result;
}
function genAugmentation(specifier, interfaces) {
return `declare module ${genString(specifier)} ${wrapInDelimiters(
Object.entries(interfaces || {}).map(
([key, entry]) => " " + (Array.isArray(entry) ? genInterface(key, ...entry) : genInterface(key, entry, {}, " "))
)
)}`;
}
exports.escapeString = escapeString;
exports.genArrayFromRaw = genArrayFromRaw;
exports.genAugmentation = genAugmentation;
exports.genDynamicImport = genDynamicImport;
exports.genExport = genExport;
exports.genImport = genImport;
exports.genInlineTypeImport = genInlineTypeImport;
exports.genInterface = genInterface;
exports.genObjectFromRaw = genObjectFromRaw;
exports.genObjectFromRawEntries = genObjectFromRawEntries;
exports.genObjectFromValues = genObjectFromValues;
exports.genObjectKey = genObjectKey;
exports.genSafeVariableName = genSafeVariableName;
exports.genString = genString;
exports.genTypeExport = genTypeExport;
exports.genTypeImport = genTypeImport;
exports.genTypeObject = genTypeObject;
exports.wrapInDelimiters = wrapInDelimiters;
+211
View File
@@ -0,0 +1,211 @@
interface CodegenOptions {
singleQuotes?: boolean;
}
type ESMImport = string | {
name: string;
as?: string;
};
type ESMExport = string | {
name: string;
as?: string;
};
interface ESMCodeGenOptions extends CodegenOptions {
attributes?: {
type: string;
};
/** @deprecated use attributes */
assert?: {
type: string;
};
}
interface DynamicImportOptions extends ESMCodeGenOptions {
comment?: string;
wrapper?: boolean;
interopDefault?: boolean;
}
/**
* Generate an ESM `import` statement.
*
* @example
*
* ```js
* genImport("pkg", "foo");
* // ~> `import foo from "pkg";`
*
* genImport("pkg", ["foo"]);
* // ~> `import { foo } from "pkg";`
*
* genImport("pkg", ["a", "b"]);
* // ~> `import { a, b } from "pkg`;
*
* genImport("pkg", [{ name: "default", as: "bar" }]);
* // ~> `import { default as bar } from "pkg`;
*
* genImport("pkg", [{ name: "foo", as: "bar" }]);
* // ~> `import { foo as bar } from "pkg`;
*
* genImport("pkg", "foo", { attributes: { type: "json" } });
* // ~> `import foo from "pkg" with { type: "json" };
*
* genExport("pkg", "foo");
* // ~> `export foo from "pkg";`
*
* genExport("pkg", ["a", "b"]);
* // ~> `export { a, b } from "pkg";`
*
* // export * as bar from "pkg"
* genExport("pkg", { name: "*", as: "bar" });
* // ~> `export * as bar from "pkg";`
* ```
*
* @group ESM
*/
declare function genImport(specifier: string, imports?: ESMImport | ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM `import type` statement.
*
* @group ESM
*/
declare function genTypeImport(specifier: string, imports: ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM `export` statement.
*
* @group ESM
*/
declare function genExport(specifier: string, exports?: ESMExport | ESMExport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM dynamic `import()` statement.
*
* @group ESM
*/
declare function genDynamicImport(specifier: string, options?: DynamicImportOptions): string;
interface GenObjectOptions extends CodegenOptions {
preserveTypes?: boolean;
}
/**
* Serialize an object to a string.
*
* Values are not escaped or quoted.
*
* @example
*
* ```js
* genObjectFromRaw({ foo: "bar", test: '() => import("pkg")' })
* // ~> `{ foo: bar, test: () => import("pkg") }`
* ```
*
* @group serialization
*/
declare function genObjectFromRaw(object: Record<string, any>, indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an object to a string.
*
* Values are escaped and quoted if necessary.
*
* @example
*
* ```js
* genObjectFromValues({ foo: "bar" })
* // ~> `{ foo: "bar" }`
* ```
*
* @group serialization
*/
declare function genObjectFromValues(obj: Record<string, any>, indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an array to a string.
*
* Values are not escaped or quoted.
*
* @example
*
* ```js
* genArrayFromRaw([1, 2, 3])
* // ~> `[1, 2, 3]`
* ```
*
* @group serialization
*/
declare function genArrayFromRaw(array: any[], indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an array of key-value pairs to a string.
*
* Values are not escaped or quoted.
*
* @group serialization
*/
declare function genObjectFromRawEntries(array: [key: string, value: any][], indent?: string, options?: GenObjectOptions): string;
/**
* Generate a string with double or single quotes and handle escapes.
*
* @group string
*/
declare function genString(input: string, options?: CodegenOptions): string;
/**
* Escape a string for use in a javascript string.
*
* @group string
*/
declare function escapeString(id: string): string;
/**
* Generate a safe javascript variable name.
*
* @group string
*/
declare function genSafeVariableName(name: string): string;
type TypeObject = {
[key: string]: string | TypeObject;
};
interface GenInterfaceOptions {
extends?: string | string[];
export?: boolean;
}
/**
* Generate a typescript `export type` statement.
*
* @group Typescript
*/
declare function genTypeExport(specifier: string, imports: ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an typescript `typeof import()` statement for default import.
*
* @group Typescript
*/
declare function genInlineTypeImport(specifier: string, name?: string, options?: ESMCodeGenOptions): string;
/**
* Generate typescript object type.
*
* @group Typescript
*/
declare function genTypeObject(object: TypeObject, indent?: string): string;
/**
* Generate typescript interface.
*
* @group Typescript
*/
declare function genInterface(name: string, contents?: TypeObject, options?: GenInterfaceOptions, indent?: string): string;
/**
* Generate typescript `declare module` augmentation.
*
* @group Typescript
*/
declare function genAugmentation(specifier: string, interfaces?: Record<string, TypeObject | [TypeObject, Omit<GenInterfaceOptions, "export">]>): string;
/**
* Wrap an array of strings in delimiters.
*
* @group utils
*/
declare function wrapInDelimiters(lines: string[], indent?: string, delimiters?: string, withComma?: boolean): string;
/**
* Generate a safe javascript variable name for an object key.
*
* @group utils
*/
declare function genObjectKey(key: string): string;
export { type CodegenOptions, type DynamicImportOptions, type ESMCodeGenOptions, type ESMExport, type ESMImport, type GenInterfaceOptions, type GenObjectOptions, type TypeObject, escapeString, genArrayFromRaw, genAugmentation, genDynamicImport, genExport, genImport, genInlineTypeImport, genInterface, genObjectFromRaw, genObjectFromRawEntries, genObjectFromValues, genObjectKey, genSafeVariableName, genString, genTypeExport, genTypeImport, genTypeObject, wrapInDelimiters };
+211
View File
@@ -0,0 +1,211 @@
interface CodegenOptions {
singleQuotes?: boolean;
}
type ESMImport = string | {
name: string;
as?: string;
};
type ESMExport = string | {
name: string;
as?: string;
};
interface ESMCodeGenOptions extends CodegenOptions {
attributes?: {
type: string;
};
/** @deprecated use attributes */
assert?: {
type: string;
};
}
interface DynamicImportOptions extends ESMCodeGenOptions {
comment?: string;
wrapper?: boolean;
interopDefault?: boolean;
}
/**
* Generate an ESM `import` statement.
*
* @example
*
* ```js
* genImport("pkg", "foo");
* // ~> `import foo from "pkg";`
*
* genImport("pkg", ["foo"]);
* // ~> `import { foo } from "pkg";`
*
* genImport("pkg", ["a", "b"]);
* // ~> `import { a, b } from "pkg`;
*
* genImport("pkg", [{ name: "default", as: "bar" }]);
* // ~> `import { default as bar } from "pkg`;
*
* genImport("pkg", [{ name: "foo", as: "bar" }]);
* // ~> `import { foo as bar } from "pkg`;
*
* genImport("pkg", "foo", { attributes: { type: "json" } });
* // ~> `import foo from "pkg" with { type: "json" };
*
* genExport("pkg", "foo");
* // ~> `export foo from "pkg";`
*
* genExport("pkg", ["a", "b"]);
* // ~> `export { a, b } from "pkg";`
*
* // export * as bar from "pkg"
* genExport("pkg", { name: "*", as: "bar" });
* // ~> `export * as bar from "pkg";`
* ```
*
* @group ESM
*/
declare function genImport(specifier: string, imports?: ESMImport | ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM `import type` statement.
*
* @group ESM
*/
declare function genTypeImport(specifier: string, imports: ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM `export` statement.
*
* @group ESM
*/
declare function genExport(specifier: string, exports?: ESMExport | ESMExport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM dynamic `import()` statement.
*
* @group ESM
*/
declare function genDynamicImport(specifier: string, options?: DynamicImportOptions): string;
interface GenObjectOptions extends CodegenOptions {
preserveTypes?: boolean;
}
/**
* Serialize an object to a string.
*
* Values are not escaped or quoted.
*
* @example
*
* ```js
* genObjectFromRaw({ foo: "bar", test: '() => import("pkg")' })
* // ~> `{ foo: bar, test: () => import("pkg") }`
* ```
*
* @group serialization
*/
declare function genObjectFromRaw(object: Record<string, any>, indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an object to a string.
*
* Values are escaped and quoted if necessary.
*
* @example
*
* ```js
* genObjectFromValues({ foo: "bar" })
* // ~> `{ foo: "bar" }`
* ```
*
* @group serialization
*/
declare function genObjectFromValues(obj: Record<string, any>, indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an array to a string.
*
* Values are not escaped or quoted.
*
* @example
*
* ```js
* genArrayFromRaw([1, 2, 3])
* // ~> `[1, 2, 3]`
* ```
*
* @group serialization
*/
declare function genArrayFromRaw(array: any[], indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an array of key-value pairs to a string.
*
* Values are not escaped or quoted.
*
* @group serialization
*/
declare function genObjectFromRawEntries(array: [key: string, value: any][], indent?: string, options?: GenObjectOptions): string;
/**
* Generate a string with double or single quotes and handle escapes.
*
* @group string
*/
declare function genString(input: string, options?: CodegenOptions): string;
/**
* Escape a string for use in a javascript string.
*
* @group string
*/
declare function escapeString(id: string): string;
/**
* Generate a safe javascript variable name.
*
* @group string
*/
declare function genSafeVariableName(name: string): string;
type TypeObject = {
[key: string]: string | TypeObject;
};
interface GenInterfaceOptions {
extends?: string | string[];
export?: boolean;
}
/**
* Generate a typescript `export type` statement.
*
* @group Typescript
*/
declare function genTypeExport(specifier: string, imports: ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an typescript `typeof import()` statement for default import.
*
* @group Typescript
*/
declare function genInlineTypeImport(specifier: string, name?: string, options?: ESMCodeGenOptions): string;
/**
* Generate typescript object type.
*
* @group Typescript
*/
declare function genTypeObject(object: TypeObject, indent?: string): string;
/**
* Generate typescript interface.
*
* @group Typescript
*/
declare function genInterface(name: string, contents?: TypeObject, options?: GenInterfaceOptions, indent?: string): string;
/**
* Generate typescript `declare module` augmentation.
*
* @group Typescript
*/
declare function genAugmentation(specifier: string, interfaces?: Record<string, TypeObject | [TypeObject, Omit<GenInterfaceOptions, "export">]>): string;
/**
* Wrap an array of strings in delimiters.
*
* @group utils
*/
declare function wrapInDelimiters(lines: string[], indent?: string, delimiters?: string, withComma?: boolean): string;
/**
* Generate a safe javascript variable name for an object key.
*
* @group utils
*/
declare function genObjectKey(key: string): string;
export { type CodegenOptions, type DynamicImportOptions, type ESMCodeGenOptions, type ESMExport, type ESMImport, type GenInterfaceOptions, type GenObjectOptions, type TypeObject, escapeString, genArrayFromRaw, genAugmentation, genDynamicImport, genExport, genImport, genInlineTypeImport, genInterface, genObjectFromRaw, genObjectFromRawEntries, genObjectFromValues, genObjectKey, genSafeVariableName, genString, genTypeExport, genTypeImport, genTypeObject, wrapInDelimiters };
+211
View File
@@ -0,0 +1,211 @@
interface CodegenOptions {
singleQuotes?: boolean;
}
type ESMImport = string | {
name: string;
as?: string;
};
type ESMExport = string | {
name: string;
as?: string;
};
interface ESMCodeGenOptions extends CodegenOptions {
attributes?: {
type: string;
};
/** @deprecated use attributes */
assert?: {
type: string;
};
}
interface DynamicImportOptions extends ESMCodeGenOptions {
comment?: string;
wrapper?: boolean;
interopDefault?: boolean;
}
/**
* Generate an ESM `import` statement.
*
* @example
*
* ```js
* genImport("pkg", "foo");
* // ~> `import foo from "pkg";`
*
* genImport("pkg", ["foo"]);
* // ~> `import { foo } from "pkg";`
*
* genImport("pkg", ["a", "b"]);
* // ~> `import { a, b } from "pkg`;
*
* genImport("pkg", [{ name: "default", as: "bar" }]);
* // ~> `import { default as bar } from "pkg`;
*
* genImport("pkg", [{ name: "foo", as: "bar" }]);
* // ~> `import { foo as bar } from "pkg`;
*
* genImport("pkg", "foo", { attributes: { type: "json" } });
* // ~> `import foo from "pkg" with { type: "json" };
*
* genExport("pkg", "foo");
* // ~> `export foo from "pkg";`
*
* genExport("pkg", ["a", "b"]);
* // ~> `export { a, b } from "pkg";`
*
* // export * as bar from "pkg"
* genExport("pkg", { name: "*", as: "bar" });
* // ~> `export * as bar from "pkg";`
* ```
*
* @group ESM
*/
declare function genImport(specifier: string, imports?: ESMImport | ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM `import type` statement.
*
* @group ESM
*/
declare function genTypeImport(specifier: string, imports: ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM `export` statement.
*
* @group ESM
*/
declare function genExport(specifier: string, exports?: ESMExport | ESMExport[], options?: ESMCodeGenOptions): string;
/**
* Generate an ESM dynamic `import()` statement.
*
* @group ESM
*/
declare function genDynamicImport(specifier: string, options?: DynamicImportOptions): string;
interface GenObjectOptions extends CodegenOptions {
preserveTypes?: boolean;
}
/**
* Serialize an object to a string.
*
* Values are not escaped or quoted.
*
* @example
*
* ```js
* genObjectFromRaw({ foo: "bar", test: '() => import("pkg")' })
* // ~> `{ foo: bar, test: () => import("pkg") }`
* ```
*
* @group serialization
*/
declare function genObjectFromRaw(object: Record<string, any>, indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an object to a string.
*
* Values are escaped and quoted if necessary.
*
* @example
*
* ```js
* genObjectFromValues({ foo: "bar" })
* // ~> `{ foo: "bar" }`
* ```
*
* @group serialization
*/
declare function genObjectFromValues(obj: Record<string, any>, indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an array to a string.
*
* Values are not escaped or quoted.
*
* @example
*
* ```js
* genArrayFromRaw([1, 2, 3])
* // ~> `[1, 2, 3]`
* ```
*
* @group serialization
*/
declare function genArrayFromRaw(array: any[], indent?: string, options?: GenObjectOptions): string;
/**
* Serialize an array of key-value pairs to a string.
*
* Values are not escaped or quoted.
*
* @group serialization
*/
declare function genObjectFromRawEntries(array: [key: string, value: any][], indent?: string, options?: GenObjectOptions): string;
/**
* Generate a string with double or single quotes and handle escapes.
*
* @group string
*/
declare function genString(input: string, options?: CodegenOptions): string;
/**
* Escape a string for use in a javascript string.
*
* @group string
*/
declare function escapeString(id: string): string;
/**
* Generate a safe javascript variable name.
*
* @group string
*/
declare function genSafeVariableName(name: string): string;
type TypeObject = {
[key: string]: string | TypeObject;
};
interface GenInterfaceOptions {
extends?: string | string[];
export?: boolean;
}
/**
* Generate a typescript `export type` statement.
*
* @group Typescript
*/
declare function genTypeExport(specifier: string, imports: ESMImport[], options?: ESMCodeGenOptions): string;
/**
* Generate an typescript `typeof import()` statement for default import.
*
* @group Typescript
*/
declare function genInlineTypeImport(specifier: string, name?: string, options?: ESMCodeGenOptions): string;
/**
* Generate typescript object type.
*
* @group Typescript
*/
declare function genTypeObject(object: TypeObject, indent?: string): string;
/**
* Generate typescript interface.
*
* @group Typescript
*/
declare function genInterface(name: string, contents?: TypeObject, options?: GenInterfaceOptions, indent?: string): string;
/**
* Generate typescript `declare module` augmentation.
*
* @group Typescript
*/
declare function genAugmentation(specifier: string, interfaces?: Record<string, TypeObject | [TypeObject, Omit<GenInterfaceOptions, "export">]>): string;
/**
* Wrap an array of strings in delimiters.
*
* @group utils
*/
declare function wrapInDelimiters(lines: string[], indent?: string, delimiters?: string, withComma?: boolean): string;
/**
* Generate a safe javascript variable name for an object key.
*
* @group utils
*/
declare function genObjectKey(key: string): string;
export { type CodegenOptions, type DynamicImportOptions, type ESMCodeGenOptions, type ESMExport, type ESMImport, type GenInterfaceOptions, type GenObjectOptions, type TypeObject, escapeString, genArrayFromRaw, genAugmentation, genDynamicImport, genExport, genImport, genInlineTypeImport, genInterface, genObjectFromRaw, genObjectFromRawEntries, genObjectFromValues, genObjectKey, genSafeVariableName, genString, genTypeExport, genTypeImport, genTypeObject, wrapInDelimiters };
+247
View File
@@ -0,0 +1,247 @@
function genString(input, options = {}) {
const str = JSON.stringify(input);
if (!options.singleQuotes) {
return str;
}
return `'${escapeString(str).slice(1, -1)}'`;
}
const NEEDS_ESCAPE_RE = /[\n\r'\\\u2028\u2029]/;
const QUOTE_NEWLINE_RE = /([\n\r'\u2028\u2029])/g;
const BACKSLASH_RE = /\\/g;
function escapeString(id) {
if (!NEEDS_ESCAPE_RE.test(id)) {
return id;
}
return id.replace(BACKSLASH_RE, "\\\\").replace(QUOTE_NEWLINE_RE, "\\$1");
}
function genSafeVariableName(name) {
if (reservedNames.has(name)) {
return `_${name}`;
}
return name.replace(/^\d/, (r) => `_${r}`).replace(/\W/g, (r) => "_" + r.charCodeAt(0));
}
const reservedNames = /* @__PURE__ */ new Set([
"Infinity",
"NaN",
"arguments",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"eval",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"implements",
"import",
"in",
"instanceof",
"interface",
"let",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"static",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"undefined",
"var",
"void",
"while",
"with",
"yield"
]);
function _genStatement(type, specifier, names, options = {}) {
const specifierString = genString(specifier, options);
if (!names) {
return `${type} ${specifierString};`;
}
const nameArray = Array.isArray(names);
const _names = (nameArray ? names : [names]).map((index) => {
if (typeof index === "string") {
return { name: index };
}
if (index.name === index.as) {
index = { name: index.name };
}
return index;
});
const namesString = _names.map((index) => index.as ? `${index.name} as ${index.as}` : index.name).join(", ");
if (nameArray) {
return `${type} { ${namesString} } from ${genString(
specifier,
options
)}${_genImportAttributes(type, options)};`;
}
return `${type} ${namesString} from ${genString(
specifier,
options
)}${_genImportAttributes(type, options)};`;
}
function _genImportAttributes(type, options) {
if (type === "import type" || type === "export type") {
return "";
}
if (typeof options.attributes?.type === "string") {
return ` with { type: ${genString(options.attributes.type)} }`;
}
if (typeof options.assert?.type === "string") {
return ` assert { type: ${genString(options.assert.type)} }`;
}
return "";
}
function genImport(specifier, imports, options = {}) {
return _genStatement("import", specifier, imports, options);
}
function genTypeImport(specifier, imports, options = {}) {
return _genStatement("import type", specifier, imports, options);
}
function genExport(specifier, exports, options = {}) {
return _genStatement("export", specifier, exports, options);
}
function genDynamicImport(specifier, options = {}) {
const commentString = options.comment ? ` /* ${options.comment} */` : "";
const wrapperString = options.wrapper === false ? "" : "() => ";
const ineropString = options.interopDefault ? ".then(m => m.default || m)" : "";
const optionsString = _genDynamicImportAttributes(options);
return `${wrapperString}import(${genString(
specifier,
options
)}${commentString}${optionsString})${ineropString}`;
}
function _genDynamicImportAttributes(options = {}) {
if (typeof options.assert?.type === "string") {
return `, { assert: { type: ${genString(options.assert.type)} } }`;
}
if (typeof options.attributes?.type === "string") {
return `, { with: { type: ${genString(options.attributes.type)} } }`;
}
return "";
}
function wrapInDelimiters(lines, indent = "", delimiters = "{}", withComma = true) {
if (lines.length === 0) {
return delimiters;
}
const [start, end] = delimiters;
return `${start}
` + lines.join(withComma ? ",\n" : "\n") + `
${indent}${end}`;
}
const VALID_IDENTIFIER_RE = /^[$_]?([A-Z_a-z]\w*|\d)$/;
function genObjectKey(key) {
return VALID_IDENTIFIER_RE.test(key) ? key : genString(key);
}
function genObjectFromRaw(object, indent = "", options = {}) {
return genObjectFromRawEntries(Object.entries(object), indent, options);
}
function genObjectFromValues(obj, indent = "", options = {}) {
return genObjectFromRaw(obj, indent, { preserveTypes: true, ...options });
}
function genArrayFromRaw(array, indent = "", options = {}) {
const newIdent = indent + " ";
return wrapInDelimiters(
array.map((index) => `${newIdent}${genRawValue(index, newIdent, options)}`),
indent,
"[]"
);
}
function genObjectFromRawEntries(array, indent = "", options = {}) {
const newIdent = indent + " ";
return wrapInDelimiters(
array.map(
([key, value]) => `${newIdent}${genObjectKey(key)}: ${genRawValue(value, newIdent, options)}`
),
indent,
"{}"
);
}
function genRawValue(value, indent = "", options = {}) {
if (value === void 0) {
return "undefined";
}
if (value === null) {
return "null";
}
if (Array.isArray(value)) {
return genArrayFromRaw(value, indent, options);
}
if (value && typeof value === "object") {
return genObjectFromRaw(value, indent, options);
}
if (options.preserveTypes && typeof value !== "function") {
return JSON.stringify(value);
}
return value.toString();
}
function genTypeExport(specifier, imports, options = {}) {
return _genStatement("export type", specifier, imports, options);
}
function genInlineTypeImport(specifier, name = "default", options = {}) {
return `typeof ${genDynamicImport(specifier, {
...options,
wrapper: false
})}.${name}`;
}
function genTypeObject(object, indent = "") {
const newIndent = indent + " ";
return wrapInDelimiters(
Object.entries(object).map(([key, value]) => {
const [, k = key, optional = ""] = key.match(/^(.*[^?])(\?)?$/) || [];
if (typeof value === "string") {
return `${newIndent}${genObjectKey(k)}${optional}: ${value}`;
}
return `${newIndent}${genObjectKey(k)}${optional}: ${genTypeObject(
value,
newIndent
)}`;
}),
indent,
"{}",
false
);
}
function genInterface(name, contents, options = {}, indent = "") {
const result = [
options.export && "export",
`interface ${name}`,
options.extends && `extends ${Array.isArray(options.extends) ? options.extends.join(", ") : options.extends}`,
contents ? genTypeObject(contents, indent) : "{}"
].filter(Boolean).join(" ");
return result;
}
function genAugmentation(specifier, interfaces) {
return `declare module ${genString(specifier)} ${wrapInDelimiters(
Object.entries(interfaces || {}).map(
([key, entry]) => " " + (Array.isArray(entry) ? genInterface(key, ...entry) : genInterface(key, entry, {}, " "))
)
)}`;
}
export { escapeString, genArrayFromRaw, genAugmentation, genDynamicImport, genExport, genImport, genInlineTypeImport, genInterface, genObjectFromRaw, genObjectFromRawEntries, genObjectFromValues, genObjectKey, genSafeVariableName, genString, genTypeExport, genTypeImport, genTypeObject, wrapInDelimiters };