Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

sveld

Package Overview
Dependencies
Maintainers
1
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sveld - npm Package Compare versions

Comparing version 0.19.2 to 0.20.0

2

lib/cli.d.ts

@@ -0,2 +1,4 @@

/// <reference types="bun-types" />
/// <reference types="node" />
/// <reference types="bun-types" />
export declare function cli(process: NodeJS.Process): Promise<void>;

113

lib/cli.js
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -25,2 +36,38 @@ if (k2 === undefined) k2 = k;

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -31,29 +78,45 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.cli = void 0;
const Rollup = __importStar(require("rollup"));
const svelte = __importStar(require("rollup-plugin-svelte"));
const plugin_node_resolve_1 = __importDefault(require("@rollup/plugin-node-resolve"));
const rollup_plugin_1 = require("./rollup-plugin");
const get_svelte_entry_1 = require("./get-svelte-entry");
async function cli(process) {
const options = process.argv
.slice(2)
.map((arg) => {
const [flag, value] = arg.split("=");
const key = flag.slice(2);
return { [key]: value === undefined ? true : value };
})
.reduce((a, c) => ({ ...a, ...c }), {});
const input = (0, get_svelte_entry_1.getSvelteEntry)() || "src/index.js";
const rollup_bundle = await Rollup.rollup({
input,
plugins: [
// @ts-ignore
svelte(),
(0, plugin_node_resolve_1.default)(),
],
var Rollup = __importStar(require("rollup"));
var svelte = __importStar(require("rollup-plugin-svelte"));
var plugin_node_resolve_1 = __importDefault(require("@rollup/plugin-node-resolve"));
var rollup_plugin_1 = require("./rollup-plugin");
var get_svelte_entry_1 = require("./get-svelte-entry");
function cli(process) {
return __awaiter(this, void 0, void 0, function () {
var options, input, rollup_bundle, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
options = process.argv
.slice(2)
.map(function (arg) {
var _a;
var _b = arg.split("="), flag = _b[0], value = _b[1];
var key = flag.slice(2);
return _a = {}, _a[key] = value === undefined ? true : value, _a;
})
.reduce(function (a, c) { return (__assign(__assign({}, a), c)); }, {});
input = (0, get_svelte_entry_1.getSvelteEntry)() || "src/index.js";
return [4 /*yield*/, Rollup.rollup({
input: input,
plugins: [
// @ts-ignore
svelte(),
(0, plugin_node_resolve_1.default)(),
],
})];
case 1:
rollup_bundle = _a.sent();
return [4 /*yield*/, rollup_bundle.generate({})];
case 2:
_a.sent();
return [4 /*yield*/, (0, rollup_plugin_1.generateBundle)(input, (options === null || options === void 0 ? void 0 : options.glob) === true)];
case 3:
result = _a.sent();
(0, rollup_plugin_1.writeOutput)(result, options, input);
return [2 /*return*/];
}
});
});
await rollup_bundle.generate({});
const result = await (0, rollup_plugin_1.generateBundle)(input, options?.glob === true);
(0, rollup_plugin_1.writeOutput)(result, options, input);
}
exports.cli = cli;

