@mbler/mcx-core 0.0.2 → 0.0.3-alpha.r20260311

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var fs = require('node:fs/promises');
6
4
  var path = require('node:path');
7
5
  var rollup = require('rollup');
@@ -10,7 +8,9 @@ var json = require('@rollup/plugin-json');
10
8
  var module_resolve = require('@rollup/plugin-node-resolve');
11
9
  var t = require('@babel/types');
12
10
  var Parser = require('@babel/parser');
11
+ var ts = require('typescript');
13
12
  var generator = require('@babel/generator');
13
+ var MagicString = require('magic-string');
14
14
 
15
15
  function _interopNamespaceDefault(e) {
16
16
  var n = Object.create(null);
@@ -33,7 +33,6 @@ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
33
33
  var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
34
34
  var t__namespace = /*#__PURE__*/_interopNamespaceDefault(t);
35
35
  var Parser__namespace = /*#__PURE__*/_interopNamespaceDefault(Parser);
36
- var generator__namespace = /*#__PURE__*/_interopNamespaceDefault(generator);
37
36
 
38
37
  let Lexer$1 = class Lexer {
39
38
  text;
@@ -226,6 +225,7 @@ let Lexer$1 = class Lexer {
226
225
  // content 现在是一个数组,包含文本节点或子标签
227
226
  content: [],
228
227
  end: null,
228
+ type: 'TagNode',
229
229
  // loc: start/end positions will be set when available
230
230
  loc: {
231
231
  start: { line: token.startLine || 1, index: token.startIndex || 0 },
@@ -482,7 +482,7 @@ function PropParser(code) {
482
482
  return Array.from(lexer.tokenize());
483
483
  }
484
484
 
485
- var AST = {
485
+ var index$2 = {
486
486
  tag: McxAst,
487
487
  prop: PropParser
488
488
  };
@@ -712,12 +712,12 @@ class CompileError extends Error {
712
712
  constructor(message, loc) {
713
713
  super(message);
714
714
  this.name = "CompileError";
715
- this.loc = loc || { line: -1, pos: -1 };
715
+ this.loc = loc || { line: -1, column: -1 };
716
716
  }
717
717
  }
718
718
  function extractLoc(node) {
719
719
  if (!node)
720
- return { line: -1, pos: -1 };
720
+ return { line: -1, column: -1 };
721
721
  // Node with loc.start (Babel or MCX): prefer column, fallback to index
722
722
  if (node.loc && node.loc.start) {
723
723
  const line = typeof node.loc.start.line === "number" ? node.loc.start.line : -1;
@@ -726,16 +726,23 @@ function extractLoc(node) {
726
726
  : typeof node.loc.start.index === "number"
727
727
  ? node.loc.start.index
728
728
  : -1;
729
- return { line, pos };
729
+ return { line, column: pos };
730
+ }
731
+ else if (node.loc && node.loc.column) {
732
+ return {
733
+ line: node.loc.line,
734
+ column: node.loc.column
735
+ };
730
736
  }
731
737
  // Our token shape from Lexer: startLine / startIndex
732
- if (typeof node.startLine === "number" || typeof node.startIndex === "number") {
738
+ if (typeof node.startLine === "number" ||
739
+ typeof node.startIndex === "number") {
733
740
  const line = typeof node.startLine === "number" ? node.startLine : -1;
734
741
  const pos = typeof node.startIndex === "number" ? node.startIndex : -1;
735
- return { line, pos };
742
+ return { line, column: pos };
736
743
  }
737
744
  // (handled above) MCX ParsedTagNode loc: { start: { line, index } }
738
- return { line: -1, pos: -1 };
745
+ return { line: -1, column: -1 };
739
746
  }
740
747
  function makeError(msg, node) {
741
748
  return new CompileError(msg, extractLoc(node));
@@ -1124,10 +1131,11 @@ class CompileMCX {
1124
1131
  Event: {
1125
1132
  on: "after",
1126
1133
  subscribe: {},
1127
- loc: { line: -1, pos: -1 },
1134
+ loc: { line: -1, column: -1 },
1128
1135
  isLoad: false,
1129
1136
  },
1130
1137
  Component: {},
1138
+ UI: null,
1131
1139
  };
1132
1140
  getCompileData() {
1133
1141
  return this.CompileData;
@@ -1165,15 +1173,25 @@ class CompileMCX {
1165
1173
  let component = null;
1166
1174
  const temp = {
1167
1175
  script: "",
1168
- Event: null};
1176
+ Event: null,
1177
+ ui: null};
1169
1178
  for (const node of this.mcxCode || []) {
1170
1179
  if (!MCXUtils.isTagNode(node))
1171
1180
  continue;
1172
1181
  if (node.name == "script") {
1173
1182
  if (temp.script)
1174
1183
  throw makeError("[compile error]: duplicate script node", node);
1175
- temp.script =
1176
- node.content.length == 0 ? "" : this.commonTagNodeContent(node);
1184
+ const scriptNode = node.content.length == 0 ? "" : this.commonTagNodeContent(node);
1185
+ let code = scriptNode;
1186
+ if (node.arr.lang == "ts") {
1187
+ code = ts.transpileModule(scriptNode, {
1188
+ compilerOptions: {
1189
+ target: ts.ScriptTarget.ES2024,
1190
+ module: ts.ModuleKind.ESNext,
1191
+ },
1192
+ }).outputText;
1193
+ }
1194
+ temp.script = code;
1177
1195
  }
1178
1196
  else if (node.name == "Event") {
1179
1197
  if (temp.Event)
@@ -1189,8 +1207,15 @@ class CompileMCX {
1189
1207
  // if Event already discovered, report error
1190
1208
  if (temp.Event)
1191
1209
  throw makeError("[compile error]: Component node cannot appear after Event", node);
1210
+ if (temp.ui)
1211
+ throw makeError("[compile error]: Component node can't use with UI node");
1192
1212
  component = node;
1193
1213
  }
1214
+ else if (node.name == "Ui") {
1215
+ if (component || temp.Event || temp.ui)
1216
+ throw makeError("[compile error]: UI node can't use with component or event or other ui node", node);
1217
+ temp.ui = node;
1218
+ }
1194
1219
  }
1195
1220
  if (!temp.script)
1196
1221
  throw makeError("[compile error]: mcx must has a script");
@@ -1222,6 +1247,9 @@ class CompileMCX {
1222
1247
  this.handlerChildComponent(subNode);
1223
1248
  }
1224
1249
  }
1250
+ if (temp.ui) {
1251
+ this.tempLoc.UI = temp.ui;
1252
+ }
1225
1253
  }
1226
1254
  // 传入组件的节点,处理子组件(如 items entities)
1227
1255
  handlerChildComponent(node) {
@@ -1251,7 +1279,7 @@ class CompileMCX {
1251
1279
  this.tempLoc.Component[`${name}/${id}`] = {
1252
1280
  type: subName,
1253
1281
  useExpore: useExpore,
1254
- loc: extractLoc(subNode)
1282
+ loc: extractLoc(subNode),
1255
1283
  };
1256
1284
  }
1257
1285
  }
@@ -1265,7 +1293,20 @@ class CompileMCX {
1265
1293
  }
1266
1294
  }
1267
1295
  function compileJSFn(code) {
1268
- const comiler = new CompileJS(Parser.parse(code, { sourceType: "module" }).program);
1296
+ let parsedCode;
1297
+ try {
1298
+ parsedCode = Parser.parse(code, { sourceType: "module", allowImportExportEverywhere: true });
1299
+ }
1300
+ catch (err) {
1301
+ if (err instanceof SyntaxError) {
1302
+ const babelErr = err;
1303
+ throw makeError(err.message, babelErr);
1304
+ }
1305
+ else {
1306
+ throw makeError(String(err));
1307
+ }
1308
+ }
1309
+ const comiler = new CompileJS(parsedCode.program);
1269
1310
  comiler.run();
1270
1311
  return comiler.getCompileData();
1271
1312
  }
@@ -1274,7 +1315,7 @@ function compileMCXFn(mcxCode) {
1274
1315
  return compiler.getCompileData();
1275
1316
  }
1276
1317
 
1277
- var Compiler = /*#__PURE__*/Object.freeze({
1318
+ var index$1 = /*#__PURE__*/Object.freeze({
1278
1319
  __proto__: null,
1279
1320
  CompileError: CompileError,
1280
1321
  CompileJS: CompileJS,
@@ -1285,1649 +1326,468 @@ var Compiler = /*#__PURE__*/Object.freeze({
1285
1326
  var config = {
1286
1327
  // script tag compile function name
1287
1328
  scriptCompileFn: "__main",
1288
- // use event tag , import event as
1289
- eventImported: "__mcx__event",
1290
- eventVarName: "__use_event"
1329
+ eventExtendsName: "McxExtendsBy",
1330
+ // paramName
1331
+ paramCtx: "__mcx__ctx"
1291
1332
  };
1292
1333
 
1293
- const allKeys = (() => {
1294
- // 闭包
1295
- const findkeyByVarId = (id, result) => {
1296
- if (id.type == "VoidPattern")
1297
- return;
1298
- if (id.type == "ArrayPattern") {
1299
- id.elements.forEach((node) => {
1300
- if (!node)
1301
- return;
1302
- findkeyByVarId(node, result);
1303
- });
1304
- }
1305
- else if (id.type == "Identifier") {
1306
- result.push(id.name);
1334
+ function extrectVarDefIdList(express) {
1335
+ const result = [];
1336
+ if (t__namespace.isIdentifier(express))
1337
+ result.push(express.name);
1338
+ if (t__namespace.isObjectPattern(express))
1339
+ express.properties.forEach((prop) => {
1340
+ // const {xxx:xxx,xxx=Litter} = xxx
1341
+ if (t__namespace.isObjectProperty(prop))
1342
+ return result.push(...extrectVarDefIdList(prop.value));
1343
+ // const {...restElement} = xx (restElement in this, ,must identifier)
1344
+ if (t__namespace.isRestElement(prop) && prop.argument.type == "Identifier")
1345
+ result.push(prop.argument.name);
1346
+ });
1347
+ if (t__namespace.isArrayPattern(express)) {
1348
+ for (const element of express.elements) {
1349
+ if (!element)
1350
+ continue;
1351
+ result.push(...extrectVarDefIdList(element));
1307
1352
  }
1308
- else if (id.type == "RestElement") {
1309
- id.argument;
1310
- findkeyByVarId(id, result);
1353
+ }
1354
+ if (t__namespace.isAssignmentPattern(express)) {
1355
+ result.push(...extrectVarDefIdList(express.left));
1356
+ }
1357
+ return result;
1358
+ }
1359
+ function extractIdList(expression) {
1360
+ if (t__namespace.isFunctionDeclaration(expression)) {
1361
+ return [expression.id?.name || ""];
1362
+ }
1363
+ if (t__namespace.isVariableDeclaration(expression)) {
1364
+ const result = [];
1365
+ for (const varDef of expression.declarations) {
1366
+ result.push(...extrectVarDefIdList(varDef.id));
1311
1367
  }
1312
- else if (id.type == "ObjectPattern") {
1313
- for (const property of id.properties) {
1314
- if (property.type == "ObjectProperty") {
1315
- const key = property.key;
1316
- if (property.value.type == "AssignmentPattern") {
1317
- const assigmentNode = property.value;
1318
- findkeyByVarId(assigmentNode.left, result);
1368
+ return result;
1369
+ }
1370
+ if (t__namespace.isClassDeclaration(expression)) {
1371
+ // 'export class {}'is not vaild(error: class name is required).
1372
+ return [expression.id?.name || ""];
1373
+ }
1374
+ return [];
1375
+ }
1376
+ function ToExpression(s) {
1377
+ if (t__namespace.isFunctionDeclaration(s))
1378
+ return t__namespace.functionExpression(s.id, s.params, s.body, s.generator, s.async);
1379
+ if (t__namespace.isClassDeclaration(s))
1380
+ return t__namespace.classExpression(s.id, s.superClass, s.body, s.decorators);
1381
+ if (t__namespace.isTSDeclareFunction(s))
1382
+ return t__namespace.objectExpression([]);
1383
+ return s;
1384
+ }
1385
+ function generateMain(code) {
1386
+ const expBody = [];
1387
+ const impBody = code.BuildCache.import.map((item) => {
1388
+ return Utils.CacheToImportNode(item);
1389
+ });
1390
+ const codeBody = code.node.body;
1391
+ for (const exp of code.BuildCache.export) {
1392
+ if (t__namespace.isExportNamedDeclaration(exp)) {
1393
+ // export {xxx} from "./xxx" or export xxx from "./xxx"
1394
+ if (exp.source &&
1395
+ exp.specifiers &&
1396
+ exp.specifiers.length >= 1 &&
1397
+ exp.source.value.length >= 1) {
1398
+ impBody.push(t__namespace.importDeclaration(exp.specifiers.map((item) => {
1399
+ if (t__namespace.isExportDefaultSpecifier(item)) {
1400
+ expBody.push(t__namespace.objectProperty(item.exported, item.exported));
1401
+ return t__namespace.importDefaultSpecifier(item.exported);
1319
1402
  }
1320
- else if (key.type == "Identifier") {
1321
- result.push(key.name);
1403
+ if (t__namespace.isExportSpecifier(item)) {
1404
+ expBody.push(t__namespace.objectProperty(item.exported, item.exported));
1405
+ return t__namespace.importSpecifier(item.local, item.exported);
1322
1406
  }
1407
+ if (t__namespace.isExportNamespaceSpecifier(item)) {
1408
+ expBody.push(t__namespace.spreadElement(item.exported));
1409
+ return t__namespace.importNamespaceSpecifier(item.exported);
1410
+ }
1411
+ // 不加的话,ts就报错
1412
+ throw new Error("[build import]: 这也不是那也不是, 你是个登啊(ts也是galgame)");
1413
+ }), exp.source));
1414
+ }
1415
+ if (exp.declaration) {
1416
+ const idList = extractIdList(exp.declaration);
1417
+ // be like: const {} = {}; (worthless)
1418
+ if (idList.length < 1)
1323
1419
  continue;
1324
- }
1325
- findkeyByVarId(property.argument, result);
1326
- }
1420
+ codeBody.push(exp.declaration);
1421
+ expBody.push(...idList.map((id) => {
1422
+ return t__namespace.objectProperty(t__namespace.identifier(id), t__namespace.identifier(id));
1423
+ }));
1424
+ }
1425
+ // export { xxx }
1426
+ if (exp.specifiers && !exp.source) {
1427
+ expBody.push(...exp.specifiers.map((item) => {
1428
+ if (!t__namespace.isExportSpecifier(item))
1429
+ throw new Error(`[build import]: invaild specifiers`);
1430
+ return t__namespace.objectProperty(item.exported, item.local);
1431
+ }));
1432
+ }
1433
+ // export * from "xxx"
1327
1434
  }
1328
- else if (id.type == "AssignmentPattern") {
1329
- findkeyByVarId(id.left, result);
1435
+ else if (t__namespace.isExportAllDeclaration(exp)) {
1436
+ // xxx.js => xxx_js(id)
1437
+ const id = exp.source.value.replace(/[!a-zA-Z0-9]+/g, "_");
1438
+ impBody.push(t__namespace.importDeclaration([t__namespace.importNamespaceSpecifier(t__namespace.identifier(id))], exp.source));
1439
+ expBody.push(t__namespace.objectProperty(t__namespace.identifier(id), t__namespace.identifier(id)));
1440
+ // export default {} or export default function a(){}
1330
1441
  }
1331
- };
1332
- return (node) => {
1333
- let result = [];
1334
- if (node.type == "VariableDeclaration") {
1335
- for (const declaration of node.declarations) {
1336
- findkeyByVarId(declaration.id, result);
1337
- }
1338
- }
1339
- return result;
1340
- };
1341
- })();
1342
- const generateTempId = (() => {
1343
- let num = 0;
1344
- return () => {
1345
- num++;
1346
- return `__mcx_${num}`;
1347
- };
1348
- })();
1349
- function generateMain(JSIR) {
1350
- const base = t__namespace.blockStatement(JSIR.node.body);
1351
- const exports$1 = [];
1352
- const importDeclarations = JSIR.BuildCache.import.map(Utils.CacheToImportNode);
1353
- if (JSIR.BuildCache.export.length >= 1)
1354
- for (let exportNode of JSIR.BuildCache.export) {
1355
- // namedExport
1356
- if (exportNode.type == "ExportNamedDeclaration") {
1357
- if (exportNode.declaration) {
1358
- // push declaration
1359
- base.body.push(exportNode.declaration);
1360
- // add export
1361
- const keys = allKeys(exportNode.declaration);
1362
- // ExportNamedDeclaration can export one and more items. So forEach it.
1363
- keys.forEach((item) => {
1364
- const milb = t__namespace.identifier(item);
1365
- exports$1.push(t__namespace.objectProperty(milb, milb));
1366
- });
1367
- continue;
1368
- }
1369
- else if (exportNode.specifiers.length >= 1 && exportNode.source) {
1370
- importDeclarations.push(t__namespace.importDeclaration(exportNode.specifiers.map((vaule) => {
1371
- if (vaule) {
1372
- if (vaule.type == "ExportSpecifier") {
1373
- return t__namespace.importSpecifier(vaule.local, vaule.exported);
1374
- }
1375
- else if (vaule.type == "ExportNamespaceSpecifier") {
1376
- return t__namespace.importNamespaceSpecifier(vaule.exported);
1377
- }
1378
- else {
1379
- return t__namespace.importDefaultSpecifier(vaule.exported);
1380
- }
1381
- }
1382
- throw new Error("[compile export]: can't handler specifier");
1383
- }), exportNode.source));
1384
- }
1385
- }
1386
- else if (exportNode.type == "ExportDefaultDeclaration") {
1387
- exports$1.push(t__namespace.objectProperty(t__namespace.identifier("default"), t__namespace.isExpression(exportNode.declaration)
1388
- ? exportNode.declaration
1389
- : DeclarationToExpression(exportNode.declaration)));
1390
- }
1391
- else {
1392
- const source = exportNode.source;
1393
- const id = generateTempId();
1394
- importDeclarations.push(t__namespace.importDeclaration([t__namespace.importNamespaceSpecifier(t__namespace.identifier(id))], source));
1395
- exports$1.push(t__namespace.spreadElement(t__namespace.identifier(id)));
1396
- }
1442
+ else if (t__namespace.isExportDefaultDeclaration(exp)) {
1443
+ // to expression
1444
+ expBody.push(t__namespace.objectProperty(t__namespace.identifier("default"), ToExpression(exp.declaration)));
1397
1445
  }
1398
- base.body.push(t__namespace.returnStatement(t__namespace.objectExpression(exports$1)));
1446
+ }
1399
1447
  return [
1400
- ...importDeclarations,
1401
- t__namespace.variableDeclaration("const", [
1402
- t__namespace.variableDeclarator(t__namespace.identifier(config.scriptCompileFn), t__namespace.callExpression(t__namespace.functionExpression(null, [], base, false, false), [])),
1403
- ]),
1448
+ [...codeBody, t__namespace.returnStatement(t__namespace.objectExpression(expBody))],
1449
+ impBody,
1404
1450
  ];
1405
1451
  }
1406
- function DeclarationToExpression(node) {
1407
- if (node.type == "ClassDeclaration")
1408
- return t__namespace.classExpression(node.id, node.superClass, node.body, node.decorators);
1409
- if (node.type == "FunctionDeclaration")
1410
- return t__namespace.functionExpression(node.id, node.params, node.body, node.generator, node.async);
1411
- throw new Error("[compile node]: can't to expression: " + node.type);
1412
- }
1413
-
1414
- function handlerPath(p, base) {
1415
- const dir = p.split("/");
1416
- if (dir[0] && dir[0] in _MCXstructureLocComponentTypes) {
1417
- return path.join(base, p);
1418
- }
1419
- throw new Error(`[component path]: path '${p}' is unreasonable. because root is not in '${Object.keys(_MCXstructureLocComponentTypes)}'`);
1420
- }
1421
- const cache$1 = new Map();
1422
- async function compileComponent(compileData, opt) {
1423
- const component = compileData.strLoc.Component;
1424
- if (cache$1.get(opt)) {
1425
- throw new CompileError("[compile comonent]: can't load two and more component mcx in same project", {
1426
- pos: 1,
1427
- line: 1
1428
- });
1429
- }
1430
- cache$1.set(opt, true);
1431
- const projectDir = path.dirname(opt.ProjectDir);
1432
- for (const jsonKey in component) {
1433
- handlerPath(jsonKey, projectDir);
1434
- component[jsonKey];
1452
+ async function generateEventConfig(eventTag, ctx, impBody) {
1453
+ const prop = ctx.compiledCode.strLoc.Event.subscribe;
1454
+ const argm = t__namespace.objectExpression([
1455
+ t__namespace.objectProperty(t__namespace.identifier("on"), t__namespace.stringLiteral(ctx.compiledCode.strLoc.Event.on))
1456
+ ]);
1457
+ if (eventTag.arr.tick) {
1458
+ const num = parseFloat(eventTag.arr.tick);
1459
+ if (!Number.isNaN(num))
1460
+ argm.properties.push(t__namespace.objectProperty(t__namespace.identifier("tick"), t__namespace.numericLiteral(num)));
1461
+ }
1462
+ // extract event and hanler
1463
+ const data = [];
1464
+ const extend = [];
1465
+ for (const [name, handlerName] of Object.entries(prop)) {
1466
+ if (name == config.eventExtendsName) {
1467
+ const extendsFile = handlerName.split(",");
1468
+ for (const extFile of extendsFile) {
1469
+ if (!(await McxUtlis.FileExsit(path.join(path.dirname(ctx.currentId), extFile))))
1470
+ throw new Error("[transform event]: can't resolve");
1471
+ const id = extFile.replace(/[!a-zA-Z0-9]+/g, "_");
1472
+ impBody.push(t__namespace.importDeclaration([t__namespace.importDefaultSpecifier(t__namespace.identifier(id))], t__namespace.stringLiteral(extFile)));
1473
+ extend.push(t__namespace.identifier(id));
1474
+ }
1475
+ }
1476
+ data.push(t__namespace.objectProperty(t__namespace.identifier(name), t__namespace.stringLiteral(handlerName)));
1435
1477
  }
1478
+ argm.properties.push(t__namespace.objectProperty(t__namespace.identifier("data"), t__namespace.objectExpression(data)), t__namespace.objectProperty(t__namespace.identifier("extends"), t__namespace.arrayExpression(extend)));
1479
+ return argm;
1436
1480
  }
1437
-
1438
- function addImport(statement, source, importArray) {
1439
- statement.unshift(t__namespace.importDeclaration(importArray, t__namespace.stringLiteral(source)));
1481
+ /**
1482
+ * record enable
1483
+ * @returns {(): void} - only call one
1484
+ */
1485
+ function _enable() {
1486
+ let success = false;
1487
+ const fn = function () {
1488
+ if (success)
1489
+ throw new Error("[enable]: can't enable again");
1490
+ success = true;
1491
+ fn.prototype.enable = success;
1492
+ };
1493
+ fn.prototype.enable = success;
1494
+ return fn;
1440
1495
  }
1441
- function loadEvent(event, body) {
1442
- const subscribeBody = [];
1443
- for (const [name, useExport] of Object.entries(event.subscribe)) {
1444
- subscribeBody.push(t__namespace.objectProperty(t__namespace.identifier(name), t__namespace.memberExpression(t__namespace.identifier(config.scriptCompileFn), t__namespace.identifier(useExport))));
1445
- }
1446
- const armg = t__namespace.objectExpression([
1447
- t__namespace.objectProperty(t__namespace.identifier("on"), t__namespace.stringLiteral(event.on)),
1448
- t__namespace.objectProperty(t__namespace.identifier("data"), t__namespace.objectExpression(subscribeBody)),
1449
- ]);
1450
- body.push(t__namespace.variableDeclaration("const", [
1451
- t__namespace.variableDeclarator(t__namespace.identifier(config.eventVarName), t__namespace.newExpression(t__namespace.identifier(config.eventImported), [armg])),
1452
- ]));
1496
+ function _enableWithData() {
1497
+ let d = null;
1498
+ const fn = function (data) {
1499
+ if (d)
1500
+ throw new Error("[enable]: can't enable again");
1501
+ d = data;
1502
+ fn.prototype.enable = d;
1503
+ };
1504
+ fn.prototype.enable = d;
1505
+ return fn;
1453
1506
  }
1454
- async function transform(compileData, cache, id, context, opt) {
1455
- const mcxModule = "@mbler/mcx";
1456
- // first compile script
1457
- const statement = generateMain(compileData.JSIR);
1458
- let mcxtype = null;
1459
- // detect imported mcx modules that are events by checking cache or compiling
1460
- const eventImportIds = [];
1461
- // build default export object: { type: <mcxtype>, setup: __main, ...(event?) }
1462
- // event MCX
1463
- if (compileData.strLoc.Event.isLoad) {
1464
- mcxtype = "event";
1465
- addImport(statement, mcxModule, [
1466
- t__namespace.importSpecifier(t__namespace.identifier(config.eventImported), t__namespace.identifier("Event")),
1467
- ]);
1468
- loadEvent(compileData.strLoc.Event, statement);
1469
- // export named event object
1470
- }
1471
- // component MCX
1472
- if (Object.keys(compileData.strLoc.Component).length >= 1) {
1473
- if (mcxtype == "event")
1474
- throw new Error("[compile component]: a mcx must event or component, can't both");
1475
- // leave placeholder for component compilation
1476
- await compileComponent(compileData, opt);
1477
- // export a MCXFile-like default for components
1478
- const defObj = t__namespace.objectExpression([
1479
- t__namespace.objectProperty(t__namespace.identifier("type"), t__namespace.stringLiteral("component")),
1480
- t__namespace.objectProperty(t__namespace.identifier("setup"), t__namespace.identifier(config.scriptCompileFn)),
1481
- ]);
1482
- statement.push(t__namespace.exportDefaultDeclaration(defObj));
1483
- return generator__namespace.generate(t__namespace.program(statement)).code;
1484
- }
1485
- // app (default) MCX
1486
- if (!mcxtype) {
1487
- mcxtype = "app";
1488
- for (const imp of compileData.JSIR.BuildCache.import || []) {
1489
- if (path.parse(imp.source).dir == "")
1490
- continue;
1491
- const source = path.join(path.dirname(id), imp.source);
1492
- if (!source.endsWith(".mcx"))
1493
- continue;
1494
- // generate code;
1495
- let moduleData;
1496
- if (cache.has(source)) {
1497
- moduleData = cache.get(source);
1507
+
1508
+ async function Comp$2(ctx) {
1509
+ const internalCtx = ctx.ctx;
1510
+ ctx.impBody.push(t__namespace.importDeclaration([t__namespace.importSpecifier(t__namespace.identifier("__mcx_ui"), t__namespace.identifier("ui"))], t__namespace.stringLiteral("@mbler/mcx")));
1511
+ const uiTagNode = ctx.ctx.compiledCode.strLoc.UI;
1512
+ if (!uiTagNode || uiTagNode?.name !== "Ui")
1513
+ throw new Error("[UI Component]: why didn't parent compeled verify?");
1514
+ let MCXUIType = null;
1515
+ const UITree = [];
1516
+ for (const uiClientTag of uiTagNode.content) {
1517
+ if (uiClientTag.type == "TagNode") {
1518
+ // if has client TagNode
1519
+ if (uiClientTag.content.some(i => i.type == "TagNode")) {
1520
+ internalCtx.rollupContext.error("[UI]: can't support ui client element", uiClientTag.loc ? {
1521
+ column: uiClientTag.loc.start.index,
1522
+ line: uiClientTag.loc.start.line
1523
+ } : void 0);
1524
+ }
1525
+ // add to tree
1526
+ UITree.push({
1527
+ arr: uiClientTag.arr,
1528
+ content: uiClientTag.content.map(i => i.type == "TagContent" && i.data || "").join(""),
1529
+ type: uiClientTag.name,
1530
+ loc: uiClientTag.loc
1531
+ });
1532
+ }
1533
+ // continue TagContentNode
1534
+ }
1535
+ const parsedObj = [];
1536
+ function pushToTree(name, params, content) {
1537
+ parsedObj.push(t__namespace.objectExpression([
1538
+ t__namespace.objectProperty(t__namespace.identifier("type"), t__namespace.stringLiteral(name)),
1539
+ t__namespace.objectProperty(t__namespace.identifier("params"), t__namespace.objectExpression(Object.entries(params).map(i => {
1540
+ return t__namespace.objectProperty(t__namespace.identifier(i[0]), typeof i[1] == "boolean" ? t__namespace.booleanLiteral(i[1]) : t__namespace.stringLiteral(i[1]));
1541
+ }))),
1542
+ t__namespace.objectProperty(t__namespace.identifier("content"), t__namespace.stringLiteral(content))
1543
+ ]));
1544
+ }
1545
+ // generate type and parsed tree
1546
+ for (const tp of UITree) {
1547
+ const name = tp.type;
1548
+ // only ModalFormData Element
1549
+ if (["input", "dropdown", "submit", "toggle", "slider"].includes(name)) {
1550
+ // ModalFromData
1551
+ if (MCXUIType && MCXUIType !== "ModalFormData") {
1552
+ internalCtx.rollupContext.error("[UI]: a mcx can't have a ModalFormData Node and other form tag", tp.loc ? {
1553
+ line: tp.loc.start.line,
1554
+ column: tp.loc.start.index
1555
+ } : void 0);
1556
+ }
1557
+ MCXUIType = "ModalFormData";
1558
+ pushToTree(name, tp.arr, tp.content);
1559
+ }
1560
+ // only MessageFormData Element
1561
+ else if (["button-m"].includes(name)) {
1562
+ if (MCXUIType && MCXUIType !== "MessageFormData") {
1563
+ internalCtx.rollupContext.error("[UI]: ", tp.loc ? {
1564
+ line: tp.loc.start.line,
1565
+ column: tp.loc.start.index
1566
+ } : void 0);
1567
+ }
1568
+ MCXUIType = "MessageFormData";
1569
+ pushToTree(name, tp.arr, tp.content);
1570
+ }
1571
+ // public
1572
+ else if (["body", "divider", "title"].includes(name)) {
1573
+ pushToTree(name, tp.arr, tp.content);
1574
+ }
1575
+ else {
1576
+ if (name == "button") {
1577
+ if (MCXUIType == "MessageFormData")
1578
+ internalCtx.rollupContext.error("[UI]: don't support use button for messageFormData", tp.loc ? {
1579
+ line: tp.loc.start.line,
1580
+ column: tp.loc.start.index
1581
+ } : void 0);
1582
+ pushToTree(name, tp.arr, tp.content);
1498
1583
  }
1499
1584
  else {
1500
- let code;
1501
- try {
1502
- code = await fs.readFile(source, "utf-8");
1503
- }
1504
- catch (err) {
1505
- context.warn("import '" + source + "' not exsit");
1506
- continue;
1507
- }
1508
- moduleData = compileMCXFn(code);
1509
- cache.set(source, moduleData);
1510
- }
1511
- if (!moduleData.strLoc.Event.isLoad)
1512
- continue;
1513
- for (const item of imp.imported) {
1514
- const base = t__namespace.identifier(item.as);
1515
- if (item.isAll)
1516
- eventImportIds.push(t__namespace.memberExpression(t__namespace.memberExpression(base, t__namespace.identifier("default")), t__namespace.identifier("event")));
1517
- else if (item.import == "default")
1518
- eventImportIds.push(t__namespace.memberExpression(base, t__namespace.identifier("event")));
1585
+ internalCtx.rollupContext.error("[UI]: don't support tag: " + name, tp.loc ? {
1586
+ line: tp.loc.start.line,
1587
+ column: tp.loc.start.index
1588
+ } : void 0);
1519
1589
  }
1520
1590
  }
1521
1591
  }
1522
- const props = [
1523
- t__namespace.objectProperty(t__namespace.identifier("type"), t__namespace.stringLiteral(mcxtype)),
1524
- t__namespace.objectProperty(t__namespace.identifier("setup"), t__namespace.objectExpression([])),
1525
- ];
1526
- // if this app imports an event mcx, attach it under `event` property
1527
- if (mcxtype === "app" && eventImportIds.length > 0) {
1528
- // prefer first discovered event import id
1529
- props.push(t__namespace.objectProperty(t__namespace.identifier("app"), t__namespace.objectExpression([
1530
- t__namespace.objectProperty(t__namespace.identifier("event"), eventImportIds[0]),
1531
- ])));
1532
- }
1533
- // if this is an event mcx we still need to provide named export 'event'
1534
- if (mcxtype === "event") {
1535
- // ensure default export still includes type and setup
1536
- props.push(t__namespace.objectProperty(t__namespace.identifier("event"), t__namespace.identifier(config.eventVarName)));
1537
- const defObj = t__namespace.objectExpression(props);
1538
- statement.push(t__namespace.exportDefaultDeclaration(defObj));
1539
- return generator__namespace.generate(t__namespace.program(statement)).code;
1540
- }
1541
- // normal app default export
1542
- const defObj = t__namespace.objectExpression(props);
1543
- statement.push(t__namespace.exportDefaultDeclaration(defObj));
1544
- return generator__namespace.generate(t__namespace.program(statement)).code;
1545
- }
1546
-
1547
- // src/vlq.ts
1548
- var comma = ",".charCodeAt(0);
1549
- var semicolon = ";".charCodeAt(0);
1550
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1551
- var intToChar = new Uint8Array(64);
1552
- var charToInt = new Uint8Array(128);
1553
- for (let i = 0; i < chars.length; i++) {
1554
- const c = chars.charCodeAt(i);
1555
- intToChar[i] = c;
1556
- charToInt[c] = i;
1557
- }
1558
- function encodeInteger(builder, num, relative) {
1559
- let delta = num - relative;
1560
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
1561
- do {
1562
- let clamped = delta & 31;
1563
- delta >>>= 5;
1564
- if (delta > 0) clamped |= 32;
1565
- builder.write(intToChar[clamped]);
1566
- } while (delta > 0);
1567
- return num;
1568
- }
1569
-
1570
- // src/strings.ts
1571
- var bufLength = 1024 * 16;
1572
- var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
1573
- decode(buf) {
1574
- const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
1575
- return out.toString();
1576
- }
1577
- } : {
1578
- decode(buf) {
1579
- let out = "";
1580
- for (let i = 0; i < buf.length; i++) {
1581
- out += String.fromCharCode(buf[i]);
1582
- }
1583
- return out;
1584
- }
1585
- };
1586
- var StringWriter = class {
1587
- constructor() {
1588
- this.pos = 0;
1589
- this.out = "";
1590
- this.buffer = new Uint8Array(bufLength);
1591
- }
1592
- write(v) {
1593
- const { buffer } = this;
1594
- buffer[this.pos++] = v;
1595
- if (this.pos === bufLength) {
1596
- this.out += td.decode(buffer);
1597
- this.pos = 0;
1598
- }
1599
- }
1600
- flush() {
1601
- const { buffer, out, pos } = this;
1602
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
1603
- }
1604
- };
1605
- function encode(decoded) {
1606
- const writer = new StringWriter();
1607
- let sourcesIndex = 0;
1608
- let sourceLine = 0;
1609
- let sourceColumn = 0;
1610
- let namesIndex = 0;
1611
- for (let i = 0; i < decoded.length; i++) {
1612
- const line = decoded[i];
1613
- if (i > 0) writer.write(semicolon);
1614
- if (line.length === 0) continue;
1615
- let genColumn = 0;
1616
- for (let j = 0; j < line.length; j++) {
1617
- const segment = line[j];
1618
- if (j > 0) writer.write(comma);
1619
- genColumn = encodeInteger(writer, segment[0], genColumn);
1620
- if (segment.length === 1) continue;
1621
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
1622
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
1623
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
1624
- if (segment.length === 4) continue;
1625
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
1626
- }
1627
- }
1628
- return writer.flush();
1629
- }
1630
-
1631
- class BitSet {
1632
- constructor(arg) {
1633
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
1634
- }
1635
-
1636
- add(n) {
1637
- this.bits[n >> 5] |= 1 << (n & 31);
1638
- }
1639
-
1640
- has(n) {
1641
- return !!(this.bits[n >> 5] & (1 << (n & 31)));
1642
- }
1643
- }
1644
-
1645
- class Chunk {
1646
- constructor(start, end, content) {
1647
- this.start = start;
1648
- this.end = end;
1649
- this.original = content;
1650
-
1651
- this.intro = '';
1652
- this.outro = '';
1653
-
1654
- this.content = content;
1655
- this.storeName = false;
1656
- this.edited = false;
1657
-
1658
- {
1659
- this.previous = null;
1660
- this.next = null;
1661
- }
1662
- }
1663
-
1664
- appendLeft(content) {
1665
- this.outro += content;
1666
- }
1667
-
1668
- appendRight(content) {
1669
- this.intro = this.intro + content;
1670
- }
1671
-
1672
- clone() {
1673
- const chunk = new Chunk(this.start, this.end, this.original);
1674
-
1675
- chunk.intro = this.intro;
1676
- chunk.outro = this.outro;
1677
- chunk.content = this.content;
1678
- chunk.storeName = this.storeName;
1679
- chunk.edited = this.edited;
1680
-
1681
- return chunk;
1682
- }
1683
-
1684
- contains(index) {
1685
- return this.start < index && index < this.end;
1686
- }
1687
-
1688
- eachNext(fn) {
1689
- let chunk = this;
1690
- while (chunk) {
1691
- fn(chunk);
1692
- chunk = chunk.next;
1693
- }
1694
- }
1695
-
1696
- eachPrevious(fn) {
1697
- let chunk = this;
1698
- while (chunk) {
1699
- fn(chunk);
1700
- chunk = chunk.previous;
1701
- }
1702
- }
1703
-
1704
- edit(content, storeName, contentOnly) {
1705
- this.content = content;
1706
- if (!contentOnly) {
1707
- this.intro = '';
1708
- this.outro = '';
1709
- }
1710
- this.storeName = storeName;
1711
-
1712
- this.edited = true;
1713
-
1714
- return this;
1715
- }
1716
-
1717
- prependLeft(content) {
1718
- this.outro = content + this.outro;
1719
- }
1720
-
1721
- prependRight(content) {
1722
- this.intro = content + this.intro;
1723
- }
1724
-
1725
- reset() {
1726
- this.intro = '';
1727
- this.outro = '';
1728
- if (this.edited) {
1729
- this.content = this.original;
1730
- this.storeName = false;
1731
- this.edited = false;
1732
- }
1733
- }
1734
-
1735
- split(index) {
1736
- const sliceIndex = index - this.start;
1737
-
1738
- const originalBefore = this.original.slice(0, sliceIndex);
1739
- const originalAfter = this.original.slice(sliceIndex);
1740
-
1741
- this.original = originalBefore;
1742
-
1743
- const newChunk = new Chunk(index, this.end, originalAfter);
1744
- newChunk.outro = this.outro;
1745
- this.outro = '';
1746
-
1747
- this.end = index;
1748
-
1749
- if (this.edited) {
1750
- // after split we should save the edit content record into the correct chunk
1751
- // to make sure sourcemap correct
1752
- // For example:
1753
- // ' test'.trim()
1754
- // split -> ' ' + 'test'
1755
- // ✔️ edit -> '' + 'test'
1756
- // ✖️ edit -> 'test' + ''
1757
- // TODO is this block necessary?...
1758
- newChunk.edit('', false);
1759
- this.content = '';
1760
- } else {
1761
- this.content = originalBefore;
1762
- }
1763
-
1764
- newChunk.next = this.next;
1765
- if (newChunk.next) newChunk.next.previous = newChunk;
1766
- newChunk.previous = this;
1767
- this.next = newChunk;
1768
-
1769
- return newChunk;
1770
- }
1771
-
1772
- toString() {
1773
- return this.intro + this.content + this.outro;
1774
- }
1775
-
1776
- trimEnd(rx) {
1777
- this.outro = this.outro.replace(rx, '');
1778
- if (this.outro.length) return true;
1779
-
1780
- const trimmed = this.content.replace(rx, '');
1781
-
1782
- if (trimmed.length) {
1783
- if (trimmed !== this.content) {
1784
- this.split(this.start + trimmed.length).edit('', undefined, true);
1785
- if (this.edited) {
1786
- // save the change, if it has been edited
1787
- this.edit(trimmed, this.storeName, true);
1788
- }
1789
- }
1790
- return true;
1791
- } else {
1792
- this.edit('', undefined, true);
1793
-
1794
- this.intro = this.intro.replace(rx, '');
1795
- if (this.intro.length) return true;
1796
- }
1797
- }
1798
-
1799
- trimStart(rx) {
1800
- this.intro = this.intro.replace(rx, '');
1801
- if (this.intro.length) return true;
1802
-
1803
- const trimmed = this.content.replace(rx, '');
1804
-
1805
- if (trimmed.length) {
1806
- if (trimmed !== this.content) {
1807
- const newChunk = this.split(this.end - trimmed.length);
1808
- if (this.edited) {
1809
- // save the change, if it has been edited
1810
- newChunk.edit(trimmed, this.storeName, true);
1811
- }
1812
- this.edit('', undefined, true);
1813
- }
1814
- return true;
1815
- } else {
1816
- this.edit('', undefined, true);
1817
-
1818
- this.outro = this.outro.replace(rx, '');
1819
- if (this.outro.length) return true;
1820
- }
1821
- }
1822
- }
1823
-
1824
- function getBtoa() {
1825
- if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
1826
- return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
1827
- } else if (typeof Buffer === 'function') {
1828
- return (str) => Buffer.from(str, 'utf-8').toString('base64');
1829
- } else {
1830
- return () => {
1831
- throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
1832
- };
1833
- }
1834
- }
1835
-
1836
- const btoa = /*#__PURE__*/ getBtoa();
1837
-
1838
- class SourceMap {
1839
- constructor(properties) {
1840
- this.version = 3;
1841
- this.file = properties.file;
1842
- this.sources = properties.sources;
1843
- this.sourcesContent = properties.sourcesContent;
1844
- this.names = properties.names;
1845
- this.mappings = encode(properties.mappings);
1846
- if (typeof properties.x_google_ignoreList !== 'undefined') {
1847
- this.x_google_ignoreList = properties.x_google_ignoreList;
1848
- }
1849
- if (typeof properties.debugId !== 'undefined') {
1850
- this.debugId = properties.debugId;
1851
- }
1852
- }
1853
-
1854
- toString() {
1855
- return JSON.stringify(this);
1856
- }
1857
-
1858
- toUrl() {
1859
- return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
1860
- }
1861
- }
1862
-
1863
- function guessIndent(code) {
1864
- const lines = code.split('\n');
1865
-
1866
- const tabbed = lines.filter((line) => /^\t+/.test(line));
1867
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
1868
-
1869
- if (tabbed.length === 0 && spaced.length === 0) {
1870
- return null;
1871
- }
1872
-
1873
- // More lines tabbed than spaced? Assume tabs, and
1874
- // default to tabs in the case of a tie (or nothing
1875
- // to go on)
1876
- if (tabbed.length >= spaced.length) {
1877
- return '\t';
1878
- }
1879
-
1880
- // Otherwise, we need to guess the multiple
1881
- const min = spaced.reduce((previous, current) => {
1882
- const numSpaces = /^ +/.exec(current)[0].length;
1883
- return Math.min(numSpaces, previous);
1884
- }, Infinity);
1885
-
1886
- return new Array(min + 1).join(' ');
1592
+ if (!MCXUIType)
1593
+ MCXUIType = "ActionFromData";
1594
+ const finallyData = t__namespace.objectExpression([
1595
+ t__namespace.objectProperty(t__namespace.identifier("layout"), t__namespace.arrayExpression(parsedObj)),
1596
+ t__namespace.objectProperty(t__namespace.identifier("use"), t__namespace.identifier(MCXUIType))
1597
+ ]);
1598
+ ctx.impBody.push(t__namespace.importDeclaration([
1599
+ t__namespace.importSpecifier(t__namespace.identifier(MCXUIType), t__namespace.identifier(MCXUIType))
1600
+ ], t__namespace.stringLiteral("@minecraft/server-ui")));
1601
+ ctx.app([
1602
+ t__namespace.objectProperty(t__namespace.identifier("ui"), t__namespace.newExpression(t__namespace.identifier("__mcx__ui"), [finallyData]))
1603
+ ]);
1887
1604
  }
1888
1605
 
1889
- function getRelativePath(from, to) {
1890
- const fromParts = from.split(/[/\\]/);
1891
- const toParts = to.split(/[/\\]/);
1892
-
1893
- fromParts.pop(); // get dirname
1894
-
1895
- while (fromParts[0] === toParts[0]) {
1896
- fromParts.shift();
1897
- toParts.shift();
1898
- }
1899
-
1900
- if (fromParts.length) {
1901
- let i = fromParts.length;
1902
- while (i--) fromParts[i] = '..';
1903
- }
1904
-
1905
- return fromParts.concat(toParts).join('/');
1606
+ async function Comp$1(ctx) {
1607
+ const appData = [
1608
+ t__namespace.objectProperty(t__namespace.identifier("event"), await generateEventConfig(ctx.ctx.compiledCode.raw.find((node) => node.name === "Event"), ctx.ctx, ctx.impBody)),
1609
+ ];
1610
+ ctx.app(appData);
1906
1611
  }
1907
1612
 
1908
- const toString = Object.prototype.toString;
1909
-
1910
- function isObject(thing) {
1911
- return toString.call(thing) === '[object Object]';
1613
+ async function Comp(ctx) {
1614
+ const eventImportIdList = [];
1615
+ for (const impNode of ctx.ctx.compiledCode.JSIR.BuildCache.import) {
1616
+ const source = impNode.source;
1617
+ const parsed = path.parse(source);
1618
+ if (!parsed.root && !parsed.dir.startsWith(".")) {
1619
+ continue;
1620
+ }
1621
+ // path
1622
+ const fPath = path.join(ctx.ctx.currentId, "../", source);
1623
+ try {
1624
+ // read file
1625
+ const code = await fs.readFile(fPath, "utf-8");
1626
+ const compiledCode = compileMCXFn(code);
1627
+ // write cache
1628
+ ctx.ctx.cache.set(fPath, compiledCode);
1629
+ if (compiledCode.strLoc.Event.isLoad) {
1630
+ for (const impItem of impNode.imported) {
1631
+ let type;
1632
+ if (impItem.isAll)
1633
+ type = "all";
1634
+ else if (impItem.import == "default")
1635
+ type = "default";
1636
+ else {
1637
+ throw new Error("not vaild importDeclartion: Event mcx only resolve default and all import, can't use other import");
1638
+ }
1639
+ eventImportIdList.push({
1640
+ type,
1641
+ as: impItem.as
1642
+ });
1643
+ }
1644
+ }
1645
+ }
1646
+ catch (err) {
1647
+ // if error: file not found, file can't write, mcx syntax error
1648
+ ctx.ctx.rollupContext.warn(`[extract import]: can't resolve file ${fPath} and import by ${ctx.ctx.currentId}\n- err: ${(err instanceof Error) ? err.stack : err}`);
1649
+ }
1650
+ }
1651
+ // only have event import
1652
+ if (eventImportIdList.length > 1) {
1653
+ ctx.mainFn.unshift(
1654
+ // add declaration
1655
+ t__namespace.variableDeclaration("var", eventImportIdList.map((item, index) => {
1656
+ if (item.type == "all") {
1657
+ return t__namespace.variableDeclarator(t__namespace.identifier(item.as), t__namespace.objectExpression([
1658
+ t__namespace.objectProperty(t__namespace.identifier("default"), t__namespace.memberExpression(t__namespace.identifier(config.paramCtx), t__namespace.identifier(`event$$${index}`))),
1659
+ ]));
1660
+ }
1661
+ else if (item.type == "default") {
1662
+ return t__namespace.variableDeclarator(t__namespace.identifier(item.as), t__namespace.memberExpression(t__namespace.identifier(config.paramCtx), t__namespace.identifier(`event$$${index}`)));
1663
+ }
1664
+ // ts galgame
1665
+ throw new Error("[javascript error]: why it not in [default, all]");
1666
+ })));
1667
+ // app: add event export to runtime framework
1668
+ const appData = [
1669
+ t__namespace.objectProperty(t__namespace.identifier("event"), t__namespace.arrayExpression(eventImportIdList.map(vl => {
1670
+ if (vl.type == "all") {
1671
+ return t__namespace.memberExpression(t__namespace.identifier(vl.as), t__namespace.identifier("default"));
1672
+ }
1673
+ else if (vl.type == "default") {
1674
+ return t__namespace.identifier(vl.as);
1675
+ }
1676
+ throw new Error("[add prop]: can't format eventImportList");
1677
+ })))
1678
+ ];
1679
+ ctx.app(appData);
1680
+ }
1912
1681
  }
1913
1682
 
1914
- function getLocator(source) {
1915
- const originalLines = source.split('\n');
1916
- const lineOffsets = [];
1917
-
1918
- for (let i = 0, pos = 0; i < originalLines.length; i++) {
1919
- lineOffsets.push(pos);
1920
- pos += originalLines[i].length + 1;
1921
- }
1922
-
1923
- return function locate(index) {
1924
- let i = 0;
1925
- let j = lineOffsets.length;
1926
- while (i < j) {
1927
- const m = (i + j) >> 1;
1928
- if (index < lineOffsets[m]) {
1929
- j = m;
1930
- } else {
1931
- i = m + 1;
1932
- }
1933
- }
1934
- const line = i - 1;
1935
- const column = index - lineOffsets[line];
1936
- return { line, column };
1937
- };
1683
+ async function compileComponent(compiledCode, project) {
1684
+ const component = compiledCode.strLoc.Component;
1685
+ for (const i of Object.entries(component)) {
1686
+ // TODO: compele compile component
1687
+ }
1938
1688
  }
1939
1689
 
1940
- const wordRegex = /\w/;
1941
-
1942
- class Mappings {
1943
- constructor(hires) {
1944
- this.hires = hires;
1945
- this.generatedCodeLine = 0;
1946
- this.generatedCodeColumn = 0;
1947
- this.raw = [];
1948
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
1949
- this.pending = null;
1950
- }
1951
-
1952
- addEdit(sourceIndex, content, loc, nameIndex) {
1953
- if (content.length) {
1954
- const contentLengthMinusOne = content.length - 1;
1955
- let contentLineEnd = content.indexOf('\n', 0);
1956
- let previousContentLineEnd = -1;
1957
- // Loop through each line in the content and add a segment, but stop if the last line is empty,
1958
- // else code afterwards would fill one line too many
1959
- while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
1960
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1961
- if (nameIndex >= 0) {
1962
- segment.push(nameIndex);
1963
- }
1964
- this.rawSegments.push(segment);
1965
-
1966
- this.generatedCodeLine += 1;
1967
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
1968
- this.generatedCodeColumn = 0;
1969
-
1970
- previousContentLineEnd = contentLineEnd;
1971
- contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
1972
- }
1973
-
1974
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1975
- if (nameIndex >= 0) {
1976
- segment.push(nameIndex);
1977
- }
1978
- this.rawSegments.push(segment);
1979
-
1980
- this.advance(content.slice(previousContentLineEnd + 1));
1981
- } else if (this.pending) {
1982
- this.rawSegments.push(this.pending);
1983
- this.advance(content);
1984
- }
1985
-
1986
- this.pending = null;
1987
- }
1988
-
1989
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
1990
- let originalCharIndex = chunk.start;
1991
- let first = true;
1992
- // when iterating each char, check if it's in a word boundary
1993
- let charInHiresBoundary = false;
1994
-
1995
- while (originalCharIndex < chunk.end) {
1996
- if (original[originalCharIndex] === '\n') {
1997
- loc.line += 1;
1998
- loc.column = 0;
1999
- this.generatedCodeLine += 1;
2000
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
2001
- this.generatedCodeColumn = 0;
2002
- first = true;
2003
- charInHiresBoundary = false;
2004
- } else {
2005
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
2006
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
2007
-
2008
- if (this.hires === 'boundary') {
2009
- // in hires "boundary", group segments per word boundary than per char
2010
- if (wordRegex.test(original[originalCharIndex])) {
2011
- // for first char in the boundary found, start the boundary by pushing a segment
2012
- if (!charInHiresBoundary) {
2013
- this.rawSegments.push(segment);
2014
- charInHiresBoundary = true;
2015
- }
2016
- } else {
2017
- // for non-word char, end the boundary by pushing a segment
2018
- this.rawSegments.push(segment);
2019
- charInHiresBoundary = false;
2020
- }
2021
- } else {
2022
- this.rawSegments.push(segment);
2023
- }
2024
- }
2025
-
2026
- loc.column += 1;
2027
- this.generatedCodeColumn += 1;
2028
- first = false;
2029
- }
2030
-
2031
- originalCharIndex += 1;
2032
- }
2033
-
2034
- this.pending = null;
2035
- }
2036
-
2037
- advance(str) {
2038
- if (!str) return;
2039
-
2040
- const lines = str.split('\n');
2041
-
2042
- if (lines.length > 1) {
2043
- for (let i = 0; i < lines.length - 1; i++) {
2044
- this.generatedCodeLine++;
2045
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
2046
- }
2047
- this.generatedCodeColumn = 0;
2048
- }
1690
+ var index = /*#__PURE__*/Object.freeze({
1691
+ __proto__: null,
1692
+ compileComponent: compileComponent
1693
+ });
2049
1694
 
2050
- this.generatedCodeColumn += lines[lines.length - 1].length;
2051
- }
1695
+ async function _transform(ctx) {
1696
+ const _temp_main = generateMain(ctx.compiledCode.JSIR);
1697
+ const mainFn = ctx.mainFn.body = _temp_main[0];
1698
+ const prop = [];
1699
+ const app = _enableWithData();
1700
+ const params = ctx.mainFn.param = [
1701
+ t__namespace.identifier(config.paramCtx)
1702
+ ];
1703
+ const parseCtx = {
1704
+ impBody: _temp_main[1],
1705
+ mainFn,
1706
+ prop,
1707
+ ctx: ctx,
1708
+ app
1709
+ };
1710
+ let type = "app";
1711
+ // enable setup fn: use to generate setup
1712
+ const enableSetup = _enable();
1713
+ if (ctx.compiledCode.strLoc.Event.isLoad) {
1714
+ // handler event type mcx
1715
+ type = "event";
1716
+ // enable export setup
1717
+ enableSetup();
1718
+ await Comp$1(parseCtx);
1719
+ }
1720
+ if (ctx.compiledCode.strLoc.UI) {
1721
+ /**
1722
+ * Completed UI handler
1723
+ * @todo - handler
1724
+ */
1725
+ type = "ui"; // ui mcx
1726
+ enableSetup();
1727
+ await Comp$2(parseCtx);
1728
+ }
1729
+ if (Object.getOwnPropertyNames(ctx.compiledCode.strLoc.Component).length >= 1) {
1730
+ type = "component";
1731
+ await compileComponent(ctx.compiledCode, ctx.opt.ProjectDir);
1732
+ return `export default {type:'component',setup:null,app:{}}`;
1733
+ }
1734
+ if (type == "app") {
1735
+ // enable setup export
1736
+ enableSetup();
1737
+ // find event mcx import
1738
+ await Comp(parseCtx);
1739
+ }
1740
+ // add default export: type
1741
+ prop.push(t__namespace.objectProperty(t__namespace.identifier("type"), t__namespace.stringLiteral(type)));
1742
+ if (enableSetup.prototype.enable) {
1743
+ prop.push(t__namespace.objectProperty(t__namespace.identifier("setup"), t__namespace.identifier(config.scriptCompileFn)));
1744
+ }
1745
+ if (app.prototype.enable) {
1746
+ prop.push(t__namespace.objectProperty(t__namespace.identifier("app"), t__namespace.objectExpression(app.prototype.enable)));
1747
+ }
1748
+ // generate code
1749
+ const code = generator.generate(
1750
+ // create program
1751
+ (t__namespace.program([
1752
+ ...parseCtx.impBody,
1753
+ t__namespace.functionDeclaration(t__namespace.identifier(config.scriptCompileFn), params, t__namespace.blockStatement(mainFn), false, false),
1754
+ t__namespace.exportDefaultDeclaration(t__namespace.objectExpression(prop)),
1755
+ ]))).code;
1756
+ return code;
2052
1757
  }
2053
1758
 
2054
- const n = '\n';
2055
-
2056
- const warned = {
2057
- insertLeft: false,
2058
- insertRight: false,
2059
- storeName: false,
2060
- };
2061
-
2062
- class MagicString {
2063
- constructor(string, options = {}) {
2064
- const chunk = new Chunk(0, string.length, string);
2065
-
2066
- Object.defineProperties(this, {
2067
- original: { writable: true, value: string },
2068
- outro: { writable: true, value: '' },
2069
- intro: { writable: true, value: '' },
2070
- firstChunk: { writable: true, value: chunk },
2071
- lastChunk: { writable: true, value: chunk },
2072
- lastSearchedChunk: { writable: true, value: chunk },
2073
- byStart: { writable: true, value: {} },
2074
- byEnd: { writable: true, value: {} },
2075
- filename: { writable: true, value: options.filename },
2076
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
2077
- sourcemapLocations: { writable: true, value: new BitSet() },
2078
- storedNames: { writable: true, value: {} },
2079
- indentStr: { writable: true, value: undefined },
2080
- ignoreList: { writable: true, value: options.ignoreList },
2081
- offset: { writable: true, value: options.offset || 0 },
2082
- });
2083
-
2084
- this.byStart[0] = chunk;
2085
- this.byEnd[string.length] = chunk;
2086
- }
2087
-
2088
- addSourcemapLocation(char) {
2089
- this.sourcemapLocations.add(char);
2090
- }
2091
-
2092
- append(content) {
2093
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
2094
-
2095
- this.outro += content;
2096
- return this;
2097
- }
2098
-
2099
- appendLeft(index, content) {
2100
- index = index + this.offset;
2101
-
2102
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
2103
-
2104
- this._split(index);
2105
-
2106
- const chunk = this.byEnd[index];
2107
-
2108
- if (chunk) {
2109
- chunk.appendLeft(content);
2110
- } else {
2111
- this.intro += content;
2112
- }
2113
- return this;
2114
- }
2115
-
2116
- appendRight(index, content) {
2117
- index = index + this.offset;
2118
-
2119
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
2120
-
2121
- this._split(index);
2122
-
2123
- const chunk = this.byStart[index];
2124
-
2125
- if (chunk) {
2126
- chunk.appendRight(content);
2127
- } else {
2128
- this.outro += content;
2129
- }
2130
- return this;
2131
- }
2132
-
2133
- clone() {
2134
- const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
2135
-
2136
- let originalChunk = this.firstChunk;
2137
- let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
2138
-
2139
- while (originalChunk) {
2140
- cloned.byStart[clonedChunk.start] = clonedChunk;
2141
- cloned.byEnd[clonedChunk.end] = clonedChunk;
2142
-
2143
- const nextOriginalChunk = originalChunk.next;
2144
- const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
2145
-
2146
- if (nextClonedChunk) {
2147
- clonedChunk.next = nextClonedChunk;
2148
- nextClonedChunk.previous = clonedChunk;
2149
-
2150
- clonedChunk = nextClonedChunk;
2151
- }
2152
-
2153
- originalChunk = nextOriginalChunk;
2154
- }
2155
-
2156
- cloned.lastChunk = clonedChunk;
2157
-
2158
- if (this.indentExclusionRanges) {
2159
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
2160
- }
2161
-
2162
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
2163
-
2164
- cloned.intro = this.intro;
2165
- cloned.outro = this.outro;
2166
-
2167
- return cloned;
2168
- }
2169
-
2170
- generateDecodedMap(options) {
2171
- options = options || {};
2172
-
2173
- const sourceIndex = 0;
2174
- const names = Object.keys(this.storedNames);
2175
- const mappings = new Mappings(options.hires);
2176
-
2177
- const locate = getLocator(this.original);
2178
-
2179
- if (this.intro) {
2180
- mappings.advance(this.intro);
2181
- }
2182
-
2183
- this.firstChunk.eachNext((chunk) => {
2184
- const loc = locate(chunk.start);
2185
-
2186
- if (chunk.intro.length) mappings.advance(chunk.intro);
2187
-
2188
- if (chunk.edited) {
2189
- mappings.addEdit(
2190
- sourceIndex,
2191
- chunk.content,
2192
- loc,
2193
- chunk.storeName ? names.indexOf(chunk.original) : -1,
2194
- );
2195
- } else {
2196
- mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
2197
- }
2198
-
2199
- if (chunk.outro.length) mappings.advance(chunk.outro);
2200
- });
2201
-
2202
- if (this.outro) {
2203
- mappings.advance(this.outro);
2204
- }
2205
-
2206
- return {
2207
- file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
2208
- sources: [
2209
- options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
2210
- ],
2211
- sourcesContent: options.includeContent ? [this.original] : undefined,
2212
- names,
2213
- mappings: mappings.raw,
2214
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
2215
- };
2216
- }
2217
-
2218
- generateMap(options) {
2219
- return new SourceMap(this.generateDecodedMap(options));
2220
- }
2221
-
2222
- _ensureindentStr() {
2223
- if (this.indentStr === undefined) {
2224
- this.indentStr = guessIndent(this.original);
2225
- }
2226
- }
2227
-
2228
- _getRawIndentString() {
2229
- this._ensureindentStr();
2230
- return this.indentStr;
2231
- }
2232
-
2233
- getIndentString() {
2234
- this._ensureindentStr();
2235
- return this.indentStr === null ? '\t' : this.indentStr;
2236
- }
2237
-
2238
- indent(indentStr, options) {
2239
- const pattern = /^[^\r\n]/gm;
2240
-
2241
- if (isObject(indentStr)) {
2242
- options = indentStr;
2243
- indentStr = undefined;
2244
- }
2245
-
2246
- if (indentStr === undefined) {
2247
- this._ensureindentStr();
2248
- indentStr = this.indentStr || '\t';
2249
- }
2250
-
2251
- if (indentStr === '') return this; // noop
2252
-
2253
- options = options || {};
2254
-
2255
- // Process exclusion ranges
2256
- const isExcluded = {};
2257
-
2258
- if (options.exclude) {
2259
- const exclusions =
2260
- typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
2261
- exclusions.forEach((exclusion) => {
2262
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
2263
- isExcluded[i] = true;
2264
- }
2265
- });
2266
- }
2267
-
2268
- let shouldIndentNextCharacter = options.indentStart !== false;
2269
- const replacer = (match) => {
2270
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
2271
- shouldIndentNextCharacter = true;
2272
- return match;
2273
- };
2274
-
2275
- this.intro = this.intro.replace(pattern, replacer);
2276
-
2277
- let charIndex = 0;
2278
- let chunk = this.firstChunk;
2279
-
2280
- while (chunk) {
2281
- const end = chunk.end;
2282
-
2283
- if (chunk.edited) {
2284
- if (!isExcluded[charIndex]) {
2285
- chunk.content = chunk.content.replace(pattern, replacer);
2286
-
2287
- if (chunk.content.length) {
2288
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
2289
- }
2290
- }
2291
- } else {
2292
- charIndex = chunk.start;
2293
-
2294
- while (charIndex < end) {
2295
- if (!isExcluded[charIndex]) {
2296
- const char = this.original[charIndex];
2297
-
2298
- if (char === '\n') {
2299
- shouldIndentNextCharacter = true;
2300
- } else if (char !== '\r' && shouldIndentNextCharacter) {
2301
- shouldIndentNextCharacter = false;
2302
-
2303
- if (charIndex === chunk.start) {
2304
- chunk.prependRight(indentStr);
2305
- } else {
2306
- this._splitChunk(chunk, charIndex);
2307
- chunk = chunk.next;
2308
- chunk.prependRight(indentStr);
2309
- }
2310
- }
2311
- }
2312
-
2313
- charIndex += 1;
2314
- }
2315
- }
2316
-
2317
- charIndex = chunk.end;
2318
- chunk = chunk.next;
2319
- }
2320
-
2321
- this.outro = this.outro.replace(pattern, replacer);
2322
-
2323
- return this;
2324
- }
2325
-
2326
- insert() {
2327
- throw new Error(
2328
- 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
2329
- );
2330
- }
2331
-
2332
- insertLeft(index, content) {
2333
- if (!warned.insertLeft) {
2334
- console.warn(
2335
- 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
2336
- );
2337
- warned.insertLeft = true;
2338
- }
2339
-
2340
- return this.appendLeft(index, content);
2341
- }
2342
-
2343
- insertRight(index, content) {
2344
- if (!warned.insertRight) {
2345
- console.warn(
2346
- 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
2347
- );
2348
- warned.insertRight = true;
2349
- }
2350
-
2351
- return this.prependRight(index, content);
2352
- }
2353
-
2354
- move(start, end, index) {
2355
- start = start + this.offset;
2356
- end = end + this.offset;
2357
- index = index + this.offset;
2358
-
2359
- if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
2360
-
2361
- this._split(start);
2362
- this._split(end);
2363
- this._split(index);
2364
-
2365
- const first = this.byStart[start];
2366
- const last = this.byEnd[end];
2367
-
2368
- const oldLeft = first.previous;
2369
- const oldRight = last.next;
2370
-
2371
- const newRight = this.byStart[index];
2372
- if (!newRight && last === this.lastChunk) return this;
2373
- const newLeft = newRight ? newRight.previous : this.lastChunk;
2374
-
2375
- if (oldLeft) oldLeft.next = oldRight;
2376
- if (oldRight) oldRight.previous = oldLeft;
2377
-
2378
- if (newLeft) newLeft.next = first;
2379
- if (newRight) newRight.previous = last;
2380
-
2381
- if (!first.previous) this.firstChunk = last.next;
2382
- if (!last.next) {
2383
- this.lastChunk = first.previous;
2384
- this.lastChunk.next = null;
2385
- }
2386
-
2387
- first.previous = newLeft;
2388
- last.next = newRight || null;
2389
-
2390
- if (!newLeft) this.firstChunk = first;
2391
- if (!newRight) this.lastChunk = last;
2392
- return this;
2393
- }
2394
-
2395
- overwrite(start, end, content, options) {
2396
- options = options || {};
2397
- return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
2398
- }
2399
-
2400
- update(start, end, content, options) {
2401
- start = start + this.offset;
2402
- end = end + this.offset;
2403
-
2404
- if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
2405
-
2406
- if (this.original.length !== 0) {
2407
- while (start < 0) start += this.original.length;
2408
- while (end < 0) end += this.original.length;
2409
- }
2410
-
2411
- if (end > this.original.length) throw new Error('end is out of bounds');
2412
- if (start === end)
2413
- throw new Error(
2414
- 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
2415
- );
2416
-
2417
- this._split(start);
2418
- this._split(end);
2419
-
2420
- if (options === true) {
2421
- if (!warned.storeName) {
2422
- console.warn(
2423
- 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
2424
- );
2425
- warned.storeName = true;
2426
- }
2427
-
2428
- options = { storeName: true };
2429
- }
2430
- const storeName = options !== undefined ? options.storeName : false;
2431
- const overwrite = options !== undefined ? options.overwrite : false;
2432
-
2433
- if (storeName) {
2434
- const original = this.original.slice(start, end);
2435
- Object.defineProperty(this.storedNames, original, {
2436
- writable: true,
2437
- value: true,
2438
- enumerable: true,
2439
- });
2440
- }
2441
-
2442
- const first = this.byStart[start];
2443
- const last = this.byEnd[end];
2444
-
2445
- if (first) {
2446
- let chunk = first;
2447
- while (chunk !== last) {
2448
- if (chunk.next !== this.byStart[chunk.end]) {
2449
- throw new Error('Cannot overwrite across a split point');
2450
- }
2451
- chunk = chunk.next;
2452
- chunk.edit('', false);
2453
- }
2454
-
2455
- first.edit(content, storeName, !overwrite);
2456
- } else {
2457
- // must be inserting at the end
2458
- const newChunk = new Chunk(start, end, '').edit(content, storeName);
2459
-
2460
- // TODO last chunk in the array may not be the last chunk, if it's moved...
2461
- last.next = newChunk;
2462
- newChunk.previous = last;
2463
- }
2464
- return this;
2465
- }
2466
-
2467
- prepend(content) {
2468
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
2469
-
2470
- this.intro = content + this.intro;
2471
- return this;
2472
- }
2473
-
2474
- prependLeft(index, content) {
2475
- index = index + this.offset;
2476
-
2477
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
2478
-
2479
- this._split(index);
2480
-
2481
- const chunk = this.byEnd[index];
2482
-
2483
- if (chunk) {
2484
- chunk.prependLeft(content);
2485
- } else {
2486
- this.intro = content + this.intro;
2487
- }
2488
- return this;
2489
- }
2490
-
2491
- prependRight(index, content) {
2492
- index = index + this.offset;
2493
-
2494
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
2495
-
2496
- this._split(index);
2497
-
2498
- const chunk = this.byStart[index];
2499
-
2500
- if (chunk) {
2501
- chunk.prependRight(content);
2502
- } else {
2503
- this.outro = content + this.outro;
2504
- }
2505
- return this;
2506
- }
2507
-
2508
- remove(start, end) {
2509
- start = start + this.offset;
2510
- end = end + this.offset;
2511
-
2512
- if (this.original.length !== 0) {
2513
- while (start < 0) start += this.original.length;
2514
- while (end < 0) end += this.original.length;
2515
- }
2516
-
2517
- if (start === end) return this;
2518
-
2519
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
2520
- if (start > end) throw new Error('end must be greater than start');
2521
-
2522
- this._split(start);
2523
- this._split(end);
2524
-
2525
- let chunk = this.byStart[start];
2526
-
2527
- while (chunk) {
2528
- chunk.intro = '';
2529
- chunk.outro = '';
2530
- chunk.edit('');
2531
-
2532
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
2533
- }
2534
- return this;
2535
- }
2536
-
2537
- reset(start, end) {
2538
- start = start + this.offset;
2539
- end = end + this.offset;
2540
-
2541
- if (this.original.length !== 0) {
2542
- while (start < 0) start += this.original.length;
2543
- while (end < 0) end += this.original.length;
2544
- }
2545
-
2546
- if (start === end) return this;
2547
-
2548
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
2549
- if (start > end) throw new Error('end must be greater than start');
2550
-
2551
- this._split(start);
2552
- this._split(end);
2553
-
2554
- let chunk = this.byStart[start];
2555
-
2556
- while (chunk) {
2557
- chunk.reset();
2558
-
2559
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
2560
- }
2561
- return this;
2562
- }
2563
-
2564
- lastChar() {
2565
- if (this.outro.length) return this.outro[this.outro.length - 1];
2566
- let chunk = this.lastChunk;
2567
- do {
2568
- if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
2569
- if (chunk.content.length) return chunk.content[chunk.content.length - 1];
2570
- if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
2571
- } while ((chunk = chunk.previous));
2572
- if (this.intro.length) return this.intro[this.intro.length - 1];
2573
- return '';
2574
- }
2575
-
2576
- lastLine() {
2577
- let lineIndex = this.outro.lastIndexOf(n);
2578
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
2579
- let lineStr = this.outro;
2580
- let chunk = this.lastChunk;
2581
- do {
2582
- if (chunk.outro.length > 0) {
2583
- lineIndex = chunk.outro.lastIndexOf(n);
2584
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
2585
- lineStr = chunk.outro + lineStr;
2586
- }
2587
-
2588
- if (chunk.content.length > 0) {
2589
- lineIndex = chunk.content.lastIndexOf(n);
2590
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
2591
- lineStr = chunk.content + lineStr;
2592
- }
2593
-
2594
- if (chunk.intro.length > 0) {
2595
- lineIndex = chunk.intro.lastIndexOf(n);
2596
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
2597
- lineStr = chunk.intro + lineStr;
2598
- }
2599
- } while ((chunk = chunk.previous));
2600
- lineIndex = this.intro.lastIndexOf(n);
2601
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
2602
- return this.intro + lineStr;
2603
- }
2604
-
2605
- slice(start = 0, end = this.original.length - this.offset) {
2606
- start = start + this.offset;
2607
- end = end + this.offset;
2608
-
2609
- if (this.original.length !== 0) {
2610
- while (start < 0) start += this.original.length;
2611
- while (end < 0) end += this.original.length;
2612
- }
2613
-
2614
- let result = '';
2615
-
2616
- // find start chunk
2617
- let chunk = this.firstChunk;
2618
- while (chunk && (chunk.start > start || chunk.end <= start)) {
2619
- // found end chunk before start
2620
- if (chunk.start < end && chunk.end >= end) {
2621
- return result;
2622
- }
2623
-
2624
- chunk = chunk.next;
2625
- }
2626
-
2627
- if (chunk && chunk.edited && chunk.start !== start)
2628
- throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
2629
-
2630
- const startChunk = chunk;
2631
- while (chunk) {
2632
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
2633
- result += chunk.intro;
2634
- }
2635
-
2636
- const containsEnd = chunk.start < end && chunk.end >= end;
2637
- if (containsEnd && chunk.edited && chunk.end !== end)
2638
- throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
2639
-
2640
- const sliceStart = startChunk === chunk ? start - chunk.start : 0;
2641
- const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
2642
-
2643
- result += chunk.content.slice(sliceStart, sliceEnd);
2644
-
2645
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
2646
- result += chunk.outro;
2647
- }
2648
-
2649
- if (containsEnd) {
2650
- break;
2651
- }
2652
-
2653
- chunk = chunk.next;
2654
- }
2655
-
2656
- return result;
2657
- }
2658
-
2659
- // TODO deprecate this? not really very useful
2660
- snip(start, end) {
2661
- const clone = this.clone();
2662
- clone.remove(0, start);
2663
- clone.remove(end, clone.original.length);
2664
-
2665
- return clone;
2666
- }
2667
-
2668
- _split(index) {
2669
- if (this.byStart[index] || this.byEnd[index]) return;
2670
-
2671
- let chunk = this.lastSearchedChunk;
2672
- let previousChunk = chunk;
2673
- const searchForward = index > chunk.end;
2674
-
2675
- while (chunk) {
2676
- if (chunk.contains(index)) return this._splitChunk(chunk, index);
2677
-
2678
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
2679
-
2680
- // Prevent infinite loop (e.g. via empty chunks, where start === end)
2681
- if (chunk === previousChunk) return;
2682
-
2683
- previousChunk = chunk;
2684
- }
2685
- }
2686
-
2687
- _splitChunk(chunk, index) {
2688
- if (chunk.edited && chunk.content.length) {
2689
- // zero-length edited chunks are a special case (overlapping replacements)
2690
- const loc = getLocator(this.original)(index);
2691
- throw new Error(
2692
- `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
2693
- );
2694
- }
2695
-
2696
- const newChunk = chunk.split(index);
2697
-
2698
- this.byEnd[index] = chunk;
2699
- this.byStart[index] = newChunk;
2700
- this.byEnd[newChunk.end] = newChunk;
2701
-
2702
- if (chunk === this.lastChunk) this.lastChunk = newChunk;
2703
-
2704
- this.lastSearchedChunk = chunk;
2705
- return true;
2706
- }
2707
-
2708
- toString() {
2709
- let str = this.intro;
2710
-
2711
- let chunk = this.firstChunk;
2712
- while (chunk) {
2713
- str += chunk.toString();
2714
- chunk = chunk.next;
2715
- }
2716
-
2717
- return str + this.outro;
2718
- }
2719
-
2720
- isEmpty() {
2721
- let chunk = this.firstChunk;
2722
- do {
2723
- if (
2724
- (chunk.intro.length && chunk.intro.trim()) ||
2725
- (chunk.content.length && chunk.content.trim()) ||
2726
- (chunk.outro.length && chunk.outro.trim())
2727
- )
2728
- return false;
2729
- } while ((chunk = chunk.next));
2730
- return true;
2731
- }
2732
-
2733
- length() {
2734
- let chunk = this.firstChunk;
2735
- let length = 0;
2736
- do {
2737
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
2738
- } while ((chunk = chunk.next));
2739
- return length;
2740
- }
2741
-
2742
- trimLines() {
2743
- return this.trim('[\\r\\n]');
2744
- }
2745
-
2746
- trim(charType) {
2747
- return this.trimStart(charType).trimEnd(charType);
2748
- }
2749
-
2750
- trimEndAborted(charType) {
2751
- const rx = new RegExp((charType || '\\s') + '+$');
2752
-
2753
- this.outro = this.outro.replace(rx, '');
2754
- if (this.outro.length) return true;
2755
-
2756
- let chunk = this.lastChunk;
2757
-
2758
- do {
2759
- const end = chunk.end;
2760
- const aborted = chunk.trimEnd(rx);
2761
-
2762
- // if chunk was trimmed, we have a new lastChunk
2763
- if (chunk.end !== end) {
2764
- if (this.lastChunk === chunk) {
2765
- this.lastChunk = chunk.next;
2766
- }
2767
-
2768
- this.byEnd[chunk.end] = chunk;
2769
- this.byStart[chunk.next.start] = chunk.next;
2770
- this.byEnd[chunk.next.end] = chunk.next;
2771
- }
2772
-
2773
- if (aborted) return true;
2774
- chunk = chunk.previous;
2775
- } while (chunk);
2776
-
2777
- return false;
2778
- }
2779
-
2780
- trimEnd(charType) {
2781
- this.trimEndAborted(charType);
2782
- return this;
2783
- }
2784
- trimStartAborted(charType) {
2785
- const rx = new RegExp('^' + (charType || '\\s') + '+');
2786
-
2787
- this.intro = this.intro.replace(rx, '');
2788
- if (this.intro.length) return true;
2789
-
2790
- let chunk = this.firstChunk;
2791
-
2792
- do {
2793
- const end = chunk.end;
2794
- const aborted = chunk.trimStart(rx);
2795
-
2796
- if (chunk.end !== end) {
2797
- // special case...
2798
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
2799
-
2800
- this.byEnd[chunk.end] = chunk;
2801
- this.byStart[chunk.next.start] = chunk.next;
2802
- this.byEnd[chunk.next.end] = chunk.next;
2803
- }
2804
-
2805
- if (aborted) return true;
2806
- chunk = chunk.next;
2807
- } while (chunk);
2808
-
2809
- return false;
2810
- }
2811
-
2812
- trimStart(charType) {
2813
- this.trimStartAborted(charType);
2814
- return this;
2815
- }
2816
-
2817
- hasChanged() {
2818
- return this.original !== this.toString();
2819
- }
2820
-
2821
- _replaceRegexp(searchValue, replacement) {
2822
- function getReplacement(match, str) {
2823
- if (typeof replacement === 'string') {
2824
- return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
2825
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
2826
- if (i === '$') return '$';
2827
- if (i === '&') return match[0];
2828
- const num = +i;
2829
- if (num < match.length) return match[+i];
2830
- return `$${i}`;
2831
- });
2832
- } else {
2833
- return replacement(...match, match.index, str, match.groups);
2834
- }
2835
- }
2836
- function matchAll(re, str) {
2837
- let match;
2838
- const matches = [];
2839
- while ((match = re.exec(str))) {
2840
- matches.push(match);
2841
- }
2842
- return matches;
2843
- }
2844
- if (searchValue.global) {
2845
- const matches = matchAll(searchValue, this.original);
2846
- matches.forEach((match) => {
2847
- if (match.index != null) {
2848
- const replacement = getReplacement(match, this.original);
2849
- if (replacement !== match[0]) {
2850
- this.overwrite(match.index, match.index + match[0].length, replacement);
2851
- }
2852
- }
2853
- });
2854
- } else {
2855
- const match = this.original.match(searchValue);
2856
- if (match && match.index != null) {
2857
- const replacement = getReplacement(match, this.original);
2858
- if (replacement !== match[0]) {
2859
- this.overwrite(match.index, match.index + match[0].length, replacement);
2860
- }
2861
- }
2862
- }
2863
- return this;
2864
- }
2865
-
2866
- _replaceString(string, replacement) {
2867
- const { original } = this;
2868
- const index = original.indexOf(string);
2869
-
2870
- if (index !== -1) {
2871
- if (typeof replacement === 'function') {
2872
- replacement = replacement(string, index, original);
2873
- }
2874
- if (string !== replacement) {
2875
- this.overwrite(index, index + string.length, replacement);
2876
- }
2877
- }
2878
-
2879
- return this;
2880
- }
2881
-
2882
- replace(searchValue, replacement) {
2883
- if (typeof searchValue === 'string') {
2884
- return this._replaceString(searchValue, replacement);
2885
- }
2886
-
2887
- return this._replaceRegexp(searchValue, replacement);
2888
- }
2889
-
2890
- _replaceAllString(string, replacement) {
2891
- const { original } = this;
2892
- const stringLength = string.length;
2893
- for (
2894
- let index = original.indexOf(string);
2895
- index !== -1;
2896
- index = original.indexOf(string, index + stringLength)
2897
- ) {
2898
- const previous = original.slice(index, index + stringLength);
2899
- let _replacement = replacement;
2900
- if (typeof replacement === 'function') {
2901
- _replacement = replacement(previous, index, original);
2902
- }
2903
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
2904
- }
2905
-
2906
- return this;
2907
- }
2908
-
2909
- replaceAll(searchValue, replacement) {
2910
- if (typeof searchValue === 'string') {
2911
- return this._replaceAllString(searchValue, replacement);
2912
- }
2913
-
2914
- if (!searchValue.global) {
2915
- throw new TypeError(
2916
- 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
2917
- );
2918
- }
2919
-
2920
- return this._replaceRegexp(searchValue, replacement);
2921
- }
1759
+ async function transform(code, cache, id, context, opt) {
1760
+ const scriptTag = code.raw.find(node => {
1761
+ return node.name == "script";
1762
+ });
1763
+ if (!scriptTag)
1764
+ throw new Error("[transform check]: not found mcx script tag");
1765
+ const transformContext = {
1766
+ rollupContext: context,
1767
+ impAST: [],
1768
+ currentAST: t.program([]),
1769
+ opt,
1770
+ currentId: id,
1771
+ compiledCode: code,
1772
+ cache,
1773
+ scriptTag: scriptTag,
1774
+ mainFn: {
1775
+ param: [],
1776
+ body: []
1777
+ }
1778
+ };
1779
+ return await _transform(transformContext);
2922
1780
  }
2923
1781
 
2924
- const cache = new Map();
2925
1782
  function mcxPlugn(opt) {
1783
+ let cache = new Map();
2926
1784
  return {
2927
1785
  name: "mbler-mcx-core",
2928
1786
  async resolveId(id, imp) {
2929
1787
  const i = path.parse(id);
1788
+ // if is not a file path
2930
1789
  if (!i.root && !i.dir.startsWith(".")) {
1790
+ // read module package.json
2931
1791
  const d = path.join(opt.moduleDir, id);
2932
1792
  let pkgJson;
2933
1793
  try {
@@ -2963,21 +1823,27 @@ function mcxPlugn(opt) {
2963
1823
  if (err instanceof CompileError) {
2964
1824
  const error = err;
2965
1825
  this.error(error.message, {
2966
- column: error.loc.pos,
1826
+ column: error.loc.column,
2967
1827
  line: error.loc.line,
2968
1828
  });
2969
1829
  }
2970
- this.error(err.message);
2971
- return;
1830
+ this.error(String(err));
2972
1831
  }
2973
1832
  compileData.setFilePath(id);
1833
+ const compiledCode = await transform(compileData, cache, id, this, opt);
2974
1834
  return {
2975
- code: await transform(compileData, cache, id, this, opt),
1835
+ code: compiledCode,
2976
1836
  map: magic.generateMap({ hires: true, source: id }),
2977
1837
  };
2978
1838
  }
2979
1839
  return null;
2980
1840
  },
1841
+ buildEnd() {
1842
+ cache.clear();
1843
+ },
1844
+ buildStart() {
1845
+ cache = new Map();
1846
+ }
2981
1847
  };
2982
1848
  }
2983
1849
  function AbsoluteJoin(base, dir) {
@@ -3044,19 +1910,12 @@ var types = /*#__PURE__*/Object.freeze({
3044
1910
  __proto__: null
3045
1911
  });
3046
1912
 
3047
- var index = {
3048
- load: CompileMcxDir,
3049
- AST: AST,
3050
- Compiler,
3051
- utils: McxUtlis,
3052
- transform
3053
- };
3054
-
3055
- exports.AST = AST;
3056
- exports.Compiler = Compiler;
1913
+ exports.AST = index$2;
1914
+ exports.Compiler = index$1;
3057
1915
  exports.PUBTYPE = types;
3058
1916
  exports.compile = CompileMcxDir;
3059
- exports.default = index;
1917
+ exports.compile_component = index;
1918
+ exports.plugin = mcxPlugn;
3060
1919
  exports.transform = transform;
3061
1920
  exports.utils = McxUtlis;
3062
1921
  //# sourceMappingURL=index.js.map