@@ -45,2 +45,3 @@ interface ComponentParserDiagnostics {

}
type ComponentGenerics = [name: string, type: string];
interface ComponentInlineElement {

@@ -65,2 +66,3 @@ type: "InlineComponent";

typedefs: TypeDef[];
generics: null | ComponentGenerics;
rest_props: RestProps;

@@ -85,2 +87,3 @@ extends?: Extends;

private readonly typedefs;
private readonly generics;
private readonly bindings;

@@ -87,0 +90,0 @@ constructor(options?: ComponentParserOptions);

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -25,36 +36,42 @@ if (k2 === undefined) k2 = k;

};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
// TODO: upgrading to Svelte 4 shows a lot of TS errors. Ignore for now but resolve.
// @ts-nocheck
const commentParser = __importStar(require("comment-parser"));
const compiler_1 = require("svelte/compiler");
const element_tag_map_1 = require("./element-tag-map");
const DEFAULT_SLOT_NAME = "__default__";
class ComponentParser {
options;
source;
compiled;
parsed;
rest_props;
extends;
componentComment;
reactive_vars = new Set();
vars = new Set();
props = new Map();
moduleExports = new Map();
slots = new Map();
events = new Map();
typedefs = new Map();
bindings = new Map();
constructor(options) {
var commentParser = __importStar(require("comment-parser"));
var compiler_1 = require("svelte/compiler");
var element_tag_map_1 = require("./element-tag-map");
var DEFAULT_SLOT_NAME = "__default__";
var ComponentParser = /** @class */ (function () {
function ComponentParser(options) {
this.reactive_vars = new Set();
this.vars = new Set();
this.props = new Map();
this.moduleExports = new Map();
this.slots = new Map();
this.events = new Map();
this.typedefs = new Map();
this.generics = null;
this.bindings = new Map();
this.options = options;
}
static mapToArray(map) {
return Array.from(map, ([key, value]) => value);
}
static assignValue(value) {
ComponentParser.mapToArray = function (map) {
return Array.from(map, function (_a) {
var key = _a[0], value = _a[1];
return value;
});
};
ComponentParser.assignValue = function (value) {
return value === undefined || value === "" ? undefined : value;
}
static formatComment(comment) {
let formatted_comment = comment;
};
ComponentParser.formatComment = function (comment) {
var formatted_comment = comment;
if (!formatted_comment.startsWith("/*")) {

@@ -67,20 +84,24 @@ formatted_comment = "/*" + formatted_comment;

return formatted_comment;
}
sourceAtPos(start, end) {
return this.source?.slice(start, end);
}
collectReactiveVars() {
this.compiled?.vars
.filter(({ reassigned, writable }) => reassigned && writable)
.forEach(({ name }) => this.reactive_vars.add(name));
}
addProp(prop_name, data) {
};
ComponentParser.prototype.sourceAtPos = function (start, end) {
var _a;
return (_a = this.source) === null || _a === void 0 ? void 0 : _a.slice(start, end);
};
ComponentParser.prototype.collectReactiveVars = function () {
var _this = this;
var _a;
(_a = this.compiled) === null || _a === void 0 ? void 0 : _a.vars.filter(function (_a) {
var reassigned = _a.reassigned, writable = _a.writable;
return reassigned && writable;
}).forEach(function (_a) {
var name = _a.name;
return _this.reactive_vars.add(name);
});
};
ComponentParser.prototype.addProp = function (prop_name, data) {
if (ComponentParser.assignValue(prop_name) === undefined)
return;
if (this.props.has(prop_name)) {
const existing_slot = this.props.get(prop_name);
this.props.set(prop_name, {
...existing_slot,
...data,
});
var existing_slot = this.props.get(prop_name);
this.props.set(prop_name, __assign(__assign({}, existing_slot), data));
}

@@ -90,12 +111,9 @@ else {

}
}
addModuleExport(prop_name, data) {
};
ComponentParser.prototype.addModuleExport = function (prop_name, data) {
if (ComponentParser.assignValue(prop_name) === undefined)
return;
if (this.moduleExports.has(prop_name)) {
const existing_slot = this.moduleExports.get(prop_name);
this.moduleExports.set(prop_name, {
...existing_slot,
...data,
});
var existing_slot = this.moduleExports.get(prop_name);
this.moduleExports.set(prop_name, __assign(__assign({}, existing_slot), data));
}

@@ -105,34 +123,33 @@ else {

}
}
aliasType(type) {
};
ComponentParser.prototype.aliasType = function (type) {
if (type === "*")
return "any";
return type;
}
addSlot({ slot_name, slot_props, slot_fallback, slot_description, }) {
const default_slot = slot_name === undefined || slot_name === "";
const name = default_slot ? DEFAULT_SLOT_NAME : slot_name;
const fallback = ComponentParser.assignValue(slot_fallback);
const props = ComponentParser.assignValue(slot_props);
const description = slot_description?.split("-").pop()?.trim();
};
ComponentParser.prototype.addSlot = function (_a) {
var _b;
var slot_name = _a.slot_name, slot_props = _a.slot_props, slot_fallback = _a.slot_fallback, slot_description = _a.slot_description;
var default_slot = slot_name === undefined || slot_name === "";
var name = default_slot ? DEFAULT_SLOT_NAME : slot_name;
var fallback = ComponentParser.assignValue(slot_fallback);
var props = ComponentParser.assignValue(slot_props);
var description = (_b = slot_description === null || slot_description === void 0 ? void 0 : slot_description.split("-").pop()) === null || _b === void 0 ? void 0 : _b.trim();
if (this.slots.has(name)) {
const existing_slot = this.slots.get(name);
this.slots.set(name, {
...existing_slot,
fallback,
slot_props: existing_slot.slot_props === undefined ? props : existing_slot.slot_props,
description: existing_slot.description || description,
});
var existing_slot = this.slots.get(name);
this.slots.set(name, __assign(__assign({}, existing_slot), { fallback: fallback, slot_props: existing_slot.slot_props === undefined ? props : existing_slot.slot_props, description: existing_slot.description || description }));
}
else {
this.slots.set(name, {
name,
name: name,
default: default_slot,
fallback,
slot_props,
description,
fallback: fallback,
slot_props: slot_props,
description: description,
});
}
}
addDispatchedEvent({ name, detail, has_argument, description, }) {
};
ComponentParser.prototype.addDispatchedEvent = function (_a) {
var _b;
var name = _a.name, detail = _a.detail, has_argument = _a.has_argument, description = _a.description;
if (name === undefined)

@@ -145,11 +162,7 @@ return;

*/
const default_detail = !has_argument && !detail ? "null" : ComponentParser.assignValue(detail);
const event_description = description?.split("-").pop()?.trim();
var default_detail = !has_argument && !detail ? "null" : ComponentParser.assignValue(detail);
var event_description = (_b = description === null || description === void 0 ? void 0 : description.split("-").pop()) === null || _b === void 0 ? void 0 : _b.trim();
if (this.events.has(name)) {
const existing_event = this.events.get(name);
this.events.set(name, {
...existing_event,
detail: existing_event.detail === undefined ? default_detail : existing_event.detail,
description: existing_event.description || event_description,
});
var existing_event = this.events.get(name);
this.events.set(name, __assign(__assign({}, existing_event), { detail: existing_event.detail === undefined ? default_detail : existing_event.detail, description: existing_event.description || event_description }));
}

@@ -159,3 +172,3 @@ else {

type: "dispatched",
name,
name: name,
detail: default_detail,

@@ -165,10 +178,13 @@ description: event_description,

}
}
parseCustomTypes() {
commentParser.parse(this.source, { spacing: "preserve" }).forEach(({ tags }) => {
tags.forEach(({ tag, type: tagType, name, description }) => {
const type = this.aliasType(tagType);
};
ComponentParser.prototype.parseCustomTypes = function () {
var _this = this;
commentParser.parse(this.source, { spacing: "preserve" }).forEach(function (_a) {
var tags = _a.tags;
tags.forEach(function (_a) {
var tag = _a.tag, tagType = _a.type, name = _a.name, description = _a.description;
var type = _this.aliasType(tagType);
switch (tag) {
case "extends":
this.extends = {
_this.extends = {
interface: name,

@@ -179,3 +195,3 @@ import: type,

case "restProps":
this.rest_props = {
_this.rest_props = {
type: "Element",

@@ -186,3 +202,3 @@ name: type,

case "slot":
this.addSlot({
_this.addSlot({
slot_name: name,

@@ -194,4 +210,4 @@ slot_props: type,

case "event":
this.addDispatchedEvent({
name,
_this.addDispatchedEvent({
name: name,
detail: type,

@@ -203,14 +219,17 @@ has_argument: false,

case "typedef":
this.typedefs.set(name, {
type,
name,
_this.typedefs.set(name, {
type: type,
name: name,
description: ComponentParser.assignValue(description),
ts: /(\}|\};)$/.test(type) ? `interface ${name} ${type}` : `type ${name} = ${type}`,
ts: /(\}|\};)$/.test(type) ? "interface ".concat(name, " ").concat(type) : "type ".concat(name, " = ").concat(type),
});
break;
case "generics":
_this.generics = [name, type];
break;
}
});
});
}
cleanup() {
};
ComponentParser.prototype.cleanup = function () {
this.source = undefined;

@@ -228,7 +247,10 @@ this.compiled = undefined;

this.typedefs.clear();
this.generics = null;
this.bindings.clear();
}
parseSvelteComponent(source, diagnostics) {
if (this.options?.verbose) {
console.log(`[parsing] "${diagnostics.moduleName}" ${diagnostics.filePath}`);
};
ComponentParser.prototype.parseSvelteComponent = function (source, diagnostics) {
var _this = this;
var _a, _b, _c;
if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.verbose) {
console.log("[parsing] \"".concat(diagnostics.moduleName, "\" ").concat(diagnostics.filePath));
}

@@ -241,14 +263,15 @@ this.cleanup();

this.parseCustomTypes();
if (this.parsed?.module) {
(0, compiler_1.walk)(this.parsed?.module, {
enter: (node) => {
if ((_b = this.parsed) === null || _b === void 0 ? void 0 : _b.module) {
(0, compiler_1.walk)((_c = this.parsed) === null || _c === void 0 ? void 0 : _c.module, {
enter: function (node) {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (node.type === "ExportNamedDeclaration") {
const { type: declaration_type, id, init, body, } = node.declaration?.declarations ? node.declaration.declarations[0] : node.declaration;
let prop_name = id.name;
let value = undefined;
let type = undefined;
let kind = node.declaration.kind;
let description = undefined;
let isFunction = false;
let isFunctionDeclaration = false;
var _j = ((_a = node.declaration) === null || _a === void 0 ? void 0 : _a.declarations) ? node.declaration.declarations[0] : node.declaration, declaration_type = _j.type, id = _j.id, init = _j.init, body = _j.body;
var prop_name = id.name;
var value = undefined;
var type = undefined;
var kind = node.declaration.kind;
var description = undefined;
var isFunction = false;
var isFunctionDeclaration = false;
if (init != null) {

@@ -259,7 +282,7 @@ if (init.type === "ObjectExpression" ||

init.type === "ArrowFunctionExpression") {
value = this.sourceAtPos(init.start, init.end)?.replace(/[\r\n]+/g, " ");
value = (_b = _this.sourceAtPos(init.start, init.end)) === null || _b === void 0 ? void 0 : _b.replace(/[\r\n]+/g, " ");
type = value;
isFunction = init.type === "ArrowFunctionExpression";
if (init.type === "BinaryExpression") {
if (init?.left.type === "Literal" && typeof init?.left.value === "string") {
if ((init === null || init === void 0 ? void 0 : init.left.type) === "Literal" && typeof (init === null || init === void 0 ? void 0 : init.left.value) === "string") {
type = "string";

@@ -271,4 +294,4 @@ }

if (init.type === "UnaryExpression") {
value = this.sourceAtPos(init.start, init.end);
type = typeof init.argument?.value;
value = _this.sourceAtPos(init.start, init.end);
type = typeof ((_c = init.argument) === null || _c === void 0 ? void 0 : _c.value);
}

@@ -282,3 +305,3 @@ else {

if (declaration_type === "FunctionDeclaration") {
value = "() => " + this.sourceAtPos(body.start, body.end)?.replace(/[\r\n]+/g, " ");
value = "() => " + ((_d = _this.sourceAtPos(body.start, body.end)) === null || _d === void 0 ? void 0 : _d.replace(/[\r\n]+/g, " "));
type = "() => any";

@@ -290,22 +313,22 @@ kind = "function";

if (node.leadingComments) {
const last_comment = node.leadingComments[node.leadingComments.length - 1];
const comment = commentParser.parse(ComponentParser.formatComment(last_comment.value), {
var last_comment = node.leadingComments[node.leadingComments.length - 1];
var comment = commentParser.parse(ComponentParser.formatComment(last_comment.value), {
spacing: "preserve",
});
const tag = comment[0]?.tags[comment[0]?.tags.length - 1];
if (tag?.tag === "type")
type = this.aliasType(tag.type);
description = ComponentParser.assignValue(comment[0]?.description?.trim());
var tag = (_e = comment[0]) === null || _e === void 0 ? void 0 : _e.tags[((_f = comment[0]) === null || _f === void 0 ? void 0 : _f.tags.length) - 1];
if ((tag === null || tag === void 0 ? void 0 : tag.tag) === "type")
type = _this.aliasType(tag.type);
description = ComponentParser.assignValue((_h = (_g = comment[0]) === null || _g === void 0 ? void 0 : _g.description) === null || _h === void 0 ? void 0 : _h.trim());
}
if (!description && this.typedefs.has(type)) {
description = this.typedefs.get(type).description;
if (!description && _this.typedefs.has(type)) {
description = _this.typedefs.get(type).description;
}
this.addModuleExport(prop_name, {
_this.addModuleExport(prop_name, {
name: prop_name,
kind,
description,
type,
value,
isFunction,
isFunctionDeclaration,
kind: kind,
description: description,
type: type,
value: value,
isFunction: isFunction,
isFunctionDeclaration: isFunctionDeclaration,
isRequired: false,

@@ -319,9 +342,10 @@ constant: kind === "const",

}
let dispatcher_name = undefined;
let callees = [];
var dispatcher_name = undefined;
var callees = [];
(0, compiler_1.walk)({ html: this.parsed.html, instance: this.parsed.instance }, {
enter: (node, parent, prop) => {
enter: function (node, parent, prop) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
if (node.type === "CallExpression") {
if (node.callee.name === "createEventDispatcher") {
dispatcher_name = parent?.id.name;
dispatcher_name = parent === null || parent === void 0 ? void 0 : parent.id.name;
}

@@ -333,5 +357,5 @@ callees.push({

}
if (node.type === "Spread" && node?.expression.name === "$$restProps") {
if (this.rest_props === undefined && (parent?.type === "InlineComponent" || parent?.type === "Element")) {
this.rest_props = {
if (node.type === "Spread" && (node === null || node === void 0 ? void 0 : node.expression.name) === "$$restProps") {
if (_this.rest_props === undefined && ((parent === null || parent === void 0 ? void 0 : parent.type) === "InlineComponent" || (parent === null || parent === void 0 ? void 0 : parent.type) === "Element")) {
_this.rest_props = {
type: parent.type,

@@ -343,3 +367,3 @@ name: parent.name,

if (node.type === "VariableDeclaration") {
this.vars.add(node);
_this.vars.add(node);
}

@@ -352,26 +376,26 @@ if (node.type === "ExportNamedDeclaration") {

// Handle renamed exports
let prop_name;
if (node.declaration == null && node.specifiers[0]?.type === "ExportSpecifier") {
const specifier = node.specifiers[0];
const localName = specifier.local.name, exportedName = specifier.exported.name;
let declaration;
var prop_name = void 0;
if (node.declaration == null && ((_a = node.specifiers[0]) === null || _a === void 0 ? void 0 : _a.type) === "ExportSpecifier") {
var specifier = node.specifiers[0];
var localName_1 = specifier.local.name, exportedName = specifier.exported.name;
var declaration_1;
// Search through all variable declarations for this variable
// Limitation: the variable must have been declared before the export
this.vars.forEach((varDecl) => {
if (varDecl.declarations.some((decl) => decl.id.type === "Identifier" && decl.id.name === localName)) {
declaration = varDecl;
_this.vars.forEach(function (varDecl) {
if (varDecl.declarations.some(function (decl) { return decl.id.type === "Identifier" && decl.id.name === localName_1; })) {
declaration_1 = varDecl;
}
});
node.declaration = declaration;
node.declaration = declaration_1;
prop_name = exportedName;
}
const { type: declaration_type, id, init, body, } = node.declaration.declarations ? node.declaration.declarations[0] : node.declaration;
prop_name ??= id.name;
let value = undefined;
let type = undefined;
let kind = node.declaration.kind;
let description = undefined;
let isFunction = false;
let isFunctionDeclaration = false;
let isRequired = kind === "let" && init == null;
var _q = node.declaration.declarations ? node.declaration.declarations[0] : node.declaration, declaration_type = _q.type, id = _q.id, init = _q.init, body = _q.body;
prop_name !== null && prop_name !== void 0 ? prop_name : (prop_name = id.name);
var value = undefined;
var type = undefined;
var kind = node.declaration.kind;
var description_1 = undefined;
var isFunction = false;
var isFunctionDeclaration = false;
var isRequired = kind === "let" && init == null;
if (init != null) {

@@ -382,7 +406,7 @@ if (init.type === "ObjectExpression" ||

init.type === "ArrowFunctionExpression") {
value = this.sourceAtPos(init.start, init.end)?.replace(/[\r\n]+/g, " ");
value = (_b = _this.sourceAtPos(init.start, init.end)) === null || _b === void 0 ? void 0 : _b.replace(/[\r\n]+/g, " ");
type = value;
isFunction = init.type === "ArrowFunctionExpression";
if (init.type === "BinaryExpression") {
if (init?.left.type === "Literal" && typeof init?.left.value === "string") {
if ((init === null || init === void 0 ? void 0 : init.left.type) === "Literal" && typeof (init === null || init === void 0 ? void 0 : init.left.value) === "string") {
type = "string";

@@ -394,4 +418,4 @@ }

if (init.type === "UnaryExpression") {
value = this.sourceAtPos(init.start, init.end);
type = typeof init.argument?.value;
value = _this.sourceAtPos(init.start, init.end);
type = typeof ((_c = init.argument) === null || _c === void 0 ? void 0 : _c.value);
}

@@ -405,3 +429,3 @@ else {

if (declaration_type === "FunctionDeclaration") {
value = "() => " + this.sourceAtPos(body.start, body.end)?.replace(/[\r\n]+/g, " ");
value = "() => " + ((_d = _this.sourceAtPos(body.start, body.end)) === null || _d === void 0 ? void 0 : _d.replace(/[\r\n]+/g, " "));
type = "() => any";

@@ -413,46 +437,48 @@ kind = "function";

if (node.leadingComments) {
const last_comment = node.leadingComments[node.leadingComments.length - 1];
const comment = commentParser.parse(ComponentParser.formatComment(last_comment.value), {
var last_comment = node.leadingComments[node.leadingComments.length - 1];
var comment = commentParser.parse(ComponentParser.formatComment(last_comment.value), {
spacing: "preserve",
});
const tag = comment[0]?.tags[comment[0]?.tags.length - 1];
if (tag?.tag === "type")
type = this.aliasType(tag.type);
description = ComponentParser.assignValue(comment[0]?.description?.trim());
const additional_tags = comment[0]?.tags.filter((tag) => !["type", "extends", "restProps", "slot", "event", "typedef"].includes(tag.tag)) ?? [];
if (additional_tags.length > 0 && description === undefined) {
description = "";
var tag = (_e = comment[0]) === null || _e === void 0 ? void 0 : _e.tags[((_f = comment[0]) === null || _f === void 0 ? void 0 : _f.tags.length) - 1];
if ((tag === null || tag === void 0 ? void 0 : tag.tag) === "type")
type = _this.aliasType(tag.type);
description_1 = ComponentParser.assignValue((_h = (_g = comment[0]) === null || _g === void 0 ? void 0 : _g.description) === null || _h === void 0 ? void 0 : _h.trim());
var additional_tags = (_k = (_j = comment[0]) === null || _j === void 0 ? void 0 : _j.tags.filter(function (tag) { return !["type", "extends", "restProps", "slot", "event", "typedef"].includes(tag.tag); })) !== null && _k !== void 0 ? _k : [];
if (additional_tags.length > 0 && description_1 === undefined) {
description_1 = "";
}
additional_tags.forEach((tag) => {
description += `${description ? "\n" : ""}@${tag.tag} ${tag.name}${tag.description ? ` ${tag.description}` : ""}`;
additional_tags.forEach(function (tag) {
description_1 += "".concat(description_1 ? "\n" : "", "@").concat(tag.tag, " ").concat(tag.name).concat(tag.description ? " ".concat(tag.description) : "");
});
}
if (!description && this.typedefs.has(type)) {
description = this.typedefs.get(type).description;
if (!description_1 && _this.typedefs.has(type)) {
description_1 = _this.typedefs.get(type).description;
}
this.addProp(prop_name, {
_this.addProp(prop_name, {
name: prop_name,
kind,
description,
type,
value,
isFunction,
isFunctionDeclaration,
isRequired,
kind: kind,
description: description_1,
type: type,
value: value,
isFunction: isFunction,
isFunctionDeclaration: isFunctionDeclaration,
isRequired: isRequired,
constant: kind === "const",
reactive: this.reactive_vars.has(prop_name),
reactive: _this.reactive_vars.has(prop_name),
});
}
if (node.type === "Comment") {
let data = node?.data?.trim() ?? "";
var data = (_m = (_l = node === null || node === void 0 ? void 0 : node.data) === null || _l === void 0 ? void 0 : _l.trim()) !== null && _m !== void 0 ? _m : "";
if (/^@component/.test(data)) {
this.componentComment = data.replace(/^@component/, "").replace(/\r/g, "");
_this.componentComment = data.replace(/^@component/, "").replace(/\r/g, "");
}
}
if (node.type === "Slot") {
const slot_name = node.attributes.find((attr) => attr.name === "name")?.value[0].data;
const slot_props = node.attributes
.filter((attr) => attr.name !== "name")
.reduce((slot_props, { name, value }) => {
let slot_prop_value = {
var slot_name = (_o = node.attributes.find(function (attr) { return attr.name === "name"; })) === null || _o === void 0 ? void 0 : _o.value[0].data;
var slot_props = node.attributes
.filter(function (attr) { return attr.name !== "name"; })
.reduce(function (slot_props, _a) {
var _b;
var name = _a.name, value = _a.value;
var slot_prop_value = {
value: undefined,

@@ -464,3 +490,3 @@ replace: false,

if (value[0]) {
const { type, expression, raw, start, end } = value[0];
var _c = value[0], type = _c.type, expression = _c.expression, raw = _c.raw, start = _c.start, end = _c.end;
if (type === "Text") {

@@ -479,6 +505,6 @@ slot_prop_value.value = raw;

if (expression.type === "ObjectExpression" || expression.type === "TemplateLiteral") {
slot_prop_value.value = this.sourceAtPos(start + 1, end - 1);
slot_prop_value.value = _this.sourceAtPos(start + 1, end - 1);
}
else {
slot_prop_value.value = this.sourceAtPos(start, end);
slot_prop_value.value = _this.sourceAtPos(start, end);
}

@@ -488,10 +514,10 @@ }

}
return { ...slot_props, [name]: slot_prop_value };
return __assign(__assign({}, slot_props), (_b = {}, _b[name] = slot_prop_value, _b));
}, {});
const fallback = node.children
?.map(({ start, end }) => this.sourceAtPos(start, end))
.join("")
.trim();
this.addSlot({
slot_name,
var fallback = (_p = node.children) === null || _p === void 0 ? void 0 : _p.map(function (_a) {
var start = _a.start, end = _a.end;
return _this.sourceAtPos(start, end);
}).join("").trim();
_this.addSlot({
slot_name: slot_name,
slot_props: JSON.stringify(slot_props, null, 2),

@@ -502,4 +528,4 @@ slot_fallback: fallback,

if (node.type === "EventHandler" && node.expression == null) {
if (!this.events.has(node.name) && parent !== undefined) {
this.events.set(node.name, {
if (!_this.events.has(node.name) && parent !== undefined) {
_this.events.set(node.name, {
type: "forwarded",

@@ -511,16 +537,13 @@ name: node.name,

}
if (parent?.type === "Element" && node.type === "Binding" && node.name === "this") {
const prop_name = node.expression.name;
const element_name = parent.name;
if (this.bindings.has(prop_name)) {
const existing_bindings = this.bindings.get(prop_name);
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "Element" && node.type === "Binding" && node.name === "this") {
var prop_name = node.expression.name;
var element_name = parent.name;
if (_this.bindings.has(prop_name)) {
var existing_bindings = _this.bindings.get(prop_name);
if (!existing_bindings.elements.includes(element_name)) {
this.bindings.set(prop_name, {
...existing_bindings,
elements: [...existing_bindings.elements, element_name],
});
_this.bindings.set(prop_name, __assign(__assign({}, existing_bindings), { elements: __spreadArray(__spreadArray([], existing_bindings.elements, true), [element_name], false) }));
}
}
else {
this.bindings.set(prop_name, {
_this.bindings.set(prop_name, {
elements: [element_name],

@@ -533,8 +556,9 @@ });

if (dispatcher_name !== undefined) {
callees.forEach((callee) => {
callees.forEach(function (callee) {
var _a;
if (callee.name === dispatcher_name) {
const event_name = callee.arguments[0]?.value;
const event_argument = callee.arguments[1];
const event_detail = event_argument?.value;
this.addDispatchedEvent({
var event_name = (_a = callee.arguments[0]) === null || _a === void 0 ? void 0 : _a.value;
var event_argument = callee.arguments[1];
var event_detail = event_argument === null || event_argument === void 0 ? void 0 : event_argument.value;
_this.addDispatchedEvent({
name: event_name,

@@ -548,13 +572,10 @@ detail: event_detail,

return {
props: ComponentParser.mapToArray(this.props).map((prop) => {
if (this.bindings.has(prop.name)) {
return {
...prop,
type: "null | " +
this.bindings
props: ComponentParser.mapToArray(this.props).map(function (prop) {
if (_this.bindings.has(prop.name)) {
return __assign(__assign({}, prop), { type: "null | " +
_this.bindings
.get(prop.name)
.elements.sort()
.map((element) => (0, element_tag_map_1.getElementByTag)(element))
.join(" | "),
};
.map(function (element) { return (0, element_tag_map_1.getElementByTag)(element); })
.join(" | ") });
}

@@ -565,16 +586,17 @@ return prop;

slots: ComponentParser.mapToArray(this.slots)
.map((slot) => {
.map(function (slot) {
try {
const slot_props = JSON.parse(slot.slot_props);
const new_props = [];
Object.keys(slot_props).forEach((key) => {
if (slot_props[key].replace && slot_props[key].value !== undefined) {
slot_props[key].value = this.props.get(slot_props[key].value)?.type;
var slot_props_1 = JSON.parse(slot.slot_props);
var new_props_1 = [];
Object.keys(slot_props_1).forEach(function (key) {
var _a;
if (slot_props_1[key].replace && slot_props_1[key].value !== undefined) {
slot_props_1[key].value = (_a = _this.props.get(slot_props_1[key].value)) === null || _a === void 0 ? void 0 : _a.type;
}
if (slot_props[key].value === undefined)
slot_props[key].value = "any";
new_props.push(`${key}: ${slot_props[key].value}`);
if (slot_props_1[key].value === undefined)
slot_props_1[key].value = "any";
new_props_1.push("".concat(key, ": ").concat(slot_props_1[key].value));
});
const formatted_slot_props = new_props.length === 0 ? "{}" : "{ " + new_props.join(", ") + " }";
return { ...slot, slot_props: formatted_slot_props };
var formatted_slot_props = new_props_1.length === 0 ? "{}" : "{ " + new_props_1.join(", ") + " }";
return __assign(__assign({}, slot), { slot_props: formatted_slot_props });
}

@@ -585,3 +607,3 @@ catch (e) {

})
.sort((a, b) => {
.sort(function (a, b) {
if (a.name < b.name)

@@ -595,2 +617,3 @@ return -1;

typedefs: ComponentParser.mapToArray(this.typedefs),
generics: this.generics,
rest_props: this.rest_props,

@@ -600,4 +623,5 @@ extends: this.extends,

};
}
}
};
return ComponentParser;
}());
exports.default = ComponentParser;

@@ -5,10 +5,11 @@ "use strict";

function createExports(parsed_exports, components) {
const source = Object.entries(parsed_exports).map(([id, exportee]) => {
let module_exports = [];
var source = Object.entries(parsed_exports).map(function (_a) {
var id = _a[0], exportee = _a[1];
var module_exports = [];
if (components.has(id)) {
module_exports = components.get(id).moduleExports.map((moduleExport) => {
module_exports = components.get(id).moduleExports.map(function (moduleExport) {
return moduleExport.name;
});
}
let named_exports = "";
var named_exports = "";
if (module_exports.length > 0)

@@ -18,7 +19,7 @@ named_exports = ", " + module_exports.join(", ");

if (exportee.mixed) {
return `export { default as ${id}${named_exports} } from "${exportee.source}";\nexport { default } from "${exportee.source}";`;
return "export { default as ".concat(id).concat(named_exports, " } from \"").concat(exportee.source, "\";\nexport { default } from \"").concat(exportee.source, "\";");
}
return `export { default${named_exports} } from "${exportee.source}";`;
return "export { default".concat(named_exports, " } from \"").concat(exportee.source, "\";");
}
return `export { default as ${id}${named_exports} } from "${exportee.source}";`;
return "export { default as ".concat(id).concat(named_exports, " } from \"").concat(exportee.source, "\";");
});

@@ -25,0 +26,0 @@ return source.join("\n");

@@ -6,3 +6,3 @@ "use strict";

// https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts#L19263
const tag_map = {
var tag_map = {
a: "HTMLAnchorElement",

@@ -9,0 +9,0 @@ applet: "HTMLAppletElement",

@@ -27,4 +27,4 @@ "use strict";

exports.getSvelteEntry = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
var fs = __importStar(require("fs"));
var path = __importStar(require("path"));
/**

@@ -36,3 +36,3 @@ * Get the file path entry point for uncompiled Svelte source code

if (entryPoint) {
const entry_path = path.join(process.cwd(), entryPoint);
var entry_path = path.join(process.cwd(), entryPoint);
if (fs.existsSync(entry_path)) {

@@ -42,9 +42,9 @@ return entryPoint;

else {
console.log(`Invalid entry point: ${entry_path}.`);
console.log("Invalid entry point: ".concat(entry_path, "."));
return null;
}
}
const pkg_path = path.join(process.cwd(), "package.json");
var pkg_path = path.join(process.cwd(), "package.json");
if (fs.existsSync(pkg_path)) {
const pkg = JSON.parse(fs.readFileSync(pkg_path, "utf-8"));
var pkg = JSON.parse(fs.readFileSync(pkg_path, "utf-8"));
if (pkg.svelte !== undefined)

@@ -51,0 +51,0 @@ return pkg.svelte;

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -30,16 +41,17 @@ if (k2 === undefined) k2 = k;

exports.parseExports = void 0;
const acorn = __importStar(require("acorn"));
const fs = __importStar(require("fs"));
const path_1 = __importDefault(require("path"));
const path_2 = require("./path");
var acorn = __importStar(require("acorn"));
var fs = __importStar(require("fs"));
var path_1 = __importDefault(require("path"));
var path_2 = require("./path");
function parseExports(source, dir) {
const ast = acorn.parse(source, {
var ast = acorn.parse(source, {
ecmaVersion: "latest",
sourceType: "module",
});
const exports_by_identifier = {};
var exports_by_identifier = {};
// @ts-ignore
ast.body.forEach((node) => {
ast.body.forEach(function (node) {
var _a, _b, _c, _d;
if (node.type === "ExportDefaultDeclaration") {
const id = node.declaration.name;
var id = node.declaration.name;
if (id in exports_by_identifier) {

@@ -55,6 +67,7 @@ exports_by_identifier[id].default = true;

return;
let file_path = path_1.default.resolve(dir, node.source.value);
var file_path = path_1.default.resolve(dir, node.source.value);
if (!fs.lstatSync(file_path).isFile()) {
const files = fs.readdirSync(file_path);
for (const file of files)
var files = fs.readdirSync(file_path);
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
var file = files_1[_i];
if (file.includes("index")) {

@@ -64,17 +77,17 @@ file_path = path_1.default.join(file_path, file);

}
}
}
const export_file = fs.readFileSync(file_path, "utf-8");
const exports = parseExports(export_file, path_1.default.dirname(file_path));
for (const [key, value] of Object.entries(exports)) {
const source = (0, path_2.normalizeSeparators)("./" + path_1.default.join(node.source.value, value.source));
exports_by_identifier[key] = {
...value,
source,
};
var export_file = fs.readFileSync(file_path, "utf-8");
var exports_1 = parseExports(export_file, path_1.default.dirname(file_path));
for (var _e = 0, _f = Object.entries(exports_1); _e < _f.length; _e++) {
var _g = _f[_e], key = _g[0], value = _g[1];
var source_1 = (0, path_2.normalizeSeparators)("./" + path_1.default.join(node.source.value, value.source));
exports_by_identifier[key] = __assign(__assign({}, value), { source: source_1 });
}
}
else if (node.type === "ExportNamedDeclaration") {
node.specifiers.forEach((specifier) => {
const exported_name = specifier.exported.name;
const id = exported_name || specifier.local.name;
node.specifiers.forEach(function (specifier) {
var _a, _b, _c, _d;
var exported_name = specifier.exported.name;
var id = exported_name || specifier.local.name;
if (id in exports_by_identifier) {

@@ -85,3 +98,3 @@ if (node.type === "ExportNamedDeclaration") {

if (!exports_by_identifier[id].source) {
exports_by_identifier[id].source = node.source?.value ?? "";
exports_by_identifier[id].source = (_b = (_a = node.source) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : "";
}

@@ -91,3 +104,3 @@ }

exports_by_identifier[id] = {
source: node.source?.value ?? "",
source: (_d = (_c = node.source) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : "",
default: id === "default",

@@ -99,6 +112,6 @@ };

else if (node.type === "ImportDeclaration") {
const id = node.specifiers[0].local.name;
var id = node.specifiers[0].local.name;
if (id in exports_by_identifier) {
if (!exports_by_identifier[id].source) {
exports_by_identifier[id].source = node.source?.value ?? "";
exports_by_identifier[id].source = (_b = (_a = node.source) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : "";
}

@@ -108,3 +121,3 @@ }

exports_by_identifier[id] = {
source: node.source?.value ?? "",
source: (_d = (_c = node.source) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : "",
default: id === "default",

@@ -111,0 +124,0 @@ };

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeSeparators = void 0;
const path_1 = require("path");
var path_1 = require("path");
/**

@@ -6,0 +6,0 @@ * Normalize directory separators to always use `/`.

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -25,2 +36,38 @@ if (k2 === undefined) k2 = k;

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -31,29 +78,39 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.writeOutput = exports.generateBundle = void 0;
const fs = __importStar(require("fs"));
const fsp = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const fg = __importStar(require("fast-glob"));
const writer_ts_definitions_1 = __importDefault(require("./writer/writer-ts-definitions"));
const writer_json_1 = __importDefault(require("./writer/writer-json"));
const writer_markdown_1 = __importDefault(require("./writer/writer-markdown"));
const ComponentParser_1 = __importDefault(require("./ComponentParser"));
const get_svelte_entry_1 = require("./get-svelte-entry");
const parse_exports_1 = require("./parse-exports");
const compiler_1 = require("svelte/compiler");
const svelte_preprocess_1 = require("svelte-preprocess");
const path_1 = require("./path");
var fs = __importStar(require("fs"));
var fsp = __importStar(require("fs/promises"));
var path = __importStar(require("path"));
var fg = __importStar(require("fast-glob"));
var writer_ts_definitions_1 = __importDefault(require("./writer/writer-ts-definitions"));
var writer_json_1 = __importDefault(require("./writer/writer-json"));
var writer_markdown_1 = __importDefault(require("./writer/writer-markdown"));
var ComponentParser_1 = __importDefault(require("./ComponentParser"));
var get_svelte_entry_1 = require("./get-svelte-entry");
var parse_exports_1 = require("./parse-exports");
var compiler_1 = require("svelte/compiler");
var svelte_preprocess_1 = require("svelte-preprocess");
var path_1 = require("./path");
function pluginSveld(opts) {
let result;
let input;
var result;
var input;
return {
name: "plugin-sveld",
buildStart() {
buildStart: function () {
input = (0, get_svelte_entry_1.getSvelteEntry)();
},
async generateBundle() {
if (input != null) {
result = await generateBundle(input, opts?.glob === true);
}
generateBundle: function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(input != null)) return [3 /*break*/, 2];
return [4 /*yield*/, generateBundle(input, (opts === null || opts === void 0 ? void 0 : opts.glob) === true)];
case 1:
result = _a.sent();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
},
writeBundle() {
writeBundle: function () {
if (input != null)

@@ -65,72 +122,72 @@ writeOutput(result, opts || {}, input);

exports.default = pluginSveld;
async function generateBundle(input, glob) {
const dir = fs.lstatSync(input).isFile() ? path.dirname(input) : input;
const entry = fs.readFileSync(input, "utf-8");
const exports = (0, parse_exports_1.parseExports)(entry, dir);
if (glob) {
fg.sync([`${dir}/**/*.svelte`]).forEach((file) => {
const moduleName = path.parse(file).name.replace(/\-/g, "");
let source = (0, path_1.normalizeSeparators)("./" + path.relative(dir, file));
if (exports[moduleName]) {
exports[moduleName].source = source;
function generateBundle(input, glob) {
return __awaiter(this, void 0, void 0, function () {
var dir, entry, exports, components, parser, exportEntries, _i, exportEntries_1, _a, exportName, entry_1, filePath, _b, ext, name_1, moduleName, source, processed;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
dir = fs.lstatSync(input).isFile() ? path.dirname(input) : input;
entry = fs.readFileSync(input, "utf-8");
exports = (0, parse_exports_1.parseExports)(entry, dir);
if (glob) {
fg.sync(["".concat(dir, "/**/*.svelte")]).forEach(function (file) {
var moduleName = path.parse(file).name.replace(/\-/g, "");
var source = (0, path_1.normalizeSeparators)("./" + path.relative(dir, file));
if (exports[moduleName]) {
exports[moduleName].source = source;
}
});
}
components = new Map();
parser = new ComponentParser_1.default();
exportEntries = Object.entries(exports);
_i = 0, exportEntries_1 = exportEntries;
_c.label = 1;
case 1:
if (!(_i < exportEntries_1.length)) return [3 /*break*/, 5];
_a = exportEntries_1[_i], exportName = _a[0], entry_1 = _a[1];
filePath = entry_1.source;
_b = path.parse(filePath), ext = _b.ext, name_1 = _b.name;
moduleName = exportName;
if (exportEntries.length === 1 && exportName === "default") {
moduleName = name_1;
}
if (!(ext === ".svelte")) return [3 /*break*/, 4];
return [4 /*yield*/, fsp.readFile(path.resolve(dir, filePath), "utf-8")];
case 2:
source = _c.sent();
return [4 /*yield*/, (0, compiler_1.preprocess)(source, [(0, svelte_preprocess_1.typescript)(), (0, svelte_preprocess_1.replace)([[/<style.+<\/style>/gims, ""]])], {
filename: path.basename(filePath),
})];
case 3:
processed = (_c.sent()).code;
components.set(moduleName, __assign({ moduleName: moduleName, filePath: filePath }, parser.parseSvelteComponent(processed, {
moduleName: moduleName,
filePath: filePath,
})));
_c.label = 4;
case 4:
_i++;
return [3 /*break*/, 1];
case 5: return [2 /*return*/, {
exports: exports,
components: components,
}];
}
});
}
const components = new Map();
const parser = new ComponentParser_1.default();
const exportEntries = Object.entries(exports);
for (const [exportName, entry] of exportEntries) {
const filePath = entry.source;
const { ext, name } = path.parse(filePath);
let moduleName = exportName;
if (exportEntries.length === 1 && exportName === "default") {
moduleName = name;
}
if (ext === ".svelte") {
const source = await fsp.readFile(path.resolve(dir, filePath), "utf-8");
const { code: processed } = await (0, compiler_1.preprocess)(source, [(0, svelte_preprocess_1.typescript)(), (0, svelte_preprocess_1.replace)([[/<style.+<\/style>/gims, ""]])], {
filename: path.basename(filePath),
});
components.set(moduleName, {
moduleName,
filePath,
...parser.parseSvelteComponent(processed, {
moduleName,
filePath,
}),
});
}
}
return {
exports,
components,
};
});
}
exports.generateBundle = generateBundle;
function writeOutput(result, opts, input) {
const inputDir = path.dirname(input);
if (opts?.types !== false) {
(0, writer_ts_definitions_1.default)(result.components, {
outDir: "types",
preamble: "",
...opts?.typesOptions,
exports: result.exports,
inputDir,
});
var inputDir = path.dirname(input);
if ((opts === null || opts === void 0 ? void 0 : opts.types) !== false) {
(0, writer_ts_definitions_1.default)(result.components, __assign(__assign({ outDir: "types", preamble: "" }, opts === null || opts === void 0 ? void 0 : opts.typesOptions), { exports: result.exports, inputDir: inputDir }));
}
if (opts?.json) {
(0, writer_json_1.default)(result.components, {
outFile: "COMPONENT_API.json",
...opts?.jsonOptions,
input,
inputDir,
});
if (opts === null || opts === void 0 ? void 0 : opts.json) {
(0, writer_json_1.default)(result.components, __assign(__assign({ outFile: "COMPONENT_API.json" }, opts === null || opts === void 0 ? void 0 : opts.jsonOptions), { input: input, inputDir: inputDir }));
}
if (opts?.markdown) {
(0, writer_markdown_1.default)(result.components, {
outFile: "COMPONENT_INDEX.md",
...opts?.markdownOptions,
});
if (opts === null || opts === void 0 ? void 0 : opts.markdown) {
(0, writer_markdown_1.default)(result.components, __assign({ outFile: "COMPONENT_INDEX.md" }, opts === null || opts === void 0 ? void 0 : opts.markdownOptions));
}
}
exports.writeOutput = writeOutput;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sveld = void 0;
const get_svelte_entry_1 = require("./get-svelte-entry");
const rollup_plugin_1 = require("./rollup-plugin");
async function sveld(opts) {
const input = (0, get_svelte_entry_1.getSvelteEntry)(opts?.input);
if (input === null)
return;
const result = await (0, rollup_plugin_1.generateBundle)(input, opts?.glob === true);
(0, rollup_plugin_1.writeOutput)(result, opts || {}, input);
var get_svelte_entry_1 = require("./get-svelte-entry");
var rollup_plugin_1 = require("./rollup-plugin");
function sveld(opts) {
return __awaiter(this, void 0, void 0, function () {
var input, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
input = (0, get_svelte_entry_1.getSvelteEntry)(opts === null || opts === void 0 ? void 0 : opts.input);
if (input === null)
return [2 /*return*/];
return [4 /*yield*/, (0, rollup_plugin_1.generateBundle)(input, (opts === null || opts === void 0 ? void 0 : opts.glob) === true)];
case 1:
result = _a.sent();
(0, rollup_plugin_1.writeOutput)(result, opts || {}, input);
return [2 /*return*/];
}
});
});
}
exports.sveld = sveld;
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -6,50 +53,78 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const path_2 = require("../path");
const Writer_1 = __importDefault(require("./Writer"));
async function writeJsonComponents(components, options) {
const output = Array.from(components, ([moduleName, component]) => ({
...component,
filePath: (0, path_2.normalizeSeparators)(path_1.default.join(options.inputDir, path_1.default.normalize(component.filePath))),
})).sort((a, b) => {
if (a.moduleName < b.moduleName)
return -1;
if (a.moduleName > b.moduleName)
return 1;
return 0;
var path_1 = __importDefault(require("path"));
var path_2 = require("../path");
var Writer_1 = __importDefault(require("./Writer"));
function writeJsonComponents(components, options) {
return __awaiter(this, void 0, void 0, function () {
var output;
return __generator(this, function (_a) {
output = Array.from(components, function (_a) {
var moduleName = _a[0], component = _a[1];
return (__assign(__assign({}, component), { filePath: (0, path_2.normalizeSeparators)(path_1.default.join(options.inputDir, path_1.default.normalize(component.filePath))) }));
}).sort(function (a, b) {
if (a.moduleName < b.moduleName)
return -1;
if (a.moduleName > b.moduleName)
return 1;
return 0;
});
output.map(function (c) {
var outFile = path_1.default.resolve(path_1.default.join(options.outDir || "", "".concat(c.moduleName, ".api.json")));
var writer = new Writer_1.default({ parser: "json", printWidth: 80 });
console.log("created ".concat(outFile, "\"\n"));
return writer.write(outFile, JSON.stringify(c));
});
return [2 /*return*/];
});
});
output.map((c) => {
const outFile = path_1.default.resolve(path_1.default.join(options.outDir || "", `${c.moduleName}.api.json`));
const writer = new Writer_1.default({ parser: "json", printWidth: 80 });
console.log(`created ${outFile}"\n`);
return writer.write(outFile, JSON.stringify(c));
}
function writeJsonLocal(components, options) {
return __awaiter(this, void 0, void 0, function () {
var output, output_path, writer;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
output = {
total: components.size,
components: Array.from(components, function (_a) {
var moduleName = _a[0], component = _a[1];
return (__assign(__assign({}, component), { filePath: (0, path_2.normalizeSeparators)(path_1.default.join(options.inputDir, path_1.default.normalize(component.filePath))) }));
}).sort(function (a, b) {
if (a.moduleName < b.moduleName)
return -1;
if (a.moduleName > b.moduleName)
return 1;
return 0;
}),
};
output_path = path_1.default.join(process.cwd(), options.outFile);
writer = new Writer_1.default({ parser: "json", printWidth: 80 });
return [4 /*yield*/, writer.write(output_path, JSON.stringify(output))];
case 1:
_a.sent();
console.log("created \"".concat(options.outFile, "\".\n"));
return [2 /*return*/];
}
});
});
}
async function writeJsonLocal(components, options) {
const output = {
total: components.size,
components: Array.from(components, ([moduleName, component]) => ({
...component,
filePath: (0, path_2.normalizeSeparators)(path_1.default.join(options.inputDir, path_1.default.normalize(component.filePath))),
})).sort((a, b) => {
if (a.moduleName < b.moduleName)
return -1;
if (a.moduleName > b.moduleName)
return 1;
return 0;
}),
};
const output_path = path_1.default.join(process.cwd(), options.outFile);
const writer = new Writer_1.default({ parser: "json", printWidth: 80 });
await writer.write(output_path, JSON.stringify(output));
console.log(`created "${options.outFile}".\n`);
function writeJson(components, options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!options.outDir) return [3 /*break*/, 2];
return [4 /*yield*/, writeJsonComponents(components, options)];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, writeJsonLocal(components, options)];
case 3:
_a.sent();
_a.label = 4;
case 4: return [2 /*return*/];
}
});
});
}
async function writeJson(components, options) {
if (options.outDir) {
await writeJsonComponents(components, options);
}
else {
await writeJsonLocal(components, options);
}
}
exports.default = writeJson;

@@ -25,2 +25,47 @@ "use strict";

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -30,13 +75,13 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const WriterMarkdown_1 = __importDefault(require("./WriterMarkdown"));
const writer_ts_definitions_1 = require("./writer-ts-definitions");
const PROP_TABLE_HEADER = `| Prop name | Required | Kind | Reactive | Type | Default value | Description |\n| :- | :- | :- | :- |\n`;
const SLOT_TABLE_HEADER = `| Slot name | Default | Props | Fallback |\n| :- | :- | :- | :- |\n`;
const EVENT_TABLE_HEADER = `| Event name | Type | Detail |\n| :- | :- | :- |\n`;
const MD_TYPE_UNDEFINED = "--";
var path = __importStar(require("path"));
var WriterMarkdown_1 = __importDefault(require("./WriterMarkdown"));
var writer_ts_definitions_1 = require("./writer-ts-definitions");
var PROP_TABLE_HEADER = "| Prop name | Required | Kind | Reactive | Type | Default value | Description |\n| :- | :- | :- | :- |\n";
var SLOT_TABLE_HEADER = "| Slot name | Default | Props | Fallback |\n| :- | :- | :- | :- |\n";
var EVENT_TABLE_HEADER = "| Event name | Type | Detail |\n| :- | :- | :- |\n";
var MD_TYPE_UNDEFINED = "--";
function formatPropType(type) {
if (type === undefined)
return MD_TYPE_UNDEFINED;
return `<code>${type.replace(/\|/g, "&#124;")}</code>`;
return "<code>".concat(type.replace(/\|/g, "&#124;"), "</code>");
}

@@ -48,4 +93,4 @@ function escapeHtml(text) {

if (value === undefined)
return `<code>${value}</code>`;
return `<code>${value.replace(/`/g, "\\`").replace(/\|/g, "&#124;")}</code>`;
return "<code>".concat(value, "</code>");
return "<code>".concat(value.replace(/`/g, "\\`").replace(/\|/g, "&#124;"), "</code>");
}

@@ -72,67 +117,77 @@ function formatPropDescription(description) {

}
async function writeMarkdown(components, options) {
const write = options?.write !== false;
const document = new WriterMarkdown_1.default({
onAppend: (type, document) => {
options.onAppend?.call(null, type, document, components);
},
function writeMarkdown(components, options) {
return __awaiter(this, void 0, void 0, function () {
var write, document, keys, outFile;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
write = (options === null || options === void 0 ? void 0 : options.write) !== false;
document = new WriterMarkdown_1.default({
onAppend: function (type, document) {
var _a;
(_a = options.onAppend) === null || _a === void 0 ? void 0 : _a.call(null, type, document, components);
},
});
document.append("h1", "Component Index");
document.append("h2", "Components").tableOfContents();
document.append("divider");
keys = Array.from(components.keys()).sort();
keys.forEach(function (key) {
var component = components.get(key);
document.append("h2", "`".concat(component.moduleName, "`"));
if (component.typedefs.length > 0) {
document.append("h3", "Types").append("raw", "```ts\n".concat((0, writer_ts_definitions_1.getTypeDefs)({
typedefs: component.typedefs,
}), "\n```\n\n"));
}
document.append("h3", "Props");
if (component.props.length > 0) {
document.append("raw", PROP_TABLE_HEADER);
__spreadArray([], component.props, true).sort(function (a) {
if (a.reactive)
return -1;
if (a.constant)
return 1;
return 0;
})
.forEach(function (prop) {
document.append("raw", "| ".concat(prop.name, " | ").concat(prop.isRequired ? "Yes" : "No", " | ").concat("<code>".concat(prop.kind, "</code>"), " | ").concat(prop.reactive ? "Yes" : "No", " | ").concat(formatPropType(prop.type), " | ").concat(formatPropValue(prop.value), " | ").concat(formatPropDescription(prop.description), " |\n"));
});
}
else {
document.append("p", "None.");
}
document.append("h3", "Slots");
if (component.slots.length > 0) {
document.append("raw", SLOT_TABLE_HEADER);
component.slots.forEach(function (slot) {
document.append("raw", "| ".concat(slot.default ? MD_TYPE_UNDEFINED : slot.name, " | ").concat(slot.default ? "Yes" : "No", " | ").concat(formatSlotProps(slot.slot_props), " | ").concat(formatSlotFallback(slot.fallback), " |\n"));
});
}
else {
document.append("p", "None.");
}
document.append("h3", "Events");
if (component.events.length > 0) {
document.append("raw", EVENT_TABLE_HEADER);
component.events.forEach(function (event) {
document.append("raw", "| ".concat(event.name, " | ").concat(event.type, " | ").concat(event.type === "dispatched" ? formatEventDetail(event.detail) : MD_TYPE_UNDEFINED, " |\n"));
});
}
else {
document.append("p", "None.");
}
});
if (!write) return [3 /*break*/, 2];
outFile = path.join(process.cwd(), options.outFile);
return [4 /*yield*/, document.write(outFile, document.end())];
case 1:
_a.sent();
console.log("created \"".concat(options.outFile, "\"."));
_a.label = 2;
case 2: return [2 /*return*/, document.end()];
}
});
});
document.append("h1", "Component Index");
document.append("h2", "Components").tableOfContents();
document.append("divider");
const keys = Array.from(components.keys()).sort();
keys.forEach((key) => {
const component = components.get(key);
document.append("h2", `\`${component.moduleName}\``);
if (component.typedefs.length > 0) {
document.append("h3", "Types").append("raw", `\`\`\`ts\n${(0, writer_ts_definitions_1.getTypeDefs)({
typedefs: component.typedefs,
})}\n\`\`\`\n\n`);
}
document.append("h3", "Props");
if (component.props.length > 0) {
document.append("raw", PROP_TABLE_HEADER);
[...component.props]
.sort((a) => {
if (a.reactive)
return -1;
if (a.constant)
return 1;
return 0;
})
.forEach((prop) => {
document.append("raw", `| ${prop.name} | ${prop.isRequired ? "Yes" : "No"} | ${`<code>${prop.kind}</code>`} | ${prop.reactive ? "Yes" : "No"} | ${formatPropType(prop.type)} | ${formatPropValue(prop.value)} | ${formatPropDescription(prop.description)} |\n`);
});
}
else {
document.append("p", "None.");
}
document.append("h3", "Slots");
if (component.slots.length > 0) {
document.append("raw", SLOT_TABLE_HEADER);
component.slots.forEach((slot) => {
document.append("raw", `| ${slot.default ? MD_TYPE_UNDEFINED : slot.name} | ${slot.default ? "Yes" : "No"} | ${formatSlotProps(slot.slot_props)} | ${formatSlotFallback(slot.fallback)} |\n`);
});
}
else {
document.append("p", "None.");
}
document.append("h3", "Events");
if (component.events.length > 0) {
document.append("raw", EVENT_TABLE_HEADER);
component.events.forEach((event) => {
document.append("raw", `| ${event.name} | ${event.type} | ${event.type === "dispatched" ? formatEventDetail(event.detail) : MD_TYPE_UNDEFINED} |\n`);
});
}
else {
document.append("p", "None.");
}
});
if (write) {
const outFile = path.join(process.cwd(), options.outFile);
await document.write(outFile, document.end());
console.log(`created "${options.outFile}".`);
}
return document.end();
}
exports.default = writeMarkdown;

@@ -25,2 +25,56 @@ "use strict";

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -31,9 +85,9 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.writeTsDefinition = exports.getTypeDefs = exports.formatTsProps = void 0;
const path = __importStar(require("path"));
const create_exports_1 = require("../create-exports");
const Writer_1 = __importDefault(require("./Writer"));
const ANY_TYPE = "any";
const EMPTY_STR = "";
var path = __importStar(require("path"));
var create_exports_1 = require("../create-exports");
var Writer_1 = __importDefault(require("./Writer"));
var ANY_TYPE = "any";
var EMPTY_STR = "";
// Svelte 4 is not compatible with `{}`
const EMPTY_EVENTS = "Record<string, any>";
var EMPTY_EVENTS = "Record<string, any>";
function formatTsProps(props) {

@@ -48,3 +102,3 @@ if (props === undefined)

return EMPTY_STR;
return def.typedefs.map((typedef) => `export ${typedef.ts}`).join("\n\n");
return def.typedefs.map(function (typedef) { return "export ".concat(typedef.ts); }).join("\n\n");
}

@@ -54,3 +108,3 @@ exports.getTypeDefs = getTypeDefs;

if (/(\-|\s+|\:)/.test(key)) {
return /(\"|\')/.test(key) ? key : `["${key}"]`;
return /(\"|\')/.test(key) ? key : "[\"".concat(key, "\"]");
}

@@ -62,9 +116,11 @@ return key;

return undefined;
return `* ${returnValue || value}\n`;
return "* ".concat(returnValue || value, "\n");
}
function genPropDef(def) {
const initial_props = def.props
.filter((prop) => !prop.isFunctionDeclaration && prop.kind !== "const")
.map((prop) => {
let defaultValue = prop.value;
var _a;
var initial_props = def.props
.filter(function (prop) { return !prop.isFunctionDeclaration && prop.kind !== "const"; })
.map(function (prop) {
var _a;
var defaultValue = prop.value;
if (typeof prop.value === "string") {

@@ -76,23 +132,22 @@ defaultValue = prop.value.replace(/\s+/g, " ");

}
const prop_comments = [
addCommentLine(prop.description?.replace(/\n/g, "\n* ")),
var prop_comments = [
addCommentLine((_a = prop.description) === null || _a === void 0 ? void 0 : _a.replace(/\n/g, "\n* ")),
addCommentLine(prop.constant, "@constant"),
`* @default ${defaultValue}\n`,
"* @default ".concat(defaultValue, "\n"),
]
.filter(Boolean)
.join("");
let prop_value = prop.constant && !prop.isFunction ? prop.value : prop.type;
return `
${prop_comments.length > 0 ? `/**\n${prop_comments}*/` : EMPTY_STR}
${prop.name}${prop.isRequired ? "" : "?"}: ${prop_value};`;
var prop_value = prop.constant && !prop.isFunction ? prop.value : prop.type;
return "\n ".concat(prop_comments.length > 0 ? "/**\n".concat(prop_comments, "*/") : EMPTY_STR, "\n ").concat(prop.name).concat(prop.isRequired ? "" : "?", ": ").concat(prop_value, ";");
});
const props = initial_props.join("\n");
const props_name = `${def.moduleName}Props`;
let prop_def = EMPTY_STR;
if (def.rest_props?.type === "Element") {
const extend_tag_map = def.rest_props.name
var props = initial_props.join("\n");
var props_name = "".concat(def.moduleName, "Props");
var prop_def = EMPTY_STR;
var genericsName = def.generics ? "<".concat(def.generics[0], ">") : "";
if (((_a = def.rest_props) === null || _a === void 0 ? void 0 : _a.type) === "Element") {
var extend_tag_map = def.rest_props.name
.split("|")
.map((name) => {
const element = name.trim();
return `SvelteHTMLElements["${element}"]`;
.map(function (name) {
var element = name.trim();
return "SvelteHTMLElements[\"".concat(element, "\"]");
})

@@ -106,22 +161,11 @@ .join("&");

*/
const dataAttributes = "[key: `data-${string}`]: any;";
prop_def = `
${extend_tag_map ? `type RestProps = ${extend_tag_map};\n` : ""}
export interface ${props_name} extends ${def.extends !== undefined ? `${def.extends.interface}, ` : ""}RestProps {
${props}
${dataAttributes}
var dataAttributes = "[key: `data-${string}`]: any;";
prop_def = "\n ".concat(extend_tag_map ? "type RestProps = ".concat(extend_tag_map, ";\n") : "", "\n export interface ").concat(props_name).concat(genericsName, " extends ").concat(def.extends !== undefined ? "".concat(def.extends.interface, ", ") : "", "RestProps {\n ").concat(props, "\n \n ").concat(dataAttributes, "\n }\n ");
}
`;
}
else {
prop_def = `
export interface ${props_name} ${def.extends !== undefined ? `extends ${def.extends.interface}` : ""} {
${props}
prop_def = "\n export interface ".concat(props_name).concat(genericsName, " ").concat(def.extends !== undefined ? "extends ".concat(def.extends.interface) : "", " {\n ").concat(props, "\n }\n ");
}
`;
}
return {
props_name,
prop_def,
props_name: props_name,
prop_def: prop_def,
};

@@ -131,10 +175,11 @@ }

return def.slots
.map(({ name, slot_props, ...rest }) => {
const key = rest.default ? "default" : clampKey(name);
const description = rest.description ? "/** " + rest.description + " */\n" : "";
return `${description}${clampKey(key)}: ${formatTsProps(slot_props)};`;
.map(function (_a) {
var name = _a.name, slot_props = _a.slot_props, rest = __rest(_a, ["name", "slot_props"]);
var key = rest.default ? "default" : clampKey(name);
var description = rest.description ? "/** " + rest.description + " */\n" : "";
return "".concat(description).concat(clampKey(key), ": ").concat(formatTsProps(slot_props), ";");
})
.join("\n");
}
const mapEvent = (name) => {
var mapEvent = function (name) {
if (["cut", "copy", "paste"].includes(name)) {

@@ -146,28 +191,28 @@ return "DocumentAndElementEventHandlersEventMap";

function genEventDef(def) {
const createDispatchedEvent = (detail = ANY_TYPE) => {
var createDispatchedEvent = function (detail) {
if (detail === void 0) { detail = ANY_TYPE; }
if (/CustomEvent/.test(detail))
return detail;
return `CustomEvent<${detail}>`;
return "CustomEvent<".concat(detail, ">");
};
if (def.events.length === 0)
return EMPTY_EVENTS;
const events_map = def.events
.map((event) => {
let description = "";
var events_map = def.events
.map(function (event) {
var description = "";
if (event.type === "dispatched" && event.description) {
description = "/** " + event.description + " */\n";
}
return `${description}${clampKey(event.name)}: ${event.type === "dispatched" ? createDispatchedEvent(event.detail) : `${mapEvent(event.name)}["${event.name}"]`};\n`;
return "".concat(description).concat(clampKey(event.name), ": ").concat(event.type === "dispatched" ? createDispatchedEvent(event.detail) : "".concat(mapEvent(event.name), "[\"").concat(event.name, "\"]"), ";\n");
})
.join("");
return `{${events_map}}`;
return "{".concat(events_map, "}");
}
function genAccessors(def) {
return def.props
.filter((prop) => prop.isFunctionDeclaration || prop.kind === "const")
.map((prop) => {
const prop_comments = [addCommentLine(prop.description?.replace(/\n/g, "\n* "))].filter(Boolean).join("");
return `
${prop_comments.length > 0 ? `/**\n${prop_comments}*/` : EMPTY_STR}
${prop.name}: ${prop.type};`;
.filter(function (prop) { return prop.isFunctionDeclaration || prop.kind === "const"; })
.map(function (prop) {
var _a;
var prop_comments = [addCommentLine((_a = prop.description) === null || _a === void 0 ? void 0 : _a.replace(/\n/g, "\n* "))].filter(Boolean).join("");
return "\n ".concat(prop_comments.length > 0 ? "/**\n".concat(prop_comments, "*/") : EMPTY_STR, "\n ").concat(prop.name, ": ").concat(prop.type, ";");
})

@@ -179,3 +224,3 @@ .join("\n");

return "";
return `import type { ${def.extends.interface} } from ${def.extends.import};`;
return "import type { ".concat(def.extends.interface, " } from ").concat(def.extends.import, ";");
}

@@ -186,22 +231,21 @@ function genComponentComment(def) {

if (!/\n/.test(def.componentComment))
return `/** ${def.componentComment.trim()} */`;
return `/*${def.componentComment
return "/** ".concat(def.componentComment.trim(), " */");
return "/*".concat(def.componentComment
.split("\n")
.map((line) => `* ${line}`)
.join("\n")}\n*/`;
.map(function (line) { return "* ".concat(line); })
.join("\n"), "\n*/");
}
function genModuleExports(def) {
return def.moduleExports
.map((prop) => {
const prop_comments = [addCommentLine(prop.description?.replace(/\n/g, "\n* "))].filter(Boolean).join("");
let type_def = `export type ${prop.name} = ${prop.type || ANY_TYPE};`;
const is_function = prop.type && /=>/.test(prop.type);
.map(function (prop) {
var _a;
var prop_comments = [addCommentLine((_a = prop.description) === null || _a === void 0 ? void 0 : _a.replace(/\n/g, "\n* "))].filter(Boolean).join("");
var type_def = "export type ".concat(prop.name, " = ").concat(prop.type || ANY_TYPE, ";");
var is_function = prop.type && /=>/.test(prop.type);
if (is_function) {
const [first, second, ...rest] = prop.type.split("=>");
const rest_type = rest.map((item) => "=>" + item).join("");
type_def = `export declare function ${prop.name}${first}:${second}${rest_type};`;
var _b = prop.type.split("=>"), first = _b[0], second = _b[1], rest = _b.slice(2);
var rest_type = rest.map(function (item) { return "=>" + item; }).join("");
type_def = "export declare function ".concat(prop.name).concat(first, ":").concat(second).concat(rest_type, ";");
}
return `
${prop_comments.length > 0 ? `/**\n${prop_comments}*/` : EMPTY_STR}
${type_def}`;
return "\n ".concat(prop_comments.length > 0 ? "/**\n".concat(prop_comments, "*/") : EMPTY_STR, "\n ").concat(type_def);
})

@@ -211,36 +255,71 @@ .join("\n");

function writeTsDefinition(component) {
const { moduleName, typedefs, props, moduleExports, slots, events, rest_props, extends: _extends, componentComment, } = component;
const { props_name, prop_def } = genPropDef({
moduleName,
props,
rest_props,
var moduleName = component.moduleName, typedefs = component.typedefs, generics = component.generics, props = component.props, moduleExports = component.moduleExports, slots = component.slots, events = component.events, rest_props = component.rest_props, _extends = component.extends, componentComment = component.componentComment;
var _a = genPropDef({
moduleName: moduleName,
props: props,
rest_props: rest_props,
extends: _extends,
});
return `
import type { SvelteComponentTyped } from "svelte";${rest_props?.type === "Element" ? `import type { SvelteHTMLElements } from "svelte/elements";\n` : ""}
${genImports({ extends: _extends })}
${genModuleExports({ moduleExports })}
${getTypeDefs({ typedefs })}
${prop_def}
${genComponentComment({ componentComment })}
export default class ${moduleName === "default" ? "" : moduleName} extends SvelteComponentTyped<
${props_name},
${genEventDef({ events })},
{${genSlotDef({ slots })}}
> {
${genAccessors({ props })}
}`;
generics: generics,
}), props_name = _a.props_name, prop_def = _a.prop_def;
var generic = generics ? "<".concat(generics[1], ">") : "";
var genericProps = generics ? "".concat(props_name, "<").concat(generics[0], ">") : props_name;
return "\n import type { SvelteComponentTyped } from \"svelte\";".concat((rest_props === null || rest_props === void 0 ? void 0 : rest_props.type) === "Element" ? "import type { SvelteHTMLElements } from \"svelte/elements\";\n" : "", "\n ").concat(genImports({ extends: _extends }), "\n ").concat(genModuleExports({ moduleExports: moduleExports }), "\n ").concat(getTypeDefs({ typedefs: typedefs }), "\n ").concat(prop_def, "\n ").concat(genComponentComment({ componentComment: componentComment }), "\n export default class ").concat(moduleName === "default" ? "" : moduleName).concat(generic, " extends SvelteComponentTyped<\n ").concat(genericProps, ",\n ").concat(genEventDef({ events: events }), ",\n {").concat(genSlotDef({ slots: slots }), "}\n > {\n ").concat(genAccessors({ props: props }), "\n }");
}
exports.writeTsDefinition = writeTsDefinition;
async function writeTsDefinitions(components, options) {
const ts_base_path = path.join(process.cwd(), options.outDir, "index.d.ts");
const writer = new Writer_1.default({ parser: "typescript", printWidth: 80 });
const indexDTs = options.preamble + (0, create_exports_1.createExports)(options.exports, components);
for await (const [moduleName, component] of components) {
const ts_filepath = (0, create_exports_1.convertSvelteExt)(path.join(options.outDir, component.filePath));
await writer.write(ts_filepath, writeTsDefinition(component));
}
await writer.write(ts_base_path, indexDTs);
console.log(`created TypeScript definitions.`);
function writeTsDefinitions(components, options) {
return __awaiter(this, void 0, void 0, function () {
var ts_base_path, writer, indexDTs, moduleName, component, ts_filepath, e_1_1;
var _a, components_1, components_1_1;
var _b, e_1, _c, _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
ts_base_path = path.join(process.cwd(), options.outDir, "index.d.ts");
writer = new Writer_1.default({ parser: "typescript", printWidth: 80 });
indexDTs = options.preamble + (0, create_exports_1.createExports)(options.exports, components);
_e.label = 1;
case 1:
_e.trys.push([1, 7, 8, 13]);
_a = true, components_1 = __asyncValues(components);
_e.label = 2;
case 2: return [4 /*yield*/, components_1.next()];
case 3:
if (!(components_1_1 = _e.sent(), _b = components_1_1.done, !_b)) return [3 /*break*/, 6];
_d = components_1_1.value;
_a = false;
moduleName = _d[0], component = _d[1];
ts_filepath = (0, create_exports_1.convertSvelteExt)(path.join(options.outDir, component.filePath));
return [4 /*yield*/, writer.write(ts_filepath, writeTsDefinition(component))];
case 4:
_e.sent();
_e.label = 5;
case 5:
_a = true;
return [3 /*break*/, 2];
case 6: return [3 /*break*/, 13];
case 7:
e_1_1 = _e.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 13];
case 8:
_e.trys.push([8, , 11, 12]);
if (!(!_a && !_b && (_c = components_1.return))) return [3 /*break*/, 10];
return [4 /*yield*/, _c.call(components_1)];
case 9:
_e.sent();
_e.label = 10;
case 10: return [3 /*break*/, 12];
case 11:
if (e_1) throw e_1.error;
return [7 /*endfinally*/];
case 12: return [7 /*endfinally*/];
case 13: return [4 /*yield*/, writer.write(ts_base_path, indexDTs)];
case 14:
_e.sent();
console.log("created TypeScript definitions.");
return [2 /*return*/];
}
});
});
}
exports.default = writeTsDefinitions;

@@ -25,12 +25,47 @@ "use strict";

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
const path = __importStar(require("path"));
const fsp = __importStar(require("fs/promises"));
const prettier = __importStar(require("prettier"));
class Writer {
options;
constructor(options) {
var path = __importStar(require("path"));
var fsp = __importStar(require("fs/promises"));
var prettier = __importStar(require("prettier"));
var Writer = /** @class */ (function () {
function Writer(options) {
this.options = options;
}
format(raw) {
Writer.prototype.format = function (raw) {
try {

@@ -43,8 +78,20 @@ return prettier.format(raw, this.options);

}
}
async write(filePath, raw) {
await fsp.mkdir(path.parse(filePath).dir, { recursive: true });
await fsp.writeFile(filePath, this.format(raw));
}
}
};
Writer.prototype.write = function (filePath, raw) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fsp.mkdir(path.parse(filePath).dir, { recursive: true })];
case 1:
_a.sent();
return [4 /*yield*/, fsp.writeFile(filePath, this.format(raw))];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
return Writer;
}());
exports.default = Writer;
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -6,17 +21,19 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
const Writer_1 = __importDefault(require("./Writer"));
class WriterMarkdown extends Writer_1.default {
onAppend;
source = "";
hasToC = false;
toc = [];
constructor(options) {
super({ parser: "markdown", printWidth: 80 });
this.onAppend = options.onAppend;
var Writer_1 = __importDefault(require("./Writer"));
var WriterMarkdown = /** @class */ (function (_super) {
__extends(WriterMarkdown, _super);
function WriterMarkdown(options) {
var _this = _super.call(this, { parser: "markdown", printWidth: 80 }) || this;
_this.source = "";
_this.hasToC = false;
_this.toc = [];
_this.onAppend = options.onAppend;
return _this;
}
appendLineBreaks() {
WriterMarkdown.prototype.appendLineBreaks = function () {
this.source += "\n\n";
return this;
}
append(type, raw) {
};
WriterMarkdown.prototype.append = function (type, raw) {
var _a;
switch (type) {

@@ -29,10 +46,10 @@ case "h1":

case "h6":
const length = Number(type.slice(-1));
this.source += `${Array.from({ length })
.map((_) => "#")
.join("")} ${raw}`;
var length_1 = Number(type.slice(-1));
this.source += "".concat(Array.from({ length: length_1 })
.map(function (_) { return "#"; })
.join(""), " ").concat(raw);
if (this.hasToC && type === "h2") {
this.toc.push({
array: Array.from({ length: (length - 1) * 2 }),
raw,
array: Array.from({ length: (length_1 - 1) * 2 }),
raw: raw,
});

@@ -42,3 +59,3 @@ }

case "quote":
this.source += `> ${raw}`;
this.source += "> ".concat(raw);
break;

@@ -57,6 +74,6 @@ case "p":

this.appendLineBreaks();
this.onAppend?.call(this, type, this);
(_a = this.onAppend) === null || _a === void 0 ? void 0 : _a.call(this, type, this);
return this;
}
tableOfContents() {
};
WriterMarkdown.prototype.tableOfContents = function () {
this.source += "<!-- __TOC__ -->";

@@ -66,12 +83,14 @@ this.hasToC = true;

return this;
}
end() {
};
WriterMarkdown.prototype.end = function () {
this.source = this.source.replace("<!-- __TOC__ -->", this.toc
.map(({ array, raw }) => {
return `${array.join(" ")} - [${raw}](#${raw.toLowerCase().replace(/\`/g, "").replace(/\s+/g, "-")})`;
.map(function (_a) {
var array = _a.array, raw = _a.raw;
return "".concat(array.join(" "), " - [").concat(raw, "](#").concat(raw.toLowerCase().replace(/\`/g, "").replace(/\s+/g, "-"), ")");
})
.join("\n"));
return this.source;
}
}
};
return WriterMarkdown;
}(Writer_1.default));
exports.default = WriterMarkdown;
{
"name": "sveld",
"version": "0.19.2",
"version": "0.20.0",
"license": "Apache-2.0",

@@ -9,6 +9,6 @@ "description": "Generate TypeScript definitions for your Svelte components.",

"scripts": {
"test": "vitest -r tests",
"test:integration": "node tests/test-integration",
"format": "prettier --write \"{src,tests,playground}/**/*.{js,ts,svelte,md}\" --ignore-path \".gitignore\"",
"build": "tsc -p tsconfig.build.json"
"test": "bun test",
"test:e2e": "bun tests/test-e2e.ts",
"format": "bun --bun prettier --write \".\"",
"build": "bun --bun tsc"
},

@@ -28,7 +28,7 @@ "dependencies": {

"devDependencies": {
"@types/bun": "^1.0.12",
"@types/jest": "^29.5.12",
"@types/node": "^20.4.9",
"@types/prettier": "^2.7.3",
"prettier-plugin-svelte": "^2.8.0",
"vite": "^5.2.8",
"vitest": "^1.4.0"
"prettier-plugin-svelte": "^2.8.0"
},

@@ -35,0 +35,0 @@ "bin": {

@@ -125,2 +125,3 @@ # sveld

- [@extends](#extends)
- [@generics](#generics)
- [@component comments](#component-comments)

@@ -151,7 +152,13 @@ - [Contributing](#contributing)

```sh
yarn add -D sveld
# OR
# npm
npm i -D sveld
# OR
# pnpm
pnpm i -D sveld
# Bun
bun i -D sveld
# Yarn
yarn add -D sveld
```

@@ -193,11 +200,11 @@

The [integration](integration) folder contains example set-ups:
The [tests/e2e](tests/e2e) folder contains example set-ups:
- [single-export](integration/single-export): library that exports one component
- [single-export-default-only](integration/single-export-default-only): library that exports one component using the concise `export { default } ...` syntax
- [multi-export](integration/multi-export): multi-component library without JSDoc annotations (types are inferred)
- [multi-export-typed](integration/multi-export-typed): multi-component library with JSDoc annotations
- [multi-export-typed-ts-only](integration/multi-export-typed-ts-only): multi-component library that only generates TS definitions
- [glob](integration/glob): library that uses the glob strategy to collect/analyze \*.svelte files
- [carbon](integration/carbon): full `carbon-components-svelte` example
- [single-export](tests/e2e/single-export): library that exports one component
- [single-export-default-only](tests/e2e/single-export-default-only): library that exports one component using the concise `export { default } ...` syntax
- [multi-export](tests/e2e/multi-export): multi-component library without JSDoc annotations (types are inferred)
- [multi-export-typed](tests/e2e/multi-export-typed): multi-component library with JSDoc annotations
- [multi-export-typed-ts-only](tests/e2e/multi-export-typed-ts-only): multi-component library that only generates TS definitions
- [glob](tests/e2e/glob): library that uses the glob strategy to collect/analyze \*.svelte files
- [carbon](tests/e2e/carbon): full `carbon-components-svelte` example

@@ -502,2 +509,41 @@ ### CLI

### `@generics`
Currently, to define generics for a Svelte component, you must use [`generics` attribute](https://github.com/dummdidumm/rfcs/blob/bfb14dc56a70ec6ddafebf2242b8e1500e06a032/text/ts-typing-props-slots-events.md#generics) on the script tag. Note that this feature is [experimental](https://svelte.dev/docs/typescript#experimental-advanced-typings) and may change in the future.
However, the `generics` attribute only works if using `lang="ts"`; the language server will produce an error if `generics` is used without specifying `lang="ts"`.
```svelte
<!-- This causes an error because `lang="ts"` must be used. -->
<script generics="Row extends DataTableRow = any"></script>
```
Because `sveld` is designed to support JavaScript-only usage as a baseline, the API design to specify generics uses a custom JSDoc tag `@generics`.
Signature:
```js
/**
* @generics {GenericParameter} GenericName
*/
```
Example
```js
/**
* @generics {Row extends DataTableRow = any} Row
*/
```
The generated TypeScript definition will resemble the following:
```ts
export default class Component<Row extends DataTableRow = any> extends SvelteComponentTyped<
ComponentProps<Row>,
Record<string, any>,
Record<string, any>
> {}
```
### `@component` comments

@@ -504,0 +550,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc