useblocks-cli 1.1.84 → 1.1.85-dev.10
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/README.md +1 -1
- package/dist/index.js +131 -96
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -16,7 +16,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
@@ -51,8 +51,8 @@ var ROOT_DIR$2 = (0, path.resolve)(__dirname, "../../..");
|
|
|
51
51
|
(0, path.resolve)(ROOT_DIR$2, "./packages");
|
|
52
52
|
(0, path.resolve)(ROOT_DIR$2, "./local_modules");
|
|
53
53
|
(0, path.resolve)(ROOT_DIR$2, "./build");
|
|
54
|
-
(0, path.resolve)(ROOT_DIR$2, "index.html"), (0, path.resolve)(ROOT_DIR$2, "src/index.tsx"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/loader/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/core/entry.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/po/index.ts"), (0, path.resolve)(ROOT_DIR$2, "iframe"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe.html"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe-eblock.html"), (0, path.resolve)(ROOT_DIR$2, "public"), (0, path.resolve)(ROOT_DIR$2, "src/pluginExamples"), (0, path.resolve)(ROOT_DIR$2, "src/extensions"), (0, path.resolve)(ROOT_DIR$2, "src/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "tsconfig.types.json"), (0, path.resolve)(ROOT_DIR$2, "src"), (0, path.resolve)(ROOT_DIR$2, "iframe/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "src/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/extensions/react/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/assets/images/atoms"), (0, path.resolve)(ROOT_DIR$2, "src/assets"), (0, path.resolve)(ROOT_DIR$2, "src"), (0, path.resolve)(ROOT_DIR$2, "
|
|
55
|
-
(0, path.resolve)(ROOT_DIR$2, "apps/widget/saas/index.tsx"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/entries/loader.ts"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/entries/core.ts"), (0, path.resolve)(ROOT_DIR$2, "iframe"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe.html"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe-eblock.html"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/public"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/pluginExamples"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/extensions"), (0, path.resolve)(ROOT_DIR$2, "apps/widget"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget"), (0, path.resolve)(ROOT_DIR$2, "iframe/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/src/assets"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/src")
|
|
54
|
+
(0, path.resolve)(ROOT_DIR$2, "index.html"), (0, path.resolve)(ROOT_DIR$2, "src/index.tsx"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/loader/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/core/entry.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/po/index.ts"), (0, path.resolve)(ROOT_DIR$2, "iframe"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe.html"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe-eblock.html"), (0, path.resolve)(ROOT_DIR$2, "public"), (0, path.resolve)(ROOT_DIR$2, "src/pluginExamples"), (0, path.resolve)(ROOT_DIR$2, "src/extensions"), (0, path.resolve)(ROOT_DIR$2, "src/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "tsconfig.types.json"), (0, path.resolve)(ROOT_DIR$2, "src"), (0, path.resolve)(ROOT_DIR$2, "iframe/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "src/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/extensions/react/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "src/assets/images/atoms"), (0, path.resolve)(ROOT_DIR$2, "src/assets"), (0, path.resolve)(ROOT_DIR$2, "src"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/const"), (0, path.resolve)(ROOT_DIR$2, "src/helpers/guid"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/utils/waitForElement"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/mixins/auth"), (0, path.resolve)(ROOT_DIR$2, "src/plugin/mixins/base");
|
|
55
|
+
(0, path.resolve)(ROOT_DIR$2, "apps/widget/saas/index.tsx"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/entries/loader.ts"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/entries/core.ts"), (0, path.resolve)(ROOT_DIR$2, "iframe"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe.html"), (0, path.resolve)(ROOT_DIR$2, "iframe/iframe-eblock.html"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/public"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/pluginExamples"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/extensions"), (0, path.resolve)(ROOT_DIR$2, "apps/widget"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/lib/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget"), (0, path.resolve)(ROOT_DIR$2, "iframe/tsconfig.json"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/src/assets"), (0, path.resolve)(ROOT_DIR$2, "apps/widget/src");
|
|
56
56
|
(0, path.resolve)(ROOT_DIR$2, "iframe/js/extensions/api/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/ui-kit/src"), (0, path.resolve)(ROOT_DIR$2, "packages/ui-kit/src/index.ts"), (0, path.resolve)(ROOT_DIR$2, "packages/ui-kit/public"), (0, path.resolve)(ROOT_DIR$2, "build-tools/config/runtime"), (0, path.resolve)(ROOT_DIR$2, "packages/core-loader/src"), (0, path.resolve)(ROOT_DIR$2, "build-tools/plugins/loaders/loaders/amd-loader.js");
|
|
57
57
|
path.default.resolve(__dirname, "../../..");
|
|
58
58
|
path.default.resolve(__dirname, "../../versions.json");
|
|
@@ -323,11 +323,13 @@ var DEFAULT_UI_TEXT = {
|
|
|
323
323
|
nextStepStart: "Start the project:",
|
|
324
324
|
nextStepStartDebug: "Start the debug mode:",
|
|
325
325
|
nextStepStartRelease: "Run the production-like check:",
|
|
326
|
+
nextStepStartProduction: "Run the full production check:",
|
|
326
327
|
promptInstallDependencies: "Install dependencies now?",
|
|
327
328
|
promptStartMode: "Which start mode should be used?",
|
|
328
329
|
promptStartModeSkip: "Do not start now",
|
|
329
330
|
promptStartModeDebug: "Development mode (debug host + sandbox watcher)",
|
|
330
331
|
promptStartModeRelease: "Production-like check (build + host using built assets)",
|
|
332
|
+
promptStartModeProduction: "Full production (both the plugin and the host are built)",
|
|
331
333
|
promptStandStartModeDebug: "Development (dev server, /api proxy, live reload)",
|
|
332
334
|
promptStandStartModeRelease: "Production-like (build + static server)",
|
|
333
335
|
promptStandStartModeRepro: "Repro: rebundle + cross-origin chunks",
|
|
@@ -420,9 +422,9 @@ var DEFAULT_EXTENSIONS_API_PACKAGE = "useblocks-extensions-api";
|
|
|
420
422
|
var DEFAULT_EXTENSIONS_REACT_PACKAGE = "useblocks-extensions-react";
|
|
421
423
|
var DEFAULT_EXTENSIONS_SANDBOX_PACKAGE = "useblocks-extensions-sandbox";
|
|
422
424
|
var DEFAULT_CLI_PACKAGE = "useblocks-cli";
|
|
423
|
-
var DEFAULT_VERSION = "1.1.
|
|
424
|
-
var DEFAULT_UI_KIT_VERSION = "1.1.
|
|
425
|
-
var DEFAULT_CLI_VERSION = "1.1.
|
|
425
|
+
var DEFAULT_VERSION = "1.1.85-dev.10";
|
|
426
|
+
var DEFAULT_UI_KIT_VERSION = "1.1.85-dev.10";
|
|
427
|
+
var DEFAULT_CLI_VERSION = "1.1.85-dev.10";
|
|
426
428
|
var DEFAULT_OPENAPI_BASE_URL = "https://app.useblocks.io/api";
|
|
427
429
|
var DEFAULT_CDN_URL = "https://cdn.useblocks.io";
|
|
428
430
|
var DEFAULT_BACKEND_DOMAIN = "api.useblocks.io";
|
|
@@ -1455,21 +1457,20 @@ var ROOT_PKG = {
|
|
|
1455
1457
|
"build-tools/cli",
|
|
1456
1458
|
"build-tools/bundler-plugins",
|
|
1457
1459
|
"build-tools/translations",
|
|
1458
|
-
"local_modules/monaco"
|
|
1459
|
-
"local_modules/pixie"
|
|
1460
|
+
"local_modules/monaco"
|
|
1460
1461
|
],
|
|
1461
1462
|
files: ["build/"],
|
|
1462
1463
|
main: "build/plugin.js",
|
|
1463
1464
|
engines: { "node": ">=24.0.0" },
|
|
1464
1465
|
packageManager: "pnpm@11.4.0",
|
|
1465
1466
|
dependencies: {
|
|
1467
|
+
"@ant-design/icons": "^6.1.0",
|
|
1468
|
+
"@babel/runtime": "^7.26.0",
|
|
1466
1469
|
"@easylogic/colorpicker": "1.10.7",
|
|
1467
|
-
"@emailmaker/filemanager": "workspace:*",
|
|
1468
|
-
"@emailmaker/ui-kit": "workspace:*",
|
|
1469
1470
|
"@emailmaker/extensions-api": "workspace:*",
|
|
1470
1471
|
"@emailmaker/extensions-react": "workspace:*",
|
|
1471
|
-
"@
|
|
1472
|
-
"@
|
|
1472
|
+
"@emailmaker/filemanager": "workspace:*",
|
|
1473
|
+
"@emailmaker/ui-kit": "workspace:*",
|
|
1473
1474
|
"@internal/core-loader": "workspace:*",
|
|
1474
1475
|
"app-core": "workspace:*",
|
|
1475
1476
|
"browserExtensionSanitizer": "workspace:*",
|
|
@@ -1500,7 +1501,7 @@ var ROOT_PKG = {
|
|
|
1500
1501
|
"@react-hook/window-size": "^3.0.7",
|
|
1501
1502
|
"@react-oauth/google": "^0.12.1",
|
|
1502
1503
|
"@reduxjs/toolkit": "^2.12.0",
|
|
1503
|
-
"@sentry/browser": "^
|
|
1504
|
+
"@sentry/browser": "^10.56.0",
|
|
1504
1505
|
"@sentry/cli": "^2.58.2",
|
|
1505
1506
|
"@sentry/react": "^10.18.0",
|
|
1506
1507
|
"@sentry/tracing": "^7.120.3",
|
|
@@ -1510,7 +1511,7 @@ var ROOT_PKG = {
|
|
|
1510
1511
|
"@types/js-cookie": "^3.0.6",
|
|
1511
1512
|
"@wordpress/i18n": "^4.58.0",
|
|
1512
1513
|
"@wordpress/react-i18n": "^3.15.0",
|
|
1513
|
-
"antd": "
|
|
1514
|
+
"antd": "6.3.5",
|
|
1514
1515
|
"autoprefixer": "10.4.5",
|
|
1515
1516
|
"axios": "^1.7.9",
|
|
1516
1517
|
"browser-image-compression": "^2.0.2",
|
|
@@ -1521,8 +1522,9 @@ var ROOT_PKG = {
|
|
|
1521
1522
|
"darkreader": "4.9.125",
|
|
1522
1523
|
"date-fns": "^2.27.0",
|
|
1523
1524
|
"dayjs": "^1.11.8",
|
|
1524
|
-
"deepmerge-ts": "^5.1.0",
|
|
1525
1525
|
"deepmerge": "^4.3.1",
|
|
1526
|
+
"deepmerge-ts": "^5.1.0",
|
|
1527
|
+
"documentCore": "workspace:*",
|
|
1526
1528
|
"effection": "^3.0.3",
|
|
1527
1529
|
"emmet": "^2.3.6",
|
|
1528
1530
|
"emmet-monaco-es": "file:local_modules/emmet-monaco-es",
|
|
@@ -1536,6 +1538,7 @@ var ROOT_PKG = {
|
|
|
1536
1538
|
"immer": "^11.1.11",
|
|
1537
1539
|
"js-cookie": "^3.0.1",
|
|
1538
1540
|
"js-sha256": "^0.11.0",
|
|
1541
|
+
"konva": "9.3.18",
|
|
1539
1542
|
"lodash.isequal": "^4.5.0",
|
|
1540
1543
|
"mailparser": "^3.6.9",
|
|
1541
1544
|
"md5": "^2.3.0",
|
|
@@ -1545,14 +1548,16 @@ var ROOT_PKG = {
|
|
|
1545
1548
|
"monaco-html-linter": "^1.0.4",
|
|
1546
1549
|
"mutation-summary": "^1.0.0",
|
|
1547
1550
|
"path-browserify": "^1.0.1",
|
|
1548
|
-
"pixie": "file:local_modules/pixie",
|
|
1549
1551
|
"postal-mime": "^3.0.0",
|
|
1552
|
+
"source": "workspace:*",
|
|
1550
1553
|
"process": "^0.11.10",
|
|
1551
1554
|
"prop-types": "^15.8.1",
|
|
1555
|
+
"rc-input-number": "^9.5.0",
|
|
1552
1556
|
"react": "19.2.7",
|
|
1553
1557
|
"react-dom": "19.2.7",
|
|
1558
|
+
"react-filerobot-image-editor": "5.0.0-beta.159",
|
|
1554
1559
|
"react-infinite-scroll-component": "^7.2.1",
|
|
1555
|
-
"
|
|
1560
|
+
"react-konva": "19.2.5",
|
|
1556
1561
|
"react-masonry-css": "^1.0.16",
|
|
1557
1562
|
"react-redux": "^7.2.3",
|
|
1558
1563
|
"react-refresh": "^0.18.0",
|
|
@@ -1560,15 +1565,16 @@ var ROOT_PKG = {
|
|
|
1560
1565
|
"react-split": "^2.0.13",
|
|
1561
1566
|
"react-sticky-box": "^1.0.1",
|
|
1562
1567
|
"react-transition-group": "^4.4.5",
|
|
1563
|
-
"regenerator-runtime": "^0.14.1",
|
|
1564
1568
|
"recharts": "^2.15.4",
|
|
1569
|
+
"regenerator-runtime": "^0.14.1",
|
|
1565
1570
|
"sass": "^1.44.0",
|
|
1566
1571
|
"save": "^2.9.0",
|
|
1567
1572
|
"selderee": "^0.11.0",
|
|
1568
1573
|
"sortablejs": "^1.15.2",
|
|
1569
1574
|
"stream-browserify": "^3.0.0",
|
|
1575
|
+
"styled-components": "^6.1.13",
|
|
1576
|
+
"textChange": "workspace:*",
|
|
1570
1577
|
"util": "^0.12.5",
|
|
1571
|
-
"uuid": "^13.0.0",
|
|
1572
1578
|
"vscode-html-languageservice": "^5.0.2",
|
|
1573
1579
|
"webfontloader": "^1.6.28",
|
|
1574
1580
|
"xss": "^1.0.14",
|
|
@@ -1581,6 +1587,7 @@ var ROOT_PKG = {
|
|
|
1581
1587
|
"build:global": "tsx build-tools/pipeline.ts --envMode=global",
|
|
1582
1588
|
"preview": "vite preview --config build-tools/config/presets/build.main.ts --mode production",
|
|
1583
1589
|
"build:cli": "tsx build-tools/cli/scripts/build.ts",
|
|
1590
|
+
"cli:local": "node build/cli/bin/createPlugin.js --local-test --local-build-dir ./build",
|
|
1584
1591
|
"emailmaker-cli": "node build/cli/bin/createPlugin.js --local-test --local-build-dir ./build",
|
|
1585
1592
|
"verify:cli": "tsx build-tools/cli/scripts/e2e/verify-global-cli.ts --cli-dir=build/cli",
|
|
1586
1593
|
"verify:cli:source": "tsx build-tools/cli/scripts/e2e/verify-global-cli.ts --source-tools",
|
|
@@ -1601,6 +1608,8 @@ var ROOT_PKG = {
|
|
|
1601
1608
|
"publish:npm": "node build-tools/scripts/publish/publish-from-manifest.mjs",
|
|
1602
1609
|
"publish:plan": "tsx build-tools/scripts/publish/publish-plan.ts",
|
|
1603
1610
|
"build:translations": "tsx build-tools/translations/extract.ts",
|
|
1611
|
+
"delivery:groups": "tsx build-tools/scripts/build/update-delivery-groups.ts",
|
|
1612
|
+
"measure:delivery": "vite build --config build-tools/config/presets/build.ui-kit-host.ts --mode production && vite build --config build-tools/config/presets/build.core.ts --mode production && vite build --config build-tools/config/presets/delivery.split.ts --mode production",
|
|
1604
1613
|
"build:bundler-plugins": "tsx build-tools/scripts/build/bundler-plugins.ts --build-dir build --mode dev",
|
|
1605
1614
|
"send:translations": "tsx build-tools/scripts/i18n/send-translations.ts",
|
|
1606
1615
|
"start:proxy": "env-cmd -f .env.dev tsx build-tools/proxy/client/server.ts --mountPath=/proxy",
|
|
@@ -1635,6 +1644,7 @@ var ROOT_PKG = {
|
|
|
1635
1644
|
"lint:types": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsc --noEmit && tsc -p build-tools/tsconfig.tooling.json",
|
|
1636
1645
|
"test:typecheck": "npm run lint:types && tsc -p iframe/tsconfig.json --noEmit && tsc -p packages/po/tsconfig.json --noEmit",
|
|
1637
1646
|
"type-check:tooling": "tsc -p build-tools/tsconfig.tooling.json",
|
|
1647
|
+
"diag:measure": "tsx build-tools/scripts/diagnostics/measure.ts",
|
|
1638
1648
|
"lint:new": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
|
|
1639
1649
|
"test:plugin-matrix": "tsx build-tools/scripts/dev/run-plugin-matrix.ts",
|
|
1640
1650
|
"lint:ci": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
|
|
@@ -1644,7 +1654,8 @@ var ROOT_PKG = {
|
|
|
1644
1654
|
"sentry:sourcemaps-dev": "sentry-cli sourcemaps inject --org sentry --project emailmaker-dev ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project emailmaker-dev ./build",
|
|
1645
1655
|
"sentry:sourcemaps-prod": "sentry-cli sourcemaps inject --org sentry --project emailmaker-prod ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project emailmaker-prod ./build",
|
|
1646
1656
|
"sentry:sourcemaps-bl-dev": "sentry-cli sourcemaps inject --org sentry --project blocks-dev ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project blocks-dev ./build",
|
|
1647
|
-
"sentry:sourcemaps-bl-prod": "sentry-cli sourcemaps inject --org sentry --project blocks-prod ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project blocks-prod ./build"
|
|
1657
|
+
"sentry:sourcemaps-bl-prod": "sentry-cli sourcemaps inject --org sentry --project blocks-prod ./build && sentry-cli --url https://sentry.emcdn.ru/ sourcemaps upload --org sentry --project blocks-prod ./build",
|
|
1658
|
+
"saas-check": "tsx build-tools/scripts/saas-check/run.ts"
|
|
1648
1659
|
},
|
|
1649
1660
|
browserslist: {
|
|
1650
1661
|
"production": [
|
|
@@ -1683,9 +1694,11 @@ var ROOT_PKG = {
|
|
|
1683
1694
|
"@vitejs/plugin-react": "^6.0.2",
|
|
1684
1695
|
"allure-jest": "^3.5.0",
|
|
1685
1696
|
"babel-preset-react-app": "^10.1.0",
|
|
1697
|
+
"cjs-module-lexer": "2.2.0",
|
|
1686
1698
|
"cross-env": "^7.0.3",
|
|
1687
1699
|
"dotenv": "^17.3.1",
|
|
1688
1700
|
"ejs": "^5.0.1",
|
|
1701
|
+
"enhanced-resolve": "^5.23.0",
|
|
1689
1702
|
"env-cmd": "^10.1.0",
|
|
1690
1703
|
"eslint-plugin-sonarjs": "^3.0.1",
|
|
1691
1704
|
"express": "^5.2.1",
|
|
@@ -1698,6 +1711,7 @@ var ROOT_PKG = {
|
|
|
1698
1711
|
"jest-junit": "^16.0.0",
|
|
1699
1712
|
"jsdom": "^16.7.0",
|
|
1700
1713
|
"less": "^4.1.3",
|
|
1714
|
+
"line-awesome": "^1.3.0",
|
|
1701
1715
|
"napi-postinstall": "^0.3.4",
|
|
1702
1716
|
"oxlint": "1.77.0",
|
|
1703
1717
|
"oxlint-tsgolint": "7.0.2001",
|
|
@@ -1707,7 +1721,7 @@ var ROOT_PKG = {
|
|
|
1707
1721
|
"postcss-preset-env": "^9.5.0",
|
|
1708
1722
|
"prettier": "^3.4.2",
|
|
1709
1723
|
"react-error-overlay": "6.0.9",
|
|
1710
|
-
"rolldown": "~1.
|
|
1724
|
+
"rolldown": "~1.2.6",
|
|
1711
1725
|
"rolldown-plugin-dts": "^0.28.0",
|
|
1712
1726
|
"rollup": "^4.61.1",
|
|
1713
1727
|
"sass-cast": "^0.5.6",
|
|
@@ -1726,7 +1740,7 @@ var ROOT_PKG = {
|
|
|
1726
1740
|
"tsdown": "^0.21.0-beta.2",
|
|
1727
1741
|
"tsx": "^4.21.0",
|
|
1728
1742
|
"typescript": "^7.0.2",
|
|
1729
|
-
"vite": "^8.
|
|
1743
|
+
"vite": "^8.3.0",
|
|
1730
1744
|
"vite-plugin-commonjs": "^0.10.4",
|
|
1731
1745
|
"vite-plugin-css-injected-by-js": "^4.0.1",
|
|
1732
1746
|
"vite-plugin-monaco-editor": "^1.1.0",
|
|
@@ -1737,7 +1751,7 @@ var ROOT_PKG = {
|
|
|
1737
1751
|
"yargs": "^17.5.1"
|
|
1738
1752
|
},
|
|
1739
1753
|
overrides: {
|
|
1740
|
-
"rolldown": "~1.
|
|
1754
|
+
"rolldown": "~1.2.6",
|
|
1741
1755
|
"monaco-html-linter": { "monaco-editor": "0.34.0" },
|
|
1742
1756
|
"@vitest/expect": "4.1.4",
|
|
1743
1757
|
"@vitest/runner": "4.1.4",
|
|
@@ -1809,6 +1823,7 @@ var LEGACY_REACT_DEPENDENCIES = {
|
|
|
1809
1823
|
react: extractPinned(getRootDependencyVersion("react")),
|
|
1810
1824
|
"react-dom": extractPinned(getRootDependencyVersion("react-dom")),
|
|
1811
1825
|
antd: extractPinned(getRootDependencyVersion("antd")),
|
|
1826
|
+
"@ant-design/icons": extractPinned(getRootDependencyVersion("@ant-design/icons")),
|
|
1812
1827
|
"@types/react": extractPinned(getRootDependencyVersion("@types/react")),
|
|
1813
1828
|
"@types/react-dom": extractPinned(getRootDependencyVersion("@types/react-dom"))
|
|
1814
1829
|
};
|
|
@@ -1993,14 +2008,21 @@ e({
|
|
|
1993
2008
|
name: "antd",
|
|
1994
2009
|
exportName: "Antd",
|
|
1995
2010
|
hasDefault: false,
|
|
1996
|
-
isCjs:
|
|
2011
|
+
isCjs: false,
|
|
2012
|
+
isLocalWorkspace: false
|
|
2013
|
+
}), e({
|
|
2014
|
+
name: "@ant-design/icons/es/components/AntdIcon",
|
|
2015
|
+
exportName: "AntDesignIconBase",
|
|
2016
|
+
hasDefault: true,
|
|
2017
|
+
isCjs: false,
|
|
1997
2018
|
isLocalWorkspace: false
|
|
1998
2019
|
}), e({
|
|
1999
2020
|
name: "@ant-design/icons",
|
|
2000
2021
|
exportName: "AntDesignIcons",
|
|
2001
2022
|
hasDefault: true,
|
|
2002
2023
|
isCjs: false,
|
|
2003
|
-
isLocalWorkspace: false
|
|
2024
|
+
isLocalWorkspace: false,
|
|
2025
|
+
delivery: "compat-lazy"
|
|
2004
2026
|
}), e({
|
|
2005
2027
|
name: "@ant-design/cssinjs",
|
|
2006
2028
|
exportName: "AntDesignCssinjs",
|
|
@@ -2020,12 +2042,6 @@ e({
|
|
|
2020
2042
|
hasDefault: true,
|
|
2021
2043
|
isCjs: true,
|
|
2022
2044
|
isLocalWorkspace: false
|
|
2023
|
-
}), e({
|
|
2024
|
-
name: "uuid",
|
|
2025
|
-
exportName: "Uuid",
|
|
2026
|
-
hasDefault: false,
|
|
2027
|
-
isCjs: false,
|
|
2028
|
-
isLocalWorkspace: false
|
|
2029
2045
|
}), e({
|
|
2030
2046
|
name: "di",
|
|
2031
2047
|
exportName: "Di",
|
|
@@ -2658,7 +2674,7 @@ var MESSAGES = {
|
|
|
2658
2674
|
"readmeStand.modeAdvancedUmd": "advanced: UMD from page script",
|
|
2659
2675
|
"readmeStand.modeAdvancedMemoryUsage": "advanced: memory usage test",
|
|
2660
2676
|
"readmeStand.modeAdvancedModuleFederation": "advanced: Module Federation host + remote",
|
|
2661
|
-
"readmeStand.moduleFederationHint": "## Module Federation stand (local CLI only)\n\nCross-origin: host `http://localhost:3000`, remote/CDN `http://localhost:3001/remoteEntry.js`. Editor `publicPath` points to port 3001.\n\nOpen `http://localhost:3000/`.\n\n`npm start`: remote `vite build --watch` + preview on :3001, host Vite dev on :3000. First remote build takes a few seconds; host starts after `remoteEntry.js` is ready.",
|
|
2677
|
+
"readmeStand.moduleFederationHint": "## Module Federation stand (local CLI only)\n\nCross-origin: host `http://localhost:3000`, remote/CDN `http://localhost:3001/remoteEntry.js`. Editor `publicPath` points to port 3001.\n\nOpen `http://localhost:3000/`.\n\n`npm start`: remote `vite build --watch` + preview on :3001, host Vite dev on :3000. First remote build takes a few seconds; host starts after `remoteEntry.js` is ready.\n\nOther ports: `PLUGIN_DEV_PORT=4000 npm start` puts the host on 4000 and the remote on 4001 (`npm start -- --port` does not reach `concurrently` children).",
|
|
2662
2678
|
"readmeStand.whatIncluded": "## What is included",
|
|
2663
2679
|
"readmeStand.simpleProject": "- simple project with {title} connected",
|
|
2664
2680
|
"readmeStand.storageProvider": "- StorageProvider with pathMode - files are stored in `./storage`",
|
|
@@ -2781,7 +2797,7 @@ function buildViteStandScripts(options) {
|
|
|
2781
2797
|
const remotePreviewOnly = `vite preview ${remoteConfigFlag}`;
|
|
2782
2798
|
const hostPreviewOnly = `vite preview ${configFlag}`;
|
|
2783
2799
|
return {
|
|
2784
|
-
start: `${concurrently} -n remote-build,remote,host "${`vite build --watch ${remoteConfigFlag}`}" "${`wait-on dist/remote/remoteEntry.js -t 120000 && vite preview ${remoteConfigFlag}`}" "
|
|
2800
|
+
start: `${concurrently} -n remote-build,remote,host "${`vite build --watch ${remoteConfigFlag}`}" "${`wait-on dist/remote/remoteEntry.js -t 120000 && vite preview ${remoteConfigFlag}`}" "vite ${configFlag}"`,
|
|
2785
2801
|
build: `vite build ${remoteConfigFlag} && vite build ${configFlag}`,
|
|
2786
2802
|
preview: `${remoteDistGuard} && ${distGuard} && ${concurrently} -n remote,host "${remotePreviewOnly}" "${hostPreviewOnly}"`,
|
|
2787
2803
|
"serve:dist": `${remoteDistGuard} && ${distGuard} && ${concurrently} -n remote,host "${remotePreviewOnly}" "${hostPreviewOnly}"`
|
|
@@ -3413,6 +3429,7 @@ function buildStandEtaContext(templateOptions) {
|
|
|
3413
3429
|
standShowSubpathBanner: standMode === "advanced" && advancedProfile === "subpath",
|
|
3414
3430
|
standViteOutputFolder: computeStandViteOutputFolder(templateOptions),
|
|
3415
3431
|
includeSmokeHelpers: Boolean(templateOptions.localTest),
|
|
3432
|
+
standCdnUrl: packageConfig.cdnUrl || "",
|
|
3416
3433
|
standAngular: isAngularStand,
|
|
3417
3434
|
...standMode === "angular-esbuild" || standMode === "angular" ? {
|
|
3418
3435
|
standAngularProductAssetsOutput: `${STAND_ANGULAR_ESBUILD_PRODUCT_PATH_PREFIX}/${appNameSlug}/`,
|
|
@@ -3535,6 +3552,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3535
3552
|
"../../project-templates/plugin/shared-base/scripts/dev-runner.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ChildProcess } from 'node:child_process';\nimport { runScript, runScriptSync } from './runScript.ts';\nimport { resolvePluginDevHostArgs } from './resolvePluginDevPort.ts';\n\nfunction waitForFile(filePath: string, timeoutMs = 30_000, pollMs = 250): Promise<void> {\n const startedAt = Date.now();\n\n return new Promise((resolve, reject) => {\n const check = (): void => {\n if (fs.existsSync(filePath)) {\n resolve();\n return;\n }\n\n if (Date.now() - startedAt >= timeoutMs) {\n reject(new Error(`Timed out waiting for file: ${filePath}`));\n return;\n }\n\n setTimeout(check, pollMs);\n };\n\n check();\n });\n}\n\nfunction hasLegacyPluginDevScripts(): boolean {\n try {\n const packageJsonPath = path.resolve(process.cwd(), 'package.json');\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as {\n scripts?: Record<string, string>;\n };\n return typeof packageJson.scripts?.['dev:plugin:once'] === 'string';\n } catch {\n return false;\n }\n}\n\nasync function main(): Promise<void> {\n const forwardedArgs = process.argv.slice(2);\n const sandboxFilePath = path.resolve(process.cwd(), 'public', 'sandbox.js');\n const pluginDistPath = path.resolve(process.cwd(), 'dist', 'index.js');\n let sandbox: ChildProcess | undefined;\n let plugin: ChildProcess | undefined;\n let app: ChildProcess | undefined;\n\n const shutdown = (): void => {\n sandbox?.kill('SIGINT');\n plugin?.kill('SIGINT');\n app?.kill('SIGINT');\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n try {\n runScriptSync('dev:sandbox:once');\n await waitForFile(sandboxFilePath, 5_000);\n\n if (hasLegacyPluginDevScripts()) {\n runScriptSync('dev:plugin:once');\n await waitForFile(pluginDistPath, 60_000);\n plugin = runScript('dev:plugin');\n }\n\n sandbox = runScript('dev:sandbox');\n const { port, hostArgs } = await resolvePluginDevHostArgs(forwardedArgs);\n console.log(`[dev] http://localhost:${port}/`);\n app = runScript('dev:host', {\n args: hostArgs,\n env: { PLUGIN_DEV_PORT: String(port) },\n });\n } catch (error) {\n shutdown();\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n }\n}\n\nvoid main();\n",
|
|
3536
3553
|
"../../project-templates/plugin/shared-base/scripts/findFreePort.ts": "import net from 'node:net';\n\n/**\n * Hosts a dev server may bind to. `::` comes first: on Windows a second bind to an IPv4\n * address of a busy port still succeeds, so only the IPv6 socket reports the conflict.\n */\nconst DEV_BIND_HOSTS: readonly string[] = ['::', '0.0.0.0', '127.0.0.1'];\n\n/** The port cannot be bound on this host: taken by another process or denied by the OS. */\nconst PORT_UNAVAILABLE_CODES = new Set(['EADDRINUSE', 'EACCES']);\n\n/** The address family is unavailable (no IPv6 and such) — says nothing about the port, so skip the host. */\nconst HOST_UNSUPPORTED_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EINVAL', 'ENOTFOUND']);\n\nexport const DEFAULT_PLUGIN_DEV_PORT = 3000;\n\ntype PortProbeResult = 'free' | 'taken' | 'host-unsupported';\n\n/**\n * Tries to bind the port on one host. An unknown error code counts as unusable:\n * moving to the next port is cheaper than crashing the dev server on EADDRINUSE.\n */\nfunction probePort(port: number, host: string): Promise<PortProbeResult> {\n return new Promise((resolve) => {\n const server = net.createServer();\n\n server.once('error', (err: NodeJS.ErrnoException) => {\n const code = err.code ?? '';\n if (HOST_UNSUPPORTED_CODES.has(code)) {\n resolve('host-unsupported');\n return;\n }\n if (!PORT_UNAVAILABLE_CODES.has(code)) {\n console.log(`[findFreePort] ${host}:${port} — unexpected bind error (${code || err.message})`);\n }\n resolve('taken');\n });\n\n server.once('listening', () => {\n server.close(() => resolve('free'));\n });\n\n server.listen({ port, host, exclusive: true });\n });\n}\n\nexport async function isDevListenPortTaken(port: number): Promise<boolean> {\n for (const host of DEV_BIND_HOSTS) {\n if ((await probePort(port, host)) === 'taken') {\n return true;\n }\n }\n return false;\n}\n\nexport async function findFreePort(\n startPort: number,\n maxAttempts = 50,\n): Promise<number | null> {\n for (let i = 0; i < maxAttempts; i++) {\n const port = startPort + i;\n if (!(await isDevListenPortTaken(port))) {\n return port;\n }\n console.log(`[findFreePort] Port ${port} is in use, trying ${port + 1}...`);\n }\n return null;\n}\n",
|
|
3537
3554
|
"../../project-templates/plugin/shared-base/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
|
|
3555
|
+
"../../project-templates/plugin/shared-base/scripts/production-runner.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport { buildProject } from './build-runner.ts';\nimport { runScript, runScriptSync } from './runScript.ts';\nimport { resolvePluginDevHostArgs } from './resolvePluginDevPort.ts';\n\n/**\n * Third mode: both the plugin and the host are built, nothing is served from sources.\n *\n * `start:release` builds the plugin but still runs a dev server for the host, and a dev server\n * hands every dependency to the bundler's optimizer — it bundles each one whole and deliberately\n * skips tree shaking. Weights and request counts seen there describe the optimizer, not the\n * delivered result. This mode is the one to judge them by.\n */\nfunction assertArtifacts(files: readonly string[], label: string): void {\n for (const filePath of files) {\n if (!fs.existsSync(filePath)) {\n throw new Error(`[production] Expected ${label} artifact is missing: ${filePath}`);\n }\n }\n}\n\n/**\n * `--bundler-runtime-strict` — same contract as in `release-runner.ts`: the flag is set only by a\n * local CLI build and must not reach vite/webpack.\n */\nfunction consumeStrictFlag(args: string[]): string[] {\n const idx = args.indexOf('--bundler-runtime-strict');\n if (idx < 0) {\n return args;\n }\n process.env.BUNDLER_RUNTIME_STRICT ??= '1';\n return [...args.slice(0, idx), ...args.slice(idx + 1)];\n}\n\n/**\n * The built plugin next to the built host.\n *\n * `release.html` loads the plugin from `/dist/index.js`. A dev server maps that path to the\n * project folder; a preview server serves only what the host build emitted, so the plugin has to\n * be copied in or the page 404s on its own entry.\n */\nfunction publishPluginDist(): void {\n const from = path.resolve(process.cwd(), 'dist');\n const to = path.resolve(process.cwd(), 'dist-host', 'dist');\n fs.rmSync(to, { recursive: true, force: true });\n fs.cpSync(from, to, { recursive: true });\n}\n\nasync function main(): Promise<void> {\n const forwardedArgs = consumeStrictFlag(process.argv.slice(2));\n\n buildProject();\n assertArtifacts(\n [path.resolve(process.cwd(), 'dist', 'index.js'), path.resolve(process.cwd(), 'dist', 'sandbox.js')],\n 'plugin',\n );\n\n runScriptSync('build:release-host');\n publishPluginDist();\n\n try {\n const { port, hostArgs } = await resolvePluginDevHostArgs(forwardedArgs);\n console.log(`[production] http://localhost:${port}/release.html`);\n const app = runScript('preview:release-host', {\n args: hostArgs,\n env: { PLUGIN_DEV_PORT: String(port) },\n });\n\n const shutdown = (): void => {\n app.kill('SIGINT');\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n }\n}\n\nvoid main();\n",
|
|
3538
3556
|
"../../project-templates/plugin/shared-base/scripts/release-runner.ts": "import fs from 'node:fs';\nimport path from 'node:path';\nimport { buildProject } from './build-runner.ts';\nimport { runScript } from './runScript.ts';\nimport { resolvePluginDevHostArgs } from './resolvePluginDevPort.ts';\n\nfunction assertReleaseArtifacts(): void {\n const requiredFiles = [\n path.resolve(process.cwd(), 'dist', 'index.js'),\n path.resolve(process.cwd(), 'dist', 'sandbox.js'),\n ];\n\n for (const filePath of requiredFiles) {\n if (!fs.existsSync(filePath)) {\n throw new Error(`[release] Expected build artifact is missing: ${filePath}`);\n }\n }\n}\n\n/**\n * `--bundler-runtime-strict` — CLI выставляет этот флаг только при локальной\n * сборке плагина из нашего репо (`--local-test`). Переключает defensive\n * детекторы host plugin + PluginDev в throw-режим: дублирование React'а или\n * bare-импорт runtime-пакета валит сборку с диагностикой вместо тихого warn'а.\n *\n * Production-CLI (опубликованный npm) этот аргумент не подставляет, поэтому\n * integrator'ские sandbox'ы не падают из-за heuristic-сигнала. См.\n * `docs/build-architecture/RUNTIME_DELIVERY_CR.md` §12.\n */\nfunction consumeStrictFlag(args: string[]): string[] {\n const idx = args.indexOf('--bundler-runtime-strict');\n if (idx < 0) {\n return args;\n }\n process.env.BUNDLER_RUNTIME_STRICT ??= '1';\n return [...args.slice(0, idx), ...args.slice(idx + 1)];\n}\n\nasync function main(): Promise<void> {\n const forwardedArgs = consumeStrictFlag(process.argv.slice(2));\n buildProject();\n assertReleaseArtifacts();\n if (process.env.BUNDLER_RUNTIME_STRICT === '1') {\n console.log('[release] BUNDLER_RUNTIME_STRICT=1 (local CLI build) — defensive checks fail-fast');\n }\n\n try {\n const { port, hostArgs } = await resolvePluginDevHostArgs(forwardedArgs);\n console.log(`[release] http://localhost:${port}/release.html`);\n const app = runScript('dev:release-host', {\n args: hostArgs,\n env: { PLUGIN_DEV_PORT: String(port) },\n });\n\n const shutdown = (): void => {\n app.kill('SIGINT');\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(message);\n process.exit(1);\n }\n}\n\nvoid main();\n",
|
|
3539
3557
|
"../../project-templates/plugin/shared-base/scripts/resolvePluginDevPort.test.ts": "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { parsePortFromArgs } from './resolvePluginDevPort.ts';\n\ntest('parsePortFromArgs extracts --port and keeps other args', () => {\n assert.deepEqual(parsePortFromArgs(['--port', '3005', '--open']), {\n explicitPort: 3005,\n restArgs: ['--open'],\n });\n});\n\ntest('parsePortFromArgs supports --port= syntax', () => {\n assert.deepEqual(parsePortFromArgs(['--port=3010']), {\n explicitPort: 3010,\n restArgs: [],\n });\n});\n\ntest('parsePortFromArgs rejects invalid port', () => {\n assert.throws(() => parsePortFromArgs(['--port', '0']), /Invalid --port value/);\n});\n",
|
|
3540
3558
|
"../../project-templates/plugin/shared-base/scripts/resolvePluginDevPort.ts": "import { DEFAULT_PLUGIN_DEV_PORT, findFreePort, isDevListenPortTaken } from './findFreePort.ts';\n\nexport function parsePortFromArgs(args: string[]): {\n explicitPort?: number;\n restArgs: string[];\n} {\n const restArgs: string[] = [];\n let explicitPort: number | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n\n if (arg === '--') {\n continue;\n }\n\n if (arg === '--port') {\n const value = args[i + 1];\n if (value === undefined) {\n throw new Error('Missing value for --port');\n }\n explicitPort = Number(value);\n i += 1;\n continue;\n }\n\n if (arg.startsWith('--port=')) {\n explicitPort = Number(arg.slice('--port='.length));\n continue;\n }\n\n restArgs.push(arg);\n }\n\n if (explicitPort !== undefined && (!Number.isInteger(explicitPort) || explicitPort <= 0)) {\n throw new Error(`Invalid --port value: ${explicitPort}`);\n }\n\n return { explicitPort, restArgs };\n}\n\nexport async function resolvePluginDevHostArgs(\n forwardedArgs: string[],\n options: { defaultPort?: number } = {},\n): Promise<{ port: number; hostArgs: string[] }> {\n const defaultPort = options.defaultPort ?? DEFAULT_PLUGIN_DEV_PORT;\n const { explicitPort, restArgs } = parsePortFromArgs(forwardedArgs);\n const envPortRaw = process.env.PLUGIN_DEV_PORT;\n const envPort = envPortRaw ? Number(envPortRaw) : undefined;\n\n let port: number;\n if (explicitPort !== undefined) {\n if (await isDevListenPortTaken(explicitPort)) {\n throw new Error(\n `Port ${explicitPort} is already in use. Omit --port to auto-select a free port, or choose another value.`,\n );\n }\n port = explicitPort;\n } else if (envPort !== undefined && Number.isInteger(envPort) && envPort > 0) {\n if (await isDevListenPortTaken(envPort)) {\n throw new Error(\n `Port ${envPort} is already in use. Omit --port to auto-select a free port, or choose another value.`,\n );\n }\n port = envPort;\n } else {\n const freePort = await findFreePort(defaultPort);\n if (freePort === null) {\n throw new Error(`Could not find free port starting from ${defaultPort}`);\n }\n port = freePort;\n }\n\n return {\n port,\n hostArgs: [...restArgs, '--port', String(port)],\n };\n}\n",
|
|
@@ -3557,7 +3575,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3557
3575
|
"../../project-templates/plugin/templating/src/app/__PLUGIN_CLASS_NAME__.tsx.eta": "import { pluginRegistry, createComponentIdentifier } from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport { ComponentRegistry } from '<%= it.packageConfig.extensionsReactPackageName %>';\nimport type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Options } from '../public-types';\nimport {\n <%= it.pluginClassName %>TemplateDataPanel,\n type <%= it.pluginClassName %>TemplateDataPanelProps,\n} from './ui/<%= it.pluginClassName %>Panel';\nimport {\n OPEN_TEMPLATE_DATA_PANEL_MESSAGE,\n PREVIEW_STATES,\n TEMPLATE_DATA_MESSAGE,\n TEMPLATE_DATA_META_KEY,\n TWIG_RUNTIME_URL,\n clonePreviewData,\n type PreviewTemplateData,\n} from '../interfaces';\n\nconst <%= it.pluginClassName %>TemplateDataPanelId =\n createComponentIdentifier<<%= it.pluginClassName %>TemplateDataPanelProps>('<%= it.pluginClassName %>TemplateDataPanel');\n\nComponentRegistry.add(<%= it.pluginClassName %>TemplateDataPanelId, <%= it.pluginClassName %>TemplateDataPanel);\n\nfunction normalizePublicPath(value?: string): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const trimmed = value.replace(/\\/+$/, '');\n return `${trimmed}/`;\n}\n\nconst AUTO_PUBLIC_PATH = (() => {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const currentScript = document.currentScript as HTMLScriptElement | null;\n if (!currentScript?.src) {\n return undefined;\n }\n\n return normalizePublicPath(currentScript.src.replace(/[^/]*$/, ''));\n})();\n\nfunction getDefaultPreviewData(): PreviewTemplateData {\n return clonePreviewData(PREVIEW_STATES[0]?.data ?? {});\n}\n\nexport class <%= it.pluginClassName %> implements IPlugin {\n private _previewData: PreviewTemplateData = getDefaultPreviewData();\n private _matcherReadyPromise: Promise<void> = Promise.resolve();\n private readonly _disposables: Array<{ dispose(): void }> = [];\n private _settingsPanel?: { showSettingsPanel?: (options: unknown) => void };\n\n constructor(\n private readonly _editor: Instance,\n private readonly _options: <%= it.pluginClassName %>Options = {},\n ) {}\n\n init() {\n const sandboxApi = this._editor.use('SandboxScriptApi');\n const settingsPanel = this._editor.use('SettingsPanelApi');\n const messageService = this._editor.use('MessageService');\n this._settingsPanel = settingsPanel;\n\n const publicPath = normalizePublicPath(this._options.publicPath) || AUTO_PUBLIC_PATH;\n const twigRuntimeHandle = sandboxApi.registerSandboxScript(TWIG_RUNTIME_URL);\n\n if (publicPath) {\n this._matcherReadyPromise = twigRuntimeHandle.ready\n .then(() => sandboxApi.registerSandboxScript(publicPath + 'sandbox.js').ready)\n .then(() => undefined);\n } else {\n this._matcherReadyPromise = twigRuntimeHandle.ready.then(() => undefined);\n }\n\n this._trackDisposable(messageService.addListener(OPEN_TEMPLATE_DATA_PANEL_MESSAGE, () => {\n this._openTemplateDataPanel(this._settingsPanel);\n }));\n\n this._trackDisposable(this._editor.handleEmailInit?.((email) => {\n void this._hydratePreviewData(email);\n }));\n }\n\n afterInit() {\n void this._hydratePreviewData();\n }\n\n dispose() {\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n\n private _trackDisposable(value: { dispose(): void } | (() => void) | void) {\n if (!value) {\n return;\n }\n\n if (typeof value === 'function') {\n this._disposables.push({ dispose: value });\n return;\n }\n\n if (typeof value.dispose === 'function') {\n this._disposables.push(value);\n }\n }\n\n private _readPreviewDataFromEmail(email: unknown): PreviewTemplateData {\n const emailMeta = (email as { meta?: Record<string, unknown> } | undefined)?.meta;\n const storedData = emailMeta?.[TEMPLATE_DATA_META_KEY];\n if (storedData && typeof storedData === 'object') {\n return clonePreviewData(storedData as PreviewTemplateData);\n }\n\n return getDefaultPreviewData();\n }\n\n private async _hydratePreviewData(email?: unknown) {\n const sourceEmail = email ?? await this._editor.getEmail?.();\n this._previewData = this._readPreviewDataFromEmail(sourceEmail);\n await this._sendPreviewData();\n }\n\n private _persistPreviewData(nextData: PreviewTemplateData) {\n this._previewData = clonePreviewData(nextData);\n this._editor.setEmailMeta?.({\n [TEMPLATE_DATA_META_KEY]: clonePreviewData(nextData),\n });\n }\n\n private _openTemplateDataPanel(settingsPanel: { showSettingsPanel?: (options: unknown) => void } | undefined) {\n if (!settingsPanel || typeof settingsPanel.showSettingsPanel !== 'function') {\n return;\n }\n\n settingsPanel.showSettingsPanel({\n caption: 'Template data JSON',\n deletable: false,\n content: {\n type: <%= it.pluginClassName %>TemplateDataPanelId,\n props: {\n initialValue: JSON.stringify(this._previewData ?? {}, null, 2),\n onValidJson: (nextData) => {\n this._persistPreviewData(nextData);\n void this._sendPreviewData();\n },\n },\n },\n });\n }\n\n private async _sendPreviewData() {\n const messageService = this._editor.use('MessageService');\n await this._matcherReadyPromise;\n messageService.send(TEMPLATE_DATA_MESSAGE, this._previewData);\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
|
|
3558
3576
|
"../../project-templates/plugin/templating/src/app/ui/__PLUGIN_PANEL_CLASS_NAME__.tsx.eta": "import React, { useEffect, useState } from 'react';\nimport type { PreviewTemplateData } from '../../interfaces';\n\nexport interface <%= it.pluginClassName %>TemplateDataPanelProps {\n initialValue: string;\n onValidJson?(value: PreviewTemplateData): void;\n}\n\nexport function <%= it.pluginClassName %>TemplateDataPanel({\n initialValue,\n onValidJson,\n}: <%= it.pluginClassName %>TemplateDataPanelProps) {\n const [value, setValue] = useState(initialValue);\n const [status, setStatus] = useState('Valid JSON applies automatically to the preview.');\n const [statusColor, setStatusColor] = useState('#64748b');\n\n useEffect(() => {\n setValue(initialValue);\n setStatus('Valid JSON applies automatically to the preview.');\n setStatusColor('#64748b');\n }, [initialValue]);\n\n useEffect(() => {\n const timer = window.setTimeout(() => {\n try {\n onValidJson?.(JSON.parse(value) as PreviewTemplateData);\n setStatus('Preview updated from sidebar JSON.');\n setStatusColor('#15803d');\n } catch (error) {\n setStatus(`JSON error: ${String(error instanceof Error ? error.message : error)}`);\n setStatusColor('#b91c1c');\n }\n }, 250);\n\n return () => {\n window.clearTimeout(timer);\n };\n }, [onValidJson, value]);\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', height: '100%', padding: '16px', boxSizing: 'border-box' }}>\n <div style={{ font: '13px/1.5 Arial,sans-serif', color: '#475569' }}>\n Edit template data as raw JSON. Valid JSON applies to the Twig preview automatically.\n </div>\n <textarea\n spellCheck={false}\n wrap=\"off\"\n value={value}\n onChange={(event) => {\n setStatus('Validating JSON...');\n setStatusColor('#64748b');\n setValue(event.target.value);\n }}\n style={{\n width: '100%',\n minHeight: '320px',\n flex: 1,\n padding: '12px',\n border: '1px solid #cbd5e1',\n borderRadius: '8px',\n background: '#0f172a',\n color: '#e2e8f0',\n font: '13px/1.5 Consolas, Monaco, monospace',\n resize: 'vertical',\n boxSizing: 'border-box',\n }}\n />\n <div style={{ font: '12px/1.5 Arial,sans-serif', color: statusColor, whiteSpace: 'pre-wrap' }}>\n {status}\n </div>\n </div>\n );\n}\n",
|
|
3559
3577
|
"../../project-templates/plugin/templating/src/dev/editorConfig.ts.eta": "import type { Config } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config } from '../public-types';\n\nconst mergeTagItems = [\n {\n label: 'System',\n value: 'system',\n children: [\n { label: 'Additional field \"Name\"', value: 'Name' },\n { label: 'Recipient name', value: 'ToName' },\n ],\n },\n];\n\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'en_US',\n historyEnabled: true,\n commonStylesEnabled: true,\n previewIconEnabled: true,\n previewModeEnabled: true,\n livePreviewEnabled: true,\n sendTestEnabled: false,\n emailExportEnabled: false,\n sharePreviewEnabled: false,\n codeModeDirection: 'bottom',\n codeMode: 'true',\n mergeTagsShow: true,\n mergeTags: {\n syntax: ['{{' + '%value%' + '}}'],\n items: mergeTagItems,\n },\n} satisfies Partial<Config & <%= it.pluginClassName %>Config>;\n\nexport function createEditorConfig(): Partial<Config> {\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n",
|
|
3560
|
-
"../../project-templates/plugin/templating/src/dev/hostApp.tsx.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\nimport { TWIG_EMAIL_CODE } from '../interfaces';\n\
|
|
3578
|
+
"../../project-templates/plugin/templating/src/dev/hostApp.tsx.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\nimport { TWIG_EMAIL_CODE } from '../interfaces';\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-templating',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: TWIG_EMAIL_CODE,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ margin: '12px 0', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n {/* The editor fills its container: without a definite height the side panels shrink to their content. */}\n <div id=\"editor-root\" style={{ height: '100vh' }} />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
|
|
3561
3579
|
"../../project-templates/plugin/templating/src/interfaces/index.ts.eta": "export interface PreviewTemplateData {\n product?: {\n title?: string;\n sku?: string;\n cards?: Array<{\n title?: string;\n price?: string;\n badge?: string;\n }>;\n };\n}\n\nexport interface PreviewState {\n label: string;\n data: PreviewTemplateData;\n}\n\nexport const TWIG_RUNTIME_URL = 'https://cdn.jsdelivr.net/npm/twig@3.0.0/twig.min.js';\nexport const TEMPLATE_DATA_MESSAGE = 'templating:preview-data';\nexport const OPEN_TEMPLATE_DATA_PANEL_MESSAGE = 'templating:open-panel';\nexport const TEMPLATE_DATA_META_KEY = 'templatingPreviewData';\nexport const TEMPLATE_DATA_PREVIEW_ATTRIBUTE = 'data-em-templating-preview';\n\nexport const PREVIEW_STATES: PreviewState[] = [\n {\n label: 'Featured products',\n data: {\n product: {\n title: 'Featured products for Alice',\n sku: 'SKU-ALPHA-001',\n cards: [\n { title: 'Starter pack', price: '$29', badge: 'Popular' },\n { title: 'Growth pack', price: '$79', badge: 'Best value' },\n ],\n },\n },\n },\n {\n label: 'Empty catalog',\n data: {\n product: {\n title: 'Recommended products for Bob',\n sku: 'SKU-BETA-002',\n cards: [],\n },\n },\n },\n];\n\nexport const TWIG_EMAIL_CODE = `<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <title>Twig matcher demo</title>\n </head>\n <body style=\"margin:0;padding:24px;font-family:Arial,sans-serif;background:#f8fafc;\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n <tr>\n <td align=\"center\">\n <table role=\"presentation\" width=\"640\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"background:#ffffff;border-radius:16px;overflow:hidden;\">\n <tr>\n <td style=\"padding:32px;\">\n <h1 style=\"margin:0 0 16px;\">{{ product.title }}</h1>\n {# sandbox matcher should replace this comment with preview html #}\n {% if product.cards is not empty %}\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"margin:16px 0 0;\">\n <tr>\n {% for card in product.cards %}\n <td style=\"width:50%;padding:8px;vertical-align:top;\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"border:1px solid #dbe4f0;border-radius:12px;background:#f8fafc;\">\n <tr>\n <td style=\"padding:16px;\">\n <div style=\"font-size:12px;line-height:16px;color:#475569;text-transform:uppercase;\">{{ card.badge }}</div>\n <div style=\"margin-top:8px;font-size:18px;line-height:24px;color:#0f172a;font-weight:bold;\">{{ card.title }}</div>\n <div style=\"margin-top:8px;font-size:14px;line-height:20px;color:#2563eb;\">{{ card.price }}</div>\n </td>\n </tr>\n </table>\n </td>\n {% endfor %}\n </tr>\n </table>\n {% endif %}\n <p style=\"margin:16px 0 0;color:#475569;\">SKU: {{ product.sku }}</p>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </body>\n</html>`;\n\nexport function clonePreviewData<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n",
|
|
3562
3580
|
"../../project-templates/plugin/templating/src/sandbox/index.ts.eta": "import { App } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport {\n OPEN_TEMPLATE_DATA_PANEL_MESSAGE,\n TEMPLATE_DATA_MESSAGE,\n TEMPLATE_DATA_PREVIEW_ATTRIBUTE,\n type PreviewTemplateData,\n} from '../interfaces';\n\ntype Disposable = { dispose(): void };\ntype MatcherRange = { start: number; end: number };\ntype MatcherMapping = {\n registerMatcherPair(config: {\n syntax?: string;\n escape: {\n match(text: string): MatcherRange[];\n mapFn(text: string): string | false;\n overrideBuiltins?: boolean;\n };\n unescape: {\n match(text: string): MatcherRange[];\n mapFn(text: string): string | false;\n overrideBuiltins?: boolean;\n };\n }): Disposable;\n rebuildFromBase?(): void;\n};\n\nclass <%= it.pluginClassName %>Sandbox implements IPlugin {\n private _previewData: PreviewTemplateData = {};\n private readonly _disposables: Disposable[] = [];\n private _messageService?: { send(message: string, data?: unknown): void; addListener(message: string, listener: (value: PreviewTemplateData) => void): Disposable };\n\n init() {\n const mapping = App.use('Mapping') as MatcherMapping | undefined;\n const messageService = App.use('MessageService');\n this._messageService = messageService;\n\n if (!mapping || typeof mapping.registerMatcherPair !== 'function') {\n console.warn('[<%= it.pluginClassName %>Sandbox] Mapping.registerMatcherPair is unavailable');\n return;\n }\n\n const registration = mapping.registerMatcherPair({\n syntax: 'twig-preview',\n escape: {\n match: (text) => this._findTwigRanges(text),\n mapFn: (text) => this._renderTwigSource(text),\n overrideBuiltins: true,\n },\n unescape: {\n match: (text) => this._findPreviewRanges(text),\n mapFn: (text) => this._restoreTwigSource(text),\n overrideBuiltins: true,\n },\n });\n\n this._disposables.push(\n registration,\n {\n dispose: this._bindPreviewClickHandler(),\n },\n messageService.addListener(TEMPLATE_DATA_MESSAGE, (nextPreviewData: PreviewTemplateData) => {\n this._previewData = nextPreviewData || {};\n mapping.rebuildFromBase?.();\n }),\n );\n }\n\n dispose() {\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n\n private _encodeSource(source: string): string {\n const bytes = new TextEncoder().encode(source);\n let binary = '';\n bytes.forEach((byte) => {\n binary += String.fromCharCode(byte);\n });\n return btoa(binary);\n }\n\n private _decodeSource(encodedSource: string): string {\n const binary = atob(encodedSource);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return new TextDecoder().decode(bytes);\n }\n\n private _collectMatches(text: string, patterns: RegExp[]): MatcherRange[] {\n const ranges: MatcherRange[] = [];\n patterns.forEach((pattern) => {\n pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(text)) !== null) {\n ranges.push({\n start: match.index,\n end: match.index + match[0].length,\n });\n }\n });\n ranges.sort((first, second) => first.start - second.start || first.end - second.end);\n return ranges;\n }\n\n private _isIntersectRange(first: MatcherRange, second: MatcherRange): boolean {\n return first.start < second.end && second.start < first.end;\n }\n\n private _mergeRanges(ranges: MatcherRange[]): MatcherRange[] {\n const sorted = ranges.slice().sort((first, second) => first.start - second.start || first.end - second.end);\n const merged: MatcherRange[] = [];\n sorted.forEach((range) => {\n const previous = merged[merged.length - 1];\n if (previous && range.start < previous.end) {\n previous.end = Math.max(previous.end, range.end);\n return;\n }\n merged.push({ start: range.start, end: range.end });\n });\n return merged;\n }\n\n private _findBlockTwigRanges(text: string): MatcherRange[] {\n const ranges: MatcherRange[] = [];\n const stack: Array<{ type: 'if' | 'for'; start: number }> = [];\n const tokenPattern = /\\{%\\s*(if|for|endif|endfor)\\b[\\s\\S]*?%\\}/g;\n const validStartPositions = new Set<number>();\n let match: RegExpExecArray | null;\n\n while ((match = tokenPattern.exec(text)) !== null) {\n const keyword = match[1];\n const tokenEnd = match.index + match[0].length;\n if (keyword === 'if' || keyword === 'for') {\n validStartPositions.add(match.index);\n stack.push({ type: keyword, start: match.index });\n continue;\n }\n\n const startType = keyword === 'endif' ? 'if' : 'for';\n for (let index = stack.length - 1; index >= 0; index -= 1) {\n if (stack[index].type === startType) {\n const start = stack[index].start;\n stack.splice(index);\n ranges.push({ start, end: tokenEnd });\n break;\n }\n }\n }\n\n stack.forEach((entry) => {\n ranges.push({ start: entry.start, end: text.length });\n });\n\n const rawStartPattern = /\\{%\\s*(if|for)\\b/g;\n while ((match = rawStartPattern.exec(text)) !== null) {\n if (!validStartPositions.has(match.index) && !ranges.some((range) => match.index >= range.start && match.index < range.end)) {\n ranges.push({ start: match.index, end: text.length });\n }\n }\n\n return this._mergeRanges(ranges);\n }\n\n private _findInlineTwigRanges(text: string): MatcherRange[] {\n const ranges = this._collectMatches(text, [\n /\\{\\{[\\s\\S]*?\\}\\}/g,\n /\\{#[\\s\\S]*?#\\}/g,\n ]);\n const rawStartPattern = /\\{\\{|\\{#/g;\n let match: RegExpExecArray | null;\n\n while ((match = rawStartPattern.exec(text)) !== null) {\n if (!ranges.some((range) => match.index >= range.start && match.index < range.end)) {\n ranges.push({ start: match.index, end: text.length });\n }\n }\n\n return this._mergeRanges(ranges);\n }\n\n private _findTwigRanges(text: string): MatcherRange[] {\n const blockRanges = this._findBlockTwigRanges(text);\n const inlineRanges = this._findInlineTwigRanges(text)\n .filter((range) => !blockRanges.some((blockRange) => this._isIntersectRange(blockRange, range)));\n\n return [...blockRanges, ...inlineRanges].sort((first, second) => first.start - second.start || first.end - second.end);\n }\n\n private _findPreviewRanges(text: string): MatcherRange[] {\n return this._collectMatches(text, [\n /<!--twig-preview-start:[A-Za-z0-9+/=]+-->[\\s\\S]*?<!--twig-preview-end-->/g,\n ]);\n }\n\n private _createPreviewMarkers(source: string, renderedHtml: string): string {\n const encodedSource = this._encodeSource(source);\n return '<!--twig-preview-start:' + encodedSource + '-->' + this._wrapRenderedHtml(source, renderedHtml) + '<!--twig-preview-end-->';\n }\n\n private _createEmptyPreview(source: string): string {\n const encodedSource = this._encodeSource(source);\n return '<!--twig-preview-start:' + encodedSource + '--><!--twig-preview-end-->';\n }\n\n private _renderTwigSource(source: string): string {\n const twigRuntime = (window as Window & { Twig?: { twig?: (options: { data: string; allowInlineIncludes: boolean; autoescape: boolean }) => { render(data: PreviewTemplateData): string } } }).Twig;\n if (!twigRuntime || typeof twigRuntime.twig !== 'function') {\n console.warn('[<%= it.pluginClassName %>Sandbox] Twig runtime is unavailable');\n return this._createEmptyPreview(source);\n }\n\n try {\n const template = twigRuntime.twig({\n data: source,\n allowInlineIncludes: true,\n autoescape: false,\n });\n const rendered = template.render(this._previewData || {});\n return this._createPreviewMarkers(source, rendered);\n } catch (error) {\n console.warn('[<%= it.pluginClassName %>Sandbox] Twig render failed, showing empty preview', error);\n return this._createEmptyPreview(source);\n }\n }\n\n private _restoreTwigSource(previewMarkup: string): string {\n const match = previewMarkup.match(/<!--twig-preview-start:([A-Za-z0-9+/=]+)-->/);\n return match ? this._decodeSource(match[1]) : previewMarkup;\n }\n\n private _wrapRenderedHtml(source: string, renderedHtml: string): string {\n const attribute = TEMPLATE_DATA_PREVIEW_ATTRIBUTE + '=\"1\"';\n const className = 'em-prevent-action';\n const trimmed = renderedHtml.trim();\n const isBlockTwig = source.includes('{%');\n\n if (isBlockTwig) {\n return '<div ' + attribute + ' class=\"' + className + '\" style=\"display:block;cursor:pointer;\">' + renderedHtml + '</div>';\n }\n\n if (trimmed.startsWith('<')) {\n return '<span ' + attribute + ' class=\"' + className + '\" style=\"display:inline-block;cursor:pointer;\">' + renderedHtml + '</span>';\n }\n\n return '<span ' + attribute + ' class=\"' + className + '\" style=\"cursor:pointer;\">' + renderedHtml + '</span>';\n }\n\n private _bindPreviewClickHandler(): () => void {\n const onClick = (event: MouseEvent) => {\n const target = event.target as HTMLElement | null;\n const previewRoot = target?.closest?.('[' + TEMPLATE_DATA_PREVIEW_ATTRIBUTE + ']');\n if (!previewRoot) {\n return;\n }\n\n this._messageService?.send(OPEN_TEMPLATE_DATA_PANEL_MESSAGE);\n };\n\n document.addEventListener('click', onClick);\n return () => {\n document.removeEventListener('click', onClick);\n };\n }\n}\n\nApp.use(<%= it.pluginClassName %>Sandbox);\n",
|
|
3563
3581
|
"../../project-templates/shared/comments/plugin-host-comments.en.ts": "export const pluginHostComments = {\n devHostMode: 'Source-mode host: load the plugin from source and keep dev helpers enabled.',\n releasePackages: 'Keep editor/runtime packages external here so the release host stays on the same DI/runtime contract as the built plugin.',\n releaseOptimizeDeps: 'Do not prebundle these packages in Vite, otherwise the host can evaluate its own runtime copy and duplicate singletons.',\n releaseAlias: 'Point the release smoke test to the built plugin bundle from dist/.',\n apiProxy: 'Proxy local /api calls to the target backend and preserve the expected origin header.',\n releaseEntry: 'Release smoke-test entry: boot the host against built assets from dist/.',\n} as const;\n",
|
|
@@ -3567,34 +3585,34 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3567
3585
|
"../../project-templates/shared/partials/editor-init-smoke.eta": "<% if (it.includeSmokeHelpers) { %>\n<%~ include('editor-init-smoke-helpers', it) %>\n<% } else { %>\nfunction formatEditorInitError(error: unknown): string {\n if (error instanceof Error && error.message) {\n return error.message;\n }\n\n if (typeof error === 'string' && error.trim()) {\n return error.trim();\n }\n\n return 'Unknown editor initialization error.';\n}\n\nfunction reportEditorReady(_meta: unknown, _mountElement?: Element | null): void {}\n\nfunction reportEditorInitError(_meta: unknown, error: unknown, _mountElement?: Element | null): string {\n const message = formatEditorInitError(error);\n console.error('[editor-host] Editor initialization failed', error);\n return message;\n}\n<% } %>\n",
|
|
3568
3586
|
"../../project-templates/shared/partials/plugin-app-advanced.eta": "import { pluginRegistry, createComponentIdentifier } from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport { ComponentRegistry } from '<%= it.packageConfig.extensionsReactPackageName %>';\nimport type { ExportedApi, IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config, <%= it.pluginClassName %>Options } from '../public-types';\nimport type { Group, VisualSettings } from '../interfaces';\nimport { Activate_Product_Settings, Change_Product_Settings } from '../interfaces';\nimport {\n <%= it.pluginClassName %>Icon,\n <%= it.pluginClassName %>SaveForm,\n <%= it.pluginClassName %>SettingsPanel,\n type <%= it.pluginClassName %>SaveFormProps,\n} from './ui/<%= it.pluginClassName %>Panel';\n\ntype DisposableLike = { dispose(): void } | (() => void) | void;\ntype Email = ExportedApi.Email;\ntype ProductBlockConfig = <%~ `NonNullable<${it.pluginClassName}Config['productBlock']>` %>;\ntype ProductBlockGroup = NonNullable<ProductBlockConfig['groups']>[number];\n\nfunction normalizePublicPath(value?: string): string | undefined {\n if (!value) {\n return undefined;\n }\n const trimmed = value.replace(/\\/+$/, '');\n return `${trimmed}/`;\n}\n\nconst AUTO_PUBLIC_PATH = (() => {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const currentScript = document.currentScript as HTMLScriptElement | null;\n if (!currentScript?.src) {\n return undefined;\n }\n\n return normalizePublicPath(currentScript.src.replace(/[^/]*$/, ''));\n})();\n\ninterface SaveParams {\n email: Email;\n content: string;\n format: string;\n}\n\nconst ELEMENT_NAME = <%~ it.literalPluginAppElementTitle %>;\nconst PRODUCT_HTML = <%~ it.productHtmlLiteral %>;\nconst PRODUCT_CARD_CSS = <%~ it.productCardCssLiteral %>;\nconst PRODUCT_CARD_SANDBOX_CSS_KEY = 'product-card-styles';\nconst <%= it.pluginClassName %>IconId = createComponentIdentifier<{ size?: number }>('<%= it.pluginClassName %>Icon');\nconst <%= it.pluginClassName %>SettingsPanelId = createComponentIdentifier<{\n groups: Group[];\n settings: VisualSettings;\n selectedGroup?: string;\n onChange?(group: Group | undefined, settings: VisualSettings): void;\n}>('<%= it.pluginClassName %>SettingsPanel');\nconst <%= it.pluginClassName %>SaveFormId = <%~ `createComponentIdentifier<${it.pluginClassName}SaveFormProps>` %>('<%= it.pluginClassName %>SaveForm');\n\n// Step 0 — register React panel/icon components for ElementsApi and SettingsPanelApi.\nComponentRegistry.add(<%= it.pluginClassName %>IconId, <%= it.pluginClassName %>Icon);\nComponentRegistry.add(<%= it.pluginClassName %>SettingsPanelId, <%= it.pluginClassName %>SettingsPanel);\nComponentRegistry.add(<%= it.pluginClassName %>SaveFormId, <%= it.pluginClassName %>SaveForm);\n\nexport class <%= it.pluginClassName %> implements IPlugin {\n private readonly _disposables: Array<{ dispose(): void }> = [];\n private _groups: ProductBlockGroup[] = [];\n\n constructor(\n private readonly _editor: Instance,\n private readonly _options: <%= it.pluginClassName %>Options = {},\n ) {}\n\n init() {\n // Step 1 — sandbox assets: CSS for the email iframe + sandbox.js (see end of init).\n const sandboxApi = this._editor.use('SandboxScriptApi');\n this._disposables.push(\n sandboxApi.registerSandboxCSSCode(PRODUCT_CARD_SANDBOX_CSS_KEY, PRODUCT_CARD_CSS),\n );\n\n const elementsApi = this._editor.use('ElementsApi');\n const messageService = this._editor.use('MessageService');\n const modalApi = this._editor.use('ModalApi');\n const config = this._editor.getConfig?.() as <%~ `Partial<${it.pluginClassName}Config>` %> | undefined;\n this._groups = config?.productBlock?.groups ?? [];\n\n // Step 2 — sidebar element + listen for clicks from sandbox (Activate_Product_Settings).\n this._disposables.push(\n elementsApi.insert({\n name: ELEMENT_NAME,\n title: ELEMENT_NAME,\n icon: {\n type: <%= it.pluginClassName %>IconId,\n props: { size: 24 },\n },\n className: 'product-atom',\n html: PRODUCT_HTML,\n }),\n messageService.addListener(Activate_Product_Settings, this._handleShowPanel),\n );\n\n // Optional demo — save modal + compileEmail download (not required for the product-card loop).\n this._trackDisposable(this._editor.handleSaveEmail?.((event) => {\n const { value } = event;\n let values: SaveParams = {\n email: value,\n content: value.code ?? '',\n format: 'text',\n };\n\n modalApi.show({\n title: <%~ it.literalPluginAppSaveEmailTitle %>,\n onOk: async () => {\n await this._onSave(values);\n },\n content: {\n type: <%= it.pluginClassName %>SaveFormId,\n props: {\n content: value.code ?? '',\n onChange: (nextValues: Omit<SaveParams, 'email'>) => {\n values = { ...values, ...nextValues };\n },\n },\n },\n });\n }));\n\n this._trackDisposable(this._editor.handleNotify?.((event: { id?: string }) => {\n if (event.id === 'EMAIL_SAVING_SUCCESS') {\n return false;\n }\n return undefined;\n }));\n\n this._trackDisposable(this._editor.handleConfigChanged?.(this._onConfigChanged));\n\n // Step 3 — load sandbox script from plugin publicPath (dev: `/`, release: `/dist/`).\n const publicPath = normalizePublicPath(this._options.publicPath) || AUTO_PUBLIC_PATH;\n if (publicPath) {\n this._disposables.push(\n sandboxApi.registerSandboxScript(publicPath + 'sandbox.js'),\n );\n }\n }\n\n private _trackDisposable(value: DisposableLike) {\n if (!value) {\n return;\n }\n\n if (typeof value === 'function') {\n this._disposables.push({ dispose: value });\n return;\n }\n\n if (typeof value.dispose === 'function') {\n this._disposables.push(value);\n }\n }\n\n private _onConfigChanged = (nextConfig: <%~ `Partial<${it.pluginClassName}Config>` %>) => {\n this._groups = nextConfig.productBlock?.enabled !== false\n ? nextConfig.productBlock?.groups ?? []\n : [];\n };\n\n private async _onSave({ email, content, format }: SaveParams) {\n try {\n if (typeof this._editor.compileEmail !== 'function') {\n throw new Error('compileEmail is not available');\n }\n\n const nextEmail: Email = { ...email, code: content };\n const result = await this._editor.compileEmail(nextEmail, true);\n const compiled = result.compiled;\n\n const lowerFormat = format.toLowerCase();\n let fileContent;\n let fileExtension;\n\n if (lowerFormat === 'amp' && compiled.ampHtml) {\n fileContent = compiled.ampHtml;\n fileExtension = 'html';\n } else if (lowerFormat === 'text' && compiled.text) {\n fileContent = compiled.text;\n fileExtension = 'txt';\n } else if (compiled.html) {\n fileContent = compiled.html;\n fileExtension = 'html';\n } else {\n throw new Error('Unable to resolve compiled email content.');\n }\n\n const blob = new Blob([fileContent], {\n type: fileExtension === 'txt' ? 'text/plain' : 'text/html',\n });\n\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = 'email-' + new Date().toISOString().slice(0, 10) + '.' + fileExtension;\n\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n\n if (typeof this._editor.notify === 'function') {\n this._editor.notify(<%~ it.literalPluginAppSavedSuccessfully %>);\n }\n } catch (error) {\n console.error('[<%= it.pluginClassName %>] Save failed', error);\n }\n }\n\n // Step 4 — open React settings panel; panel changes go back to sandbox via Change_Product_Settings.\n private _handleShowPanel = ({\n groupId,\n visualSettings,\n }: {\n groupId?: string;\n visualSettings: VisualSettings;\n }) => {\n if (!this._groups.length) return;\n const settingsPanel = this._editor.use('SettingsPanelApi');\n settingsPanel.showSettingsPanel({\n content: {\n type: <%= it.pluginClassName %>SettingsPanelId,\n props: {\n groups: this._groups,\n settings: visualSettings,\n selectedGroup: groupId || '',\n onChange: (group, settings) => {\n this._editor.use('MessageService').send(Change_Product_Settings, {\n group,\n visualSettings: settings,\n });\n },\n },\n },\n });\n };\n\n dispose() {\n this._editor.use('ElementsApi').delete(ELEMENT_NAME);\n while (this._disposables.length > 0) {\n const d = this._disposables.pop();\n d?.dispose();\n }\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
|
|
3569
3587
|
"../../project-templates/shared/partials/plugin-app-minimal.eta": "import { pluginRegistry } from '<%= it.packageConfig.extensionsApiPackageName %>';\nimport type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Options } from '../public-types';\n\ntype Disposable = { dispose(): void };\n\nfunction normalizePublicPath(value?: string): string | undefined {\n if (!value) {\n return undefined;\n }\n const trimmed = value.replace(/\\/+$/, '');\n return trimmed + '/';\n}\n\nconst AUTO_PUBLIC_PATH = (() => {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const currentScript = document.currentScript as HTMLScriptElement | null;\n if (!currentScript?.src) {\n return undefined;\n }\n\n return normalizePublicPath(currentScript.src.replace(/[^/]*$/, ''));\n})();\n\nexport class <%= it.pluginClassName %> implements IPlugin {\n private readonly _disposables: Disposable[] = [];\n\n constructor(\n private readonly _editor: Instance,\n private readonly _options: <%= it.pluginClassName %>Options = {},\n ) {}\n\n init() {\n const publicPath = normalizePublicPath(this._options.publicPath) || AUTO_PUBLIC_PATH;\n if (publicPath) {\n const sandboxApi = this._editor.use('SandboxScriptApi');\n this._disposables.push(\n sandboxApi.registerSandboxScript(publicPath + 'sandbox.js'),\n );\n }\n }\n\n dispose() {\n while (this._disposables.length > 0) {\n const disposable = this._disposables.pop();\n disposable?.dispose();\n }\n }\n}\n\npluginRegistry.add(<%~ it.pluginKeyLiteral %>, <%= it.pluginClassName %>);\n",
|
|
3570
|
-
"../../project-templates/shared/partials/plugin-dev-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ it.devAuthMissing %>);\n }\n\n const formData = new
|
|
3571
|
-
"../../project-templates/shared/partials/plugin-dev-host-app-advanced.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { createEditorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nconst productBlockGroups = [\n {\n id: 'group1',\n name: 'iPhone X',\n image_url: '/demo/product-1.svg',\n price: 999.95,\n count: 5,\n },\n {\n id: 'group2',\n name: 'MacBook Pro',\n image_url: '/demo/product-2.svg',\n price: 1499.95,\n count: 1,\n },\n];\n\nconst editorConfig = createEditorConfig({ productBlockGroups });\n\
|
|
3572
|
-
"../../project-templates/shared/partials/plugin-dev-host-app-minimal.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\
|
|
3573
|
-
"../../project-templates/shared/partials/plugin-dev-tsx-debug.eta": "<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\nlogLegacyRuntimeStage('before-renderHostApp');\n\n\n\n\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nconst plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [PluginClass, { publicPath: '/' }],\n\n\n\n];\n\n\n\n\n\n\n\nrenderHostApp({ plugins });\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n\n\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import('./index');\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n",
|
|
3588
|
+
"../../project-templates/shared/partials/plugin-dev-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ it.devAuthMissing %>);\n }\n\n const formData = new URLSearchParams();\n formData.append('grant_type', 'client_credentials');\n formData.append('client_id', oauthCredentials.clientId);\n formData.append('client_secret', oauthCredentials.clientSecret);\n\n const response = await fetch('/api/oauth/token', {\n method: 'POST',\n body: formData,\n redirect: 'follow',\n });\n const payload = await response.json().catch(() => null);\n\n if (!response.ok || !payload || typeof payload.access_token !== 'string') {\n throw new Error(\n <%~ it.devAuthTokenFailed %>,\n );\n }\n\n return payload.access_token;\n}\n",
|
|
3589
|
+
"../../project-templates/shared/partials/plugin-dev-host-app-advanced.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { createEditorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nconst productBlockGroups = [\n {\n id: 'group1',\n name: 'iPhone X',\n image_url: '/demo/product-1.svg',\n price: 999.95,\n count: 5,\n },\n {\n id: 'group2',\n name: 'MacBook Pro',\n image_url: '/demo/product-2.svg',\n price: 1499.95,\n count: 1,\n },\n];\n\nconst editorConfig = createEditorConfig({ productBlockGroups });\n\n// Demo hint injected into the starter email HTML (see README → Demo Flow).\nconst DEMO_TARGET_MARKUP = [\n '<tr em=\"block\" class=\"empty-structure\">',\n ' <td align=\"center\">',\n ' <table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" style=\"max-width: 660px;\">',\n ' <tr>',\n ' <td align=\"center\">',\n ' <table align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"91%\">',\n ' <tr>',\n ' <td align=\"left\"></td>',\n ' </tr>',\n ' </table>',\n ' </td>',\n ' </tr>',\n ' </table>',\n ' </td>',\n '</tr>',\n '<tr>',\n ' <td style=\"padding: 32px; font-family: Arial, sans-serif; font-size: 16px; line-height: 24px; color: #333333;\">',\n ' <div style=\"padding: 16px; border: 1px dashed #d9d9d9; border-radius: 8px; background: #ffffff;\">',\n <%~ it.demoMessageLiteral %>,\n ' </div>',\n ' </td>',\n '</tr>',\n].join('');\n\nconst EMPTY_EMAIL_CONTAINER = '<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" border=\"0\" style=\"max-width: 660px; min-width: 660px; width: 660px;\" class=\"em-narrow-table\"></table>';\n\nfunction createDemoEmailHtml() {\n const populatedContainer = EMPTY_EMAIL_CONTAINER.replace('</table>', DEMO_TARGET_MARKUP + '</table>');\n return baseEmailHtml.includes(EMPTY_EMAIL_CONTAINER)\n ? baseEmailHtml.replace(EMPTY_EMAIL_CONTAINER, populatedContainer)\n : baseEmailHtml;\n}\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n const contentCode = createDemoEmailHtml();\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-advanced',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: contentCode,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n {/* The editor fills its container: without a definite height the side panels shrink to their content. */}\n <div id=\"editor-root\" style={{ height: '100vh' }} />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
|
|
3590
|
+
"../../project-templates/shared/partials/plugin-dev-host-app-minimal.eta": "/* @jsxImportSource <%= it.packageConfig.packageName %>/runtime/react */\nimport { useEffect, useRef, useState } from '<%= it.packageConfig.packageName %>/runtime/react';\nimport { createRoot } from '<%= it.packageConfig.packageName %>/runtime/react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './email.html?raw';\nimport { editorConfig } from './editorConfig';\nimport { getAuthToken } from './getAuthToken';\n\nexport interface HostAppOptions {\n plugins: NonNullable<ExportedApi.Options['plugins']>;\n}\n\n<%~ include('editor-init-smoke', it) %>\nexport function renderHostApp(options: HostAppOptions): void {\n const { plugins } = options;\n\n function EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-host-minimal',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n plugins,\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n {/* The editor fills its container: without a definite height the side panels shrink to their content. */}\n <div id=\"editor-root\" style={{ height: '100vh' }} />\n </>\n );\n }\n\n const rootElement = document.getElementById('root');\n\n if (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n }\n\n createRoot(rootElement).render(<EditorApp />);\n}\n",
|
|
3591
|
+
"../../project-templates/shared/partials/plugin-dev-tsx-debug.eta": "<% if (it.devHostCompatGlobals) { %>\n// Plugin sources resolve their dependencies from `window.<ns>.modules`: turn the compatibility layer on.\nimport '<%= it.packageConfig.packageName %>/compat-globals';\n<% } %>\n<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\nlogLegacyRuntimeStage('before-renderHostApp');\n\n\n\n\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nconst plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [PluginClass, { publicPath: '/' }],\n\n\n\n];\n\n\n\n\n\n\n\nrenderHostApp({ plugins });\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n\n\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import('./index');\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n",
|
|
3574
3592
|
"../../project-templates/shared/partials/plugin-dev-tsx-minimal.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport { init } from '<%= it.packageConfig.packageName %>';\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\n\n<%~ include('plugin-dev-tsx-runtime-helpers', it) %>\n<%~ include('editor-init-smoke', it) %>\nfunction createDemoEmailId() {\n if (typeof globalThis.crypto?.randomUUID === 'function') {\n return globalThis.crypto.randomUUID();\n }\n\n return `demo-email-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction EditorApp() {\n const instanceRef = useRef<ExportedApi.Instance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'plugin-host',\n variant: 'plugin-dev-minimal',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const PluginClass = IS_RELEASE_MODE && <%= it.releaseUsesUmd ? 'true' : 'false' %>\n ? undefined\n : await loadPluginConstructor();\n const initOptions = {\n getAuthToken,\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ it.devHostDemoTitleLiteral %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n plugins: getPluginEntries(PluginClass),\n } satisfies ExportedApi.Options;\n const instance = await init(initOptions);\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" />\n </>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ it.rootElementNotFoundLiteral %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3575
|
-
"../../project-templates/shared/partials/plugin-dev-tsx-release.eta": "<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nlogLegacyRuntimeStage('release-before-renderHostApp-umd');\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nrenderHostApp({\n\n\n\n plugins: [[PluginClass, { publicPath: '/dist/' }]],\n\n\n\n});\n\n\n\n<% } %>\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import(
|
|
3593
|
+
"../../project-templates/shared/partials/plugin-dev-tsx-release.eta": "<% if (it.releaseHostCompatGlobals) { %>\n// The built plugin reads its dependencies from `window.<ns>.modules`: turn the compatibility layer on.\nimport '<%= it.packageConfig.packageName %>/compat-globals';\n<% } %>\n<% if (it.isLegacyWebpack) { %>\n\n\n\nimport '<%= it.packageConfig.packageName %>';\n\n\n\nimport './dev/legacyRuntimeDiagAfterProduct';\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\nimport { logLegacyRuntimeStage } from './dev/legacyRuntimeDiag';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nlogLegacyRuntimeStage('release-before-renderHostApp-umd');\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nimport PluginClass from './index';\n\n\n\nimport './dev/legacyRuntimeDiagAfterPlugin';\n\n\n\nif (!PluginClass) {\n\n\n\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n\n\n\n}\n\n\n\n\n\n\n\nrenderHostApp({\n\n\n\n plugins: [[PluginClass, { publicPath: '/dist/' }]],\n\n\n\n});\n\n\n\n<% } %>\n\n\n\n<% } else { %>\n\n\n\nimport type { ExportedApi } from '<%= it.packageConfig.packageName %>';\n\n\n\nimport { renderHostApp } from './dev/hostApp';\n\n\n\n// <%= it.commentReleaseEntry %>\n\n\n\n<% if (it.releaseUsesUmd) { %>\n\n\n\nrenderHostApp({\n\n\n\n plugins: [{\n\n\n\n type: 'umd',\n\n\n\n url: '/dist/index.js',\n\n\n\n name: <%~ it.pluginKeyLiteral %>,\n\n\n\n resolve: 'registry',\n\n\n\n }] as NonNullable<ExportedApi.Options['plugins']>,\n\n\n\n});\n\n\n\n<% } else { %>\n\n\n\nasync function main(): Promise<void> {\n\n\n\n const pluginModule = await import('../dist/index.js') as {\n\n\n\n default?: typeof import('./index').default;\n\n\n\n };\n\n\n\n\n\n\n\n if (!pluginModule.default) {\n\n\n\n throw new Error('Unable to resolve the built plugin constructor from ../dist/index.js.');\n\n\n\n }\n\n\n\n\n\n\n\n const plugins: NonNullable<ExportedApi.Options['plugins']> = [\n\n\n\n [pluginModule.default, { publicPath: '/dist/' }],\n\n\n\n ];\n\n\n\n\n\n\n\n renderHostApp({ plugins });\n\n\n\n}\n\n\n\n\n\n\n\nvoid main();\n\n\n\n<% } %>\n\n\n\n<% } %>\n\n",
|
|
3576
3594
|
"../../project-templates/shared/partials/plugin-dev-tsx-runtime-helpers.eta": "type PluginConstructor = typeof import('./index').default;\ntype PluginEntries = NonNullable<ExportedApi.Options['plugins']>;\ntype PluginRunMode = 'debug' | 'release';\nconst RELEASE_PLUGIN_ENTRY: string = '/dist/index.js';\n\ndeclare global {\n var __EM_PLUGIN_RUN_MODE__: PluginRunMode | undefined;\n}\n\nconst RUN_MODE: PluginRunMode = globalThis.__EM_PLUGIN_RUN_MODE__ ?? 'debug';\nconst IS_RELEASE_MODE = RUN_MODE === 'release';\nconst SANDBOX_PUBLIC_PATH = IS_RELEASE_MODE ? '/dist/' : '/';\n\n<% if (it.releaseUsesUmd) { %>\nconst RELEASE_PLUGIN_DESCRIPTOR = {\n type: 'umd',\n url: RELEASE_PLUGIN_ENTRY,\n name: <%~ it.pluginKeyLiteral %>,\n resolve: 'registry',\n} as const;\n<% } %>\nasync function loadPluginConstructor() {\n if (!IS_RELEASE_MODE) {\n const pluginModule = await import('./index');\n if (!pluginModule.default) {\n throw new Error('Unable to resolve the local plugin constructor from ./index.');\n }\n return pluginModule.default;\n }\n\n <% if (it.releaseUsesUmd) { %>throw new Error('Release UMD bundle should be passed as a descriptor.');<% } else { %>throw new Error('Release ESM bundle should be resolved by the release host entry.');<% } %>\n}\n\nfunction getPluginEntries(pluginClass?: PluginConstructor): PluginEntries {\n if (IS_RELEASE_MODE && <%= it.releaseUsesUmd ? 'true' : 'false' %>) {\n return [RELEASE_PLUGIN_DESCRIPTOR] as PluginEntries;\n }\n\n if (!pluginClass) {\n throw new Error('Unable to resolve the plugin constructor.');\n }\n\n return [[pluginClass, { publicPath: SANDBOX_PUBLIC_PATH }] as const] as PluginEntries;\n}\n",
|
|
3577
3595
|
"../../project-templates/shared/partials/plugin-editor-config.eta": "<% if (it.isAdvanced) { %>\nimport type { Config } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config, <%= it.pluginClassName %>ProductGroup } from '../public-types';\n\ntype EditorConfigOptions = {\n productBlockGroups?: <%= it.pluginClassName %>ProductGroup[];\n};\n\n/** Minimal dev-host config: product groups for the demo. Extend with merge tags, fileManager, etc. as needed. */\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'ru_RU',\n} satisfies Partial<<%~ it.baseConfigTarget %>>;\n\nexport function createEditorConfig(options: EditorConfigOptions = {}): Partial<Config> {\n if (options.productBlockGroups?.length) {\n return {\n ...baseEditorConfig,\n productBlock: {\n enabled: true,\n groups: options.productBlockGroups,\n },\n } satisfies <%~ `Partial<Config & ${it.pluginClassName}Config>` %>;\n }\n\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n<% } else { %>\nimport type { Config } from '<%= it.packageConfig.packageName %>';\nimport type { <%= it.pluginClassName %>Config } from '../public-types';\n\nconst mergeTagItems = [\n {\n label: 'Profile',\n value: 'profile',\n children: [\n { label: 'First name', value: 'profile.firstName' },\n { label: 'Last name', value: 'profile.lastName' },\n { label: 'Email', value: 'profile.email' },\n ],\n },\n {\n label: 'Company',\n value: 'company',\n children: [\n { label: 'Name', value: 'company.name' },\n { label: 'Industry', value: 'company.industry' },\n { label: 'Website', value: 'company.website' },\n ],\n },\n {\n label: 'Campaign',\n value: 'campaign',\n children: [\n { label: 'Title', value: 'campaign.title' },\n { label: 'Promo code', value: 'campaign.promoCode' },\n { label: 'CTA URL', value: 'campaign.ctaUrl' },\n ],\n },\n];\n\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'ru_RU',\n autosaveTimeout: 15000,\n commonStylesEnabled: true,\n mergeTagsShow: true,\n imageCenterFileManagerView: true,\n fileManager: {\n defaultFolderName: 'demo-assets',\n enableMoveFolder: true,\n enableEdit: true,\n enableTrash: true,\n enableCopyFile: true,\n enableCopyFolder: true,\n },\n mergeTags: {\n syntax: ['{{' + '%value%' + '}}'],\n items: mergeTagItems,\n },\n} satisfies Partial<<%~ it.baseConfigTarget %>>;\n\nexport function createEditorConfig(): Partial<Config> {\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n<% } %>\n",
|
|
3578
3596
|
"../../project-templates/shared/partials/plugin-index-ts.eta": "import { <%= it.pluginClassName %> } from './app/<%= it.pluginClassName %>';\n\nexport default <%= it.pluginClassName %>;\n",
|
|
3579
|
-
"../../project-templates/shared/partials/plugin-panel-advanced.eta": "import React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { Collapse, Form, Input, Select, Typography } from 'antd';\nimport { ColorPicker, EmIcons } from '<%= it.packageConfig.uiKitPackageName %>';\nimport type { Group, VisualSettings } from '../../interfaces';\n\nconst { Panel } = Collapse;\nconst { Text } = Typography;\nconst { TextArea } = Input;\n\nconst UI_TEXT = {\n contentSettings: <%~ it.panelUi.contentSettings %>,\n visualSettings: <%~ it.panelUi.visualSettings %>,\n selectGroup: <%~ it.panelUi.selectGroup %>,\n itemsCount: <%~ it.panelUi.itemsCount %>,\n blockBorder: <%~ it.panelUi.blockBorder %>,\n blockPadding: <%~ it.panelUi.blockPadding %>,\n cardBackgroundColor: <%~ it.panelUi.cardBackgroundColor %>,\n cardTextColor: <%~ it.panelUi.cardTextColor %>,\n cardTextAlign: <%~ it.panelUi.cardTextAlign %>,\n alignLeft: <%~ it.panelUi.alignLeft %>,\n alignCenter: <%~ it.panelUi.alignCenter %>,\n alignRight: <%~ it.panelUi.alignRight %>,\n buttonText: <%~ it.panelUi.buttonText %>,\n buttonColor: <%~ it.panelUi.buttonColor %>,\n saveTitle: <%~ it.panelUi.saveTitle %>,\n saveSize: <%~ it.panelUi.saveSize %>,\n bytes: <%~ it.panelUi.bytes %>,\n contentPlaceholder: <%~ it.panelUi.contentPlaceholder %>,\n emailFormat: <%~ it.panelUi.emailFormat %>,\n};\n\nexport function <%= it.pluginClassName %>Icon() {\n return React.createElement(EmIcons, { icon: 'Sun' });\n}\n\nexport interface <%= it.pluginClassName %>SettingsPanelProps {\n groups: Group[];\n settings: VisualSettings;\n selectedGroup?: string;\n onChange?(group: Group | undefined, settings: VisualSettings): void;\n}\n\nexport type EmailFormat = 'amp' | 'text' | 'html';\n\nexport interface <%= it.pluginClassName %>SaveFormProps {\n content?: string;\n initialFormat?: EmailFormat;\n onChange?: (values: { content: string; format: EmailFormat }) => void;\n}\n\nfunction renderGroupOption(group: Group) {\n return (\n <div style={{ display: 'flex', alignItems: 'center', padding: '8px', borderBottom: '1px solid #ddd' }}>\n <img\n src={group.image_url}\n alt={group.name}\n style={{ width: 40, height: 40, marginRight: 10, borderRadius: 4 }}\n />\n <div>\n <Text strong>{group.name}</Text>\n <br />\n <Text type=\"secondary\">{group.count} {UI_TEXT.itemsCount}</Text>\n </div>\n </div>\n );\n}\n\nfunction ContentSettings({\n groups,\n selectedGroup,\n onChange,\n}: {\n groups: Group[];\n selectedGroup: string;\n onChange: (value: string) => void;\n}) {\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.selectGroup}>\n <Select\n value={groups.some((group) => group.id === selectedGroup) ? selectedGroup : undefined}\n onChange={onChange}\n style={{ width: '100%', height: '60px' }}\n dropdownStyle={{ padding: 0 }}\n >\n {groups.map((group) => (\n <Select.Option key={group.id} value={group.id}>\n {renderGroupOption(group)}\n </Select.Option>\n ))}\n </Select>\n </Form.Item>\n </Form>\n );\n}\n\nfunction VisualSettingsForm({\n settings,\n onChange,\n}: {\n settings: VisualSettings;\n onChange: (nextSettings: VisualSettings) => void;\n}) {\n const [local, setLocal] = useState(settings);\n const isEditingRef = useRef(false);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!isEditingRef.current) {\n setLocal(settings);\n }\n }, [settings]);\n\n useEffect(() => () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n }, []);\n\n const updateField = (key: keyof VisualSettings, value: VisualSettings[keyof VisualSettings]) => {\n isEditingRef.current = true;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n const updated = { ...local, [key]: value };\n setLocal(updated);\n onChange(updated);\n\n timeoutRef.current = setTimeout(() => {\n isEditingRef.current = false;\n }, 50);\n };\n\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.blockBorder}>\n <Input\n type=\"number\"\n value={local.blockBorder}\n onChange={(e) => updateField('blockBorder', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.blockPadding}>\n <Input\n type=\"number\"\n value={local.blockPadding}\n onChange={(e) => updateField('blockPadding', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n {/*\n ColorPicker fills Form.Item width by default (ui-kit).\n With antd Form + field names prefer FormColorField from ui-kit — see docs/plugin-system/06-ui/UI_KIT.md.\n */}\n <Form.Item label={UI_TEXT.cardBackgroundColor}>\n <ColorPicker\n value={local.cardBackgroundColor}\n onChange={(color) => updateField('cardBackgroundColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextColor}>\n <ColorPicker\n value={local.cardTextColor}\n onChange={(color) => updateField('cardTextColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextAlign}>\n <Select\n value={local.cardTextAlign}\n onChange={(value) => updateField('cardTextAlign', value)}\n >\n <Select.Option value=\"left\">{UI_TEXT.alignLeft}</Select.Option>\n <Select.Option value=\"center\">{UI_TEXT.alignCenter}</Select.Option>\n <Select.Option value=\"right\">{UI_TEXT.alignRight}</Select.Option>\n </Select>\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonText}>\n <Input\n value={local.cardButtonText}\n onChange={(e) => updateField('cardButtonText', e.target.value)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonColor}>\n <ColorPicker\n value={local.cardButtonColor}\n onChange={(color) => updateField('cardButtonColor', color)}\n />\n </Form.Item>\n </Form>\n );\n}\n\nexport function <%= it.pluginClassName %>SettingsPanel({\n groups,\n settings,\n selectedGroup,\n onChange,\n}: <%= it.pluginClassName %>SettingsPanelProps) {\n const [currentGroupId, setCurrentGroupId] = useState<string>(selectedGroup || '');\n const [currentSettings, setCurrentSettings] = useState<VisualSettings>(settings);\n const isFirstRender = useRef(true);\n const isDirty = useRef(false);\n\n const currentGroup = useMemo(\n () => groups.find((group) => group.id === currentGroupId),\n [groups, currentGroupId],\n );\n\n useEffect(() => {\n setCurrentSettings(settings);\n setCurrentGroupId(selectedGroup !== undefined ? selectedGroup : '');\n isDirty.current = false;\n }, [settings, selectedGroup]);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n\n if (isDirty.current && onChange) {\n onChange(currentGroup, currentSettings);\n }\n }, [currentSettings, currentGroup, onChange]);\n\n return (\n <div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}>\n <Collapse defaultActiveKey={['1', '2']} style={{ borderRadius: '8px' }}>\n <Panel header={<Text strong>{UI_TEXT.contentSettings}</Text>} key=\"1\">\n <ContentSettings\n groups={groups}\n selectedGroup={currentGroupId}\n onChange={(groupId) => {\n setCurrentGroupId(groupId);\n isDirty.current = true;\n\n const group = groups.find((item) => item.id === groupId);\n onChange?.(group, currentSettings);\n }}\n />\n </Panel>\n <Panel header={<Text strong>{UI_TEXT.visualSettings}</Text>} key=\"2\">\n <VisualSettingsForm\n settings={currentSettings}\n onChange={(nextSettings) => {\n setCurrentSettings(nextSettings);\n isDirty.current = true;\n }}\n />\n </Panel>\n </Collapse>\n </div>\n );\n}\n\nexport function <%= it.pluginClassName %>SaveForm({\n content: initialContent = '',\n initialFormat = 'text',\n onChange,\n}: <%= it.pluginClassName %>SaveFormProps) {\n const [content, setContent] = useState(initialContent);\n const [format, setFormat] = useState<EmailFormat>(initialFormat);\n\n const getByteLength = (value: string): number => new TextEncoder().encode(value).length;\n\n useEffect(() => {\n onChange?.({ content, format });\n }, [content, format, onChange]);\n\n return (\n <Form layout=\"vertical\" autoComplete=\"off\">\n <Form.Item label={UI_TEXT.saveSize + ': ' + String(getByteLength(content)) + ' ' + UI_TEXT.bytes}>\n <TextArea\n rows={6}\n value={content}\n onChange={(e) => setContent(e.target.value)}\n placeholder={UI_TEXT.contentPlaceholder}\n allowClear\n data-testid=\"email-content-input\"\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.emailFormat} required>\n <Select<EmailFormat>\n value={format}\n onChange={(value) => setFormat(value)}\n data-testid=\"email-format-select\"\n >\n <Select.Option value=\"amp\">AMP</Select.Option>\n <Select.Option value=\"text\">Text/plain</Select.Option>\n <Select.Option value=\"html\">HTML</Select.Option>\n </Select>\n </Form.Item>\n </Form>\n );\n}\n",
|
|
3597
|
+
"../../project-templates/shared/partials/plugin-panel-advanced.eta": "import React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { Collapse, Form, Input, Select, Typography } from 'antd';\n/*\n * Icons come from the plugin's own `@ant-design/icons` copy and are tree-shaken there: the host\n * publishes only the `AntdIcon` machinery, not the 831-entry catalogue. Any icon of the package\n * works, including ones the host never uses — and it still renders in the host's icon context,\n * because the machinery that computes the class is a single shared copy.\n */\nimport { ApiOutlined, SunOutlined } from '@ant-design/icons';\n/*\n * No `EmIcons icon=\"…\"` here: a plugin is built without the host's icon codemod, so a name is\n * looked up in the registry at runtime and pulls the whole ui-kit catalog.\n */\nimport { ColorPicker } from '<%= it.packageConfig.uiKitPackageName %>';\nimport type { Group, VisualSettings } from '../../interfaces';\n\nconst { Panel } = Collapse;\nconst { Text } = Typography;\nconst { TextArea } = Input;\n\nconst UI_TEXT = {\n contentSettings: <%~ it.panelUi.contentSettings %>,\n visualSettings: <%~ it.panelUi.visualSettings %>,\n selectGroup: <%~ it.panelUi.selectGroup %>,\n itemsCount: <%~ it.panelUi.itemsCount %>,\n blockBorder: <%~ it.panelUi.blockBorder %>,\n blockPadding: <%~ it.panelUi.blockPadding %>,\n cardBackgroundColor: <%~ it.panelUi.cardBackgroundColor %>,\n cardTextColor: <%~ it.panelUi.cardTextColor %>,\n cardTextAlign: <%~ it.panelUi.cardTextAlign %>,\n alignLeft: <%~ it.panelUi.alignLeft %>,\n alignCenter: <%~ it.panelUi.alignCenter %>,\n alignRight: <%~ it.panelUi.alignRight %>,\n buttonText: <%~ it.panelUi.buttonText %>,\n buttonColor: <%~ it.panelUi.buttonColor %>,\n saveTitle: <%~ it.panelUi.saveTitle %>,\n saveSize: <%~ it.panelUi.saveSize %>,\n bytes: <%~ it.panelUi.bytes %>,\n contentPlaceholder: <%~ it.panelUi.contentPlaceholder %>,\n emailFormat: <%~ it.panelUi.emailFormat %>,\n};\n\nexport function <%= it.pluginClassName %>Icon() {\n return React.createElement(SunOutlined);\n}\n\nexport interface <%= it.pluginClassName %>SettingsPanelProps {\n groups: Group[];\n settings: VisualSettings;\n selectedGroup?: string;\n onChange?(group: Group | undefined, settings: VisualSettings): void;\n}\n\nexport type EmailFormat = 'amp' | 'text' | 'html';\n\nexport interface <%= it.pluginClassName %>SaveFormProps {\n content?: string;\n initialFormat?: EmailFormat;\n onChange?: (values: { content: string; format: EmailFormat }) => void;\n}\n\nfunction renderGroupOption(group: Group) {\n return (\n <div style={{ display: 'flex', alignItems: 'center', padding: '8px', borderBottom: '1px solid #ddd' }}>\n <img\n src={group.image_url}\n alt={group.name}\n style={{ width: 40, height: 40, marginRight: 10, borderRadius: 4 }}\n />\n <div>\n <Text strong>{group.name}</Text>\n <br />\n <Text type=\"secondary\">{group.count} {UI_TEXT.itemsCount}</Text>\n </div>\n </div>\n );\n}\n\nfunction ContentSettings({\n groups,\n selectedGroup,\n onChange,\n}: {\n groups: Group[];\n selectedGroup: string;\n onChange: (value: string) => void;\n}) {\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.selectGroup}>\n <Select\n value={groups.some((group) => group.id === selectedGroup) ? selectedGroup : undefined}\n onChange={onChange}\n style={{ width: '100%', height: '60px' }}\n dropdownStyle={{ padding: 0 }}\n >\n {groups.map((group) => (\n <Select.Option key={group.id} value={group.id}>\n {renderGroupOption(group)}\n </Select.Option>\n ))}\n </Select>\n </Form.Item>\n </Form>\n );\n}\n\nfunction VisualSettingsForm({\n settings,\n onChange,\n}: {\n settings: VisualSettings;\n onChange: (nextSettings: VisualSettings) => void;\n}) {\n const [local, setLocal] = useState(settings);\n const isEditingRef = useRef(false);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!isEditingRef.current) {\n setLocal(settings);\n }\n }, [settings]);\n\n useEffect(() => () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n }, []);\n\n const updateField = (key: keyof VisualSettings, value: VisualSettings[keyof VisualSettings]) => {\n isEditingRef.current = true;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n\n const updated = { ...local, [key]: value };\n setLocal(updated);\n onChange(updated);\n\n timeoutRef.current = setTimeout(() => {\n isEditingRef.current = false;\n }, 50);\n };\n\n return (\n <Form layout=\"vertical\" style={{ padding: '10px' }}>\n <Form.Item label={UI_TEXT.blockBorder}>\n <Input\n type=\"number\"\n value={local.blockBorder}\n onChange={(e) => updateField('blockBorder', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.blockPadding}>\n <Input\n type=\"number\"\n value={local.blockPadding}\n onChange={(e) => updateField('blockPadding', parseInt(e.target.value, 10) || 0)}\n />\n </Form.Item>\n\n {/*\n ColorPicker fills Form.Item width by default (ui-kit).\n With antd Form + field names prefer FormColorField from ui-kit — see docs/plugin-system/06-ui/UI_KIT.md.\n */}\n <Form.Item label={UI_TEXT.cardBackgroundColor}>\n <ColorPicker\n value={local.cardBackgroundColor}\n onChange={(color) => updateField('cardBackgroundColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextColor}>\n <ColorPicker\n value={local.cardTextColor}\n onChange={(color) => updateField('cardTextColor', color)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.cardTextAlign}>\n <Select\n value={local.cardTextAlign}\n onChange={(value) => updateField('cardTextAlign', value)}\n >\n <Select.Option value=\"left\">{UI_TEXT.alignLeft}</Select.Option>\n <Select.Option value=\"center\">{UI_TEXT.alignCenter}</Select.Option>\n <Select.Option value=\"right\">{UI_TEXT.alignRight}</Select.Option>\n </Select>\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonText}>\n <Input\n value={local.cardButtonText}\n onChange={(e) => updateField('cardButtonText', e.target.value)}\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.buttonColor}>\n <ColorPicker\n value={local.cardButtonColor}\n onChange={(color) => updateField('cardButtonColor', color)}\n />\n </Form.Item>\n </Form>\n );\n}\n\nexport function <%= it.pluginClassName %>SettingsPanel({\n groups,\n settings,\n selectedGroup,\n onChange,\n}: <%= it.pluginClassName %>SettingsPanelProps) {\n const [currentGroupId, setCurrentGroupId] = useState<string>(selectedGroup || '');\n const [currentSettings, setCurrentSettings] = useState<VisualSettings>(settings);\n const isFirstRender = useRef(true);\n const isDirty = useRef(false);\n\n const currentGroup = useMemo(\n () => groups.find((group) => group.id === currentGroupId),\n [groups, currentGroupId],\n );\n\n useEffect(() => {\n setCurrentSettings(settings);\n setCurrentGroupId(selectedGroup !== undefined ? selectedGroup : '');\n isDirty.current = false;\n }, [settings, selectedGroup]);\n\n useEffect(() => {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n\n if (isDirty.current && onChange) {\n onChange(currentGroup, currentSettings);\n }\n }, [currentSettings, currentGroup, onChange]);\n\n return (\n <div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}>\n <Collapse defaultActiveKey={['1', '2']} style={{ borderRadius: '8px' }}>\n <Panel\n header={\n <Text strong>\n <ApiOutlined /> {UI_TEXT.contentSettings}\n </Text>\n }\n key=\"1\"\n >\n <ContentSettings\n groups={groups}\n selectedGroup={currentGroupId}\n onChange={(groupId) => {\n setCurrentGroupId(groupId);\n isDirty.current = true;\n\n const group = groups.find((item) => item.id === groupId);\n onChange?.(group, currentSettings);\n }}\n />\n </Panel>\n <Panel header={<Text strong>{UI_TEXT.visualSettings}</Text>} key=\"2\">\n <VisualSettingsForm\n settings={currentSettings}\n onChange={(nextSettings) => {\n setCurrentSettings(nextSettings);\n isDirty.current = true;\n }}\n />\n </Panel>\n </Collapse>\n </div>\n );\n}\n\nexport function <%= it.pluginClassName %>SaveForm({\n content: initialContent = '',\n initialFormat = 'text',\n onChange,\n}: <%= it.pluginClassName %>SaveFormProps) {\n const [content, setContent] = useState(initialContent);\n const [format, setFormat] = useState<EmailFormat>(initialFormat);\n\n const getByteLength = (value: string): number => new TextEncoder().encode(value).length;\n\n useEffect(() => {\n onChange?.({ content, format });\n }, [content, format, onChange]);\n\n return (\n <Form layout=\"vertical\" autoComplete=\"off\">\n <Form.Item label={UI_TEXT.saveSize + ': ' + String(getByteLength(content)) + ' ' + UI_TEXT.bytes}>\n <TextArea\n rows={6}\n value={content}\n onChange={(e) => setContent(e.target.value)}\n placeholder={UI_TEXT.contentPlaceholder}\n allowClear\n data-testid=\"email-content-input\"\n />\n </Form.Item>\n\n <Form.Item label={UI_TEXT.emailFormat} required>\n <Select<EmailFormat>\n value={format}\n onChange={(value) => setFormat(value)}\n data-testid=\"email-format-select\"\n >\n <Select.Option value=\"amp\">AMP</Select.Option>\n <Select.Option value=\"text\">Text/plain</Select.Option>\n <Select.Option value=\"html\">HTML</Select.Option>\n </Select>\n </Form.Item>\n </Form>\n );\n}\n",
|
|
3580
3598
|
"../../project-templates/shared/partials/plugin-panel-minimal.eta": "import {\n DomComponentRegistry,\n createComponentIdentifier,\n type IDomComponentFactory,\n} from '<%= it.packageConfig.extensionsApiPackageName %>';\n\nexport const <%= it.pluginClassName %>PanelId = <%~ `createComponentIdentifier<${it.pluginClassName}PanelProps>` %>(\n '<%= it.pluginClassName %>SettingsPanel',\n);\n\nexport interface <%= it.pluginClassName %>PanelProps {\n initialValue: string;\n onApply(value: string): void;\n}\n\nconst create<%= it.pluginClassName %>PanelNode: <%~ `IDomComponentFactory<${it.pluginClassName}PanelProps>` %> = (props) => {\n const root = document.createElement('div');\n root.style.display = 'grid';\n root.style.gap = '12px';\n\n const text = document.createElement('div');\n text.textContent = <%~ it.panelUi.minimalInstructions %>;\n\n const input = document.createElement('input');\n input.value = props.initialValue;\n input.style.padding = '8px 12px';\n input.style.border = '1px solid #d9d9d9';\n input.style.borderRadius = '6px';\n\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = <%~ it.panelUi.minimalApply %>;\n button.style.padding = '8px 12px';\n button.style.border = '0';\n button.style.borderRadius = '6px';\n button.style.background = '#1677ff';\n button.style.color = '#ffffff';\n button.style.cursor = 'pointer';\n\n let currentProps = props;\n const handleClick = () => {\n currentProps.onApply(input.value);\n };\n\n button.addEventListener('click', handleClick);\n\n root.append(text, input, button);\n\n return {\n node: root,\n update(nextProps) {\n currentProps = nextProps;\n input.value = nextProps.initialValue;\n },\n dispose() {\n button.removeEventListener('click', handleClick);\n },\n };\n};\n\nlet panelRegistered = false;\n\nexport function ensure<%= it.pluginClassName %>PanelRegistered() {\n if (panelRegistered) {\n return;\n }\n\n DomComponentRegistry.add(<%= it.pluginClassName %>PanelId, create<%= it.pluginClassName %>PanelNode);\n panelRegistered = true;\n}\n",
|
|
3581
3599
|
"../../project-templates/shared/partials/plugin-public-types.eta": "import type { IPlugin, Instance } from '<%= it.packageConfig.packageName %>';\n\nexport interface <%= it.pluginClassName %>Options {\n publicPath?: string;\n}\n\n<% if (it.isAdvanced) { %>\nexport interface <%= it.pluginClassName %>ProductGroup {\n id: string;\n name: string;\n image_url: string;\n price: number;\n count: number;\n}\n\nexport interface <%= it.pluginClassName %>Config {\n productBlock?: {\n enabled?: boolean;\n groups?: <%= it.pluginClassName %>ProductGroup[];\n };\n}\n\n<% } else { %>\nexport interface <%= it.pluginClassName %>Config {}\n\n<% } %>\nexport declare class <%= it.pluginClassName %> implements IPlugin {\n constructor(instance: Instance, options?: <%= it.pluginClassName %>Options);\n init?(): Promise<void> | void;\n afterInit?(): Promise<void> | void;\n dispose?(): Promise<void> | void;\n}\n\nexport default <%= it.pluginClassName %>;\n\ndeclare module '<%= it.packageConfig.packageName %>' {\n interface PluginTypeMap {\n <%= it.pluginKey %>: typeof <%= it.pluginClassName %>;\n }\n\n interface Config extends <%= it.pluginClassName %>Config {}\n}\n\nexport {};\n",
|
|
3582
3600
|
"../../project-templates/shared/partials/plugin-readme.eta": "# <%= it.pluginPackageName %>\n\n<%= it.readme.generated %>\n\n<%= it.readme.whatIncluded %>\n\n<%= it.readme.lineMinimalScaffold %>\n<%= it.readme.lineMinimalSandbox %>\n<% if (it.readme.lineAdvancedProductCard) { %><%= it.readme.lineAdvancedProductCard %>\n<% } %><% if (it.readme.lineTemplatingPreview) { %><%= it.readme.lineTemplatingPreview %>\n<% } %><%= it.readme.localDebugHost %>\n<%= it.readme.presetLine %>\n<%= it.readme.bundlerLine %>\n<%= it.readme.deliveryTarget %>\n\n<%= it.readme.commands %>\n\n```bash\nnpm install\nnpm run start\nnpm run start:release\nnpm run build\n```\n\n<%= it.readme.commandStartDebug %>\n<%= it.readme.commandStartRelease %>\n\n<%= it.readme.localAuthSetup %>\n\n<%= it.readme.fillOAuthCredentials %>\n\n```ts\nexport const oauthCredentials = {\n clientId: 'YOUR_CLIENT_ID',\n clientSecret: 'YOUR_CLIENT_SECRET',\n};\n```\n\n<%= it.readme.afterAuth %>\n\n<% if (it.readme.advancedDemoFlow) { %><%= it.readme.advancedDemoFlow %>\n\n<%= it.readme.advancedDemoFlowBody %>\n<% } %>\n<%= it.readme.structure %>\n\n<%= it.readme.structureApp %>\n<%= it.readme.structureSandbox %>\n<% if (it.readme.structureCommon) { %><%= it.readme.structureCommon %>\n<% } %><% if (it.readme.structureInterfaces) { %><%= it.readme.structureInterfaces %>\n<% } %><%= it.readme.structureDevHost %>\n<%= it.readme.structureEmail %>\n<%= it.readme.structureCredentials %>\n<%= it.readme.structurePublicTypes %>\n<%= it.readme.structureEditorConfig %>\n<% if (it.readme.advancedEditorConfigNote) { %><%= it.readme.advancedEditorConfigNote %>\n<% } %><%= it.readme.structureConfig %>\n\n<%= it.readme.notes %>\n\n<%= it.readme.registeredInPluginRegistry %>\n<%= it.readme.sandboxLoadedFrom %>\n<%= it.readme.releaseBundleTarget %>\n<%= it.readme.reactIntegrations %>\n<%= it.readme.troubleshooting %>\n<% if (it.readme.legacyMappings) { %><%= it.readme.legacyMappings %>\n<% } %><% if (it.readme.localTarballs) { %><%= it.readme.localTarballs %>\n<% } %>\n",
|
|
3583
3601
|
"../../project-templates/shared/partials/plugin-sandbox-advanced.eta": "import { App, MessageService, SyncService } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport {\n Activate_Product_Settings,\n Change_Product_Settings,\n Group,\n VisualSettings,\n} from '../interfaces';\n\nimport groupCardTemplate from '../common/templates/group-card.html?raw';\nimport emptyGroupTemplate from '../common/templates/empty-group.html?raw';\n\n/** SSOT: same CSS as plugin-app-advanced (`plugin/assets/advanced/product-card.css` via Eta). */\nconst PRODUCT_CARD_CSS = <%~ it.productCardCssLiteral %>;\n\ntype Disposable = { dispose(): void };\n\nclass ProductCardSandbox implements IPlugin {\n private _messageService!: MessageService;\n private _syncService?: SyncService;\n private _activeAtom: HTMLElement | null = null;\n private readonly _disposables: Disposable[] = [];\n\n private _hasExtensionStyles(): boolean {\n return Boolean(document.querySelector('style[data-extension=\"product-card-styles\"]'));\n }\n\n private _injectStylesFallback() {\n if (this._hasExtensionStyles()) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute('data-extension', 'product-card-styles');\n style.textContent = PRODUCT_CARD_CSS;\n document.head.appendChild(style);\n }\n\n private async _ensureStyles() {\n for (let attempt = 0; attempt < 40; attempt += 1) {\n if (this._hasExtensionStyles()) {\n return;\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n this._injectStylesFallback();\n }\n\n private _fillTemplate(template: string, data: Record<string, string>): string {\n return template.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, key) => data[key] || '');\n }\n\n private _onClick = (e: MouseEvent) => {\n const target = e.target as HTMLElement;\n const atom = target.closest('.product-atom') as HTMLElement | null;\n if (!atom) return;\n this._activeAtom = atom;\n const groupId = this._getGroupId(atom);\n const settings = this._extractVisualSettings(atom);\n this._messageService.send(Activate_Product_Settings, { groupId, visualSettings: settings });\n e.preventDefault();\n };\n\n private _onChangeSettings = ({\n group,\n visualSettings,\n }: {\n group?: Group;\n visualSettings: VisualSettings;\n }) => {\n if (!this._activeAtom) return;\n if (this._getGroupId(this._activeAtom) !== group?.id) {\n this._renderGroupCard(this._activeAtom, group);\n const groupId = this._getGroupId(this._activeAtom);\n const settings = this._extractVisualSettings(this._activeAtom);\n this._messageService.send(Activate_Product_Settings, {\n groupId,\n visualSettings: settings,\n });\n }\n setTimeout(() => {\n this._applyVisualSettings(this._activeAtom!, visualSettings);\n }, 0);\n };\n\n private _renderGroupCard(containerAtom: HTMLElement, group?: Group) {\n const container = containerAtom.querySelector('.groups-container') as HTMLElement;\n if (!container) return;\n const html = group\n ? this._fillTemplate(groupCardTemplate, {\n groupId: group.id,\n imageUrl: group.image_url,\n name: group.name,\n price: String(group.price),\n count: String(group.count),\n })\n : emptyGroupTemplate;\n container.innerHTML = html;\n this._syncService?.commit();\n }\n\n private _applyVisualSettings(atom: HTMLElement, settings: VisualSettings) {\n const card = atom.querySelector('.group-container') as HTMLElement | null;\n if (!card) return;\n const button = card.querySelector('.button-buy') as HTMLElement | null;\n if (settings.blockBorder !== undefined) {\n card.style.border = settings.blockBorder + 'px solid #ccc';\n }\n if (settings.blockPadding !== undefined) {\n card.style.padding = settings.blockPadding + 'px';\n }\n if (settings.cardBackgroundColor) card.style.backgroundColor = settings.cardBackgroundColor;\n if (settings.cardTextColor && button) button.style.color = settings.cardTextColor;\n if (settings.cardTextAlign) card.style.textAlign = settings.cardTextAlign;\n if (button) {\n if (settings.cardButtonColor) button.style.backgroundColor = settings.cardButtonColor;\n if (settings.cardButtonText) button.textContent = settings.cardButtonText;\n }\n this._syncService?.commit();\n }\n\n private _extractVisualSettings(atom: HTMLElement): VisualSettings {\n const card = atom.querySelector('.group-container') as HTMLElement | null;\n const button = card?.querySelector('.button-buy') as HTMLElement | null;\n const cardStyle = card && getComputedStyle(card);\n const buttonStyle = button && getComputedStyle(button);\n return {\n blockBorder: cardStyle?.border ? parseInt(cardStyle.border, 10) : 0,\n blockPadding: cardStyle?.padding ? parseInt(cardStyle.padding, 10) : 0,\n cardBackgroundColor: cardStyle?.backgroundColor || undefined,\n cardTextColor: buttonStyle?.color || cardStyle?.color || undefined,\n cardTextAlign: (cardStyle?.textAlign as VisualSettings['cardTextAlign']) || 'left',\n cardButtonText: button?.textContent || '',\n cardButtonColor: buttonStyle?.backgroundColor || undefined,\n };\n }\n\n private _getGroupId(atom: HTMLElement): string | undefined {\n const container = atom.querySelector('.group-container');\n return container?.getAttribute('data-group-id') || undefined;\n }\n\n init() {\n this._messageService = App.use('MessageService');\n this._syncService = App.use('SyncService');\n void this._ensureStyles();\n // Click on .product-atom in the email → tell app to open the settings panel.\n document.addEventListener('mousedown', this._onClick, true);\n this._disposables.push(\n this._messageService.addListener(Change_Product_Settings, this._onChangeSettings),\n );\n }\n\n dispose() {\n document.removeEventListener('mousedown', this._onClick, true);\n while (this._disposables.length > 0) {\n this._disposables.pop()?.dispose();\n }\n }\n}\n\nApp.use(ProductCardSandbox);\n",
|
|
3584
3602
|
"../../project-templates/shared/partials/plugin-sandbox-minimal.eta": "import { App } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\nimport type { IPlugin } from '<%= it.packageConfig.extensionsSandboxPackageName %>';\n\nclass <%= it.pluginClassName %>Sandbox implements IPlugin {}\n\nApp.use(<%= it.pluginClassName %>Sandbox);\n",
|
|
3585
3603
|
"../../project-templates/shared/partials/plugin-types-dts.eta": "declare module '*.html?raw' {\n const content: string;\n export default content;\n}\n\ndeclare module '*.css?raw' {\n const content: string;\n export default content;\n}\n",
|
|
3586
|
-
"../../project-templates/shared/partials/plugin-vite-dev-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n // <%= it.commentDevHostMode %>\n plugins: [\n PluginDev({ externals: false }),\n react(),\n VitePlugin(),\n ],\n optimizeDeps: {\n entries: ['index.html'],\n },\n server: {\n port: devPort,\n strictPort: true,\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n configure: (proxy) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3604
|
+
"../../project-templates/shared/partials/plugin-vite-dev-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n // <%= it.commentDevHostMode %>\n plugins: [\n PluginDev({ externals: false }),\n react(),\n VitePlugin(),\n ],\n optimizeDeps: {\n entries: ['index.html'],\n },\n server: {\n port: devPort,\n strictPort: true,\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxy) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3587
3605
|
"../../project-templates/shared/partials/plugin-vite-index-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> <%= it.indexHtmlTitleSuffix %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"<%= it.pluginViteIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
|
|
3588
3606
|
"../../project-templates/shared/partials/plugin-vite-plugin-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport PluginDev from '<%= it.packageConfig.packageName %>/vite/pluginDev';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst pluginDevExternals = <%~ it.importsModeLiteral %>;\n\nconst config = defineConfig({\n root: projectRoot,\n plugins: [\n PluginDev({ externals: pluginDevExternals }),\n ],\n build: {\n sourcemap: true,\n minify: true,\n outDir: 'dist',\n emptyOutDir: false,\n lib: {\n entry: path.resolve(projectRoot, 'src/index.ts'),\n formats: ['<%= it.pluginFormatVite %>'],\n name: '<%= it.pluginClassName %>',\n fileName: () => 'index.js',\n },\n },\n}) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3589
|
-
"../../project-templates/shared/partials/plugin-vite-release-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\
|
|
3607
|
+
"../../project-templates/shared/partials/plugin-vite-release-host.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport VitePlugin from '<%= it.packageConfig.packageName %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devPort = Number(process.env.PLUGIN_DEV_PORT) || 3000;\n\n/**\n * Proxy shared by the dev server and the preview server: the production host serves built assets,\n * but still talks to the same API.\n */\nconst apiProxy = {\n '/api': {\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxy: any) => {\n // <%= it.commentApiProxy %>\n proxy.on('proxyReq', (proxyReq: any) => {\n if (proxyReq.getHeader('origin')) {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n }\n });\n },\n },\n};\n\nconst config = defineConfig(() => ({\n root: projectRoot,\n plugins: [\n react(),\n VitePlugin(),\n ],\n /**\n * Production host: `build` + `preview` instead of the dev server.\n *\n * The dev server hands every dependency to vite's optimizer, which bundles each one whole and on\n * purpose does not shake it. Weights seen there say nothing about the delivered result — only a\n * built host does.\n */\n build: {\n outDir: 'dist-host',\n emptyOutDir: true,\n rollupOptions: {\n input: path.resolve(projectRoot, 'release.html'),\n },\n },\n preview: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n proxy: apiProxy,\n },\n server: {\n port: devPort,\n strictPort: true,\n open: '/release.html',\n // Allow `/@vite/client` when the initiator has opaque origin (`Origin: null`, e.g. sandbox iframe).\n cors: true,\n proxy: apiProxy,\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3590
3608
|
"../../project-templates/shared/partials/plugin-vite-release-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> release host</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/dev-release.tsx\"><\/script>\n </body>\n</html>\n",
|
|
3591
3609
|
"../../project-templates/shared/partials/plugin-vite-sandbox-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { defineConfig, type UserConfigExport } from 'vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = defineConfig(({ mode }) => ({\n root: projectRoot,\n build: {\n sourcemap: true,\n minify: mode === 'production',\n outDir: mode === 'development' ? 'public' : 'dist',\n emptyOutDir: false,\n lib: {\n entry: path.resolve(projectRoot, 'src/sandbox/index.ts'),\n formats: ['iife'],\n name: '<%= it.pluginClassName %>Sandbox',\n fileName: () => 'sandbox.js',\n },\n },\n})) satisfies UserConfigExport;\n\nexport default config;\n",
|
|
3592
|
-
"../../project-templates/shared/partials/plugin-webpack-dev-host-legacy.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n\n\n<%~ include('plugin-wp-legacy-externals', it) %>\n\n\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n externals: getExternals(),\n\n // <%= it.commentDevHostMode %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
|
|
3593
|
-
"../../project-templates/shared/partials/plugin-webpack-dev-host-modern.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport PluginDev from '<%= it.packageConfig.packageName %>/webpack/pluginDev';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n ? Number(process.env.PLUGIN_DEV_PORT)\n : 'auto';\n\nconst config = {\n mode: 'development',\n devtool: 'eval-source-map',\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n // <%= it.commentDevHostMode %>\n plugins: [\n new WebpackPlugin(),\n new PluginDev({ externals: false }),\n ],\n output: {\n filename: 'dev.js',\n path: path.resolve(projectRoot, 'dev-build'),\n publicPath: '/',\n },\n devServer: {\n static: [\n { directory: path.resolve(projectRoot, 'public') },\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n ],\n port: devServerPort,\n hot: false,\n liveReload: true,\n allowedHosts: 'all',\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n // <%= it.commentApiProxy %>\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n },\n },\n ],\n },\n} satisfies Configuration;\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
|
|
3610
|
+
"../../project-templates/shared/partials/plugin-webpack-dev-host-legacy.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n\n\n<%~ include('plugin-wp-legacy-externals', it) %>\n\n\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n externals: getExternals(),\n\n // <%= it.commentDevHostMode %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
|
|
3611
|
+
"../../project-templates/shared/partials/plugin-webpack-dev-host-modern.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport PluginDev from '<%= it.packageConfig.packageName %>/webpack/pluginDev';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n ? Number(process.env.PLUGIN_DEV_PORT)\n : 'auto';\n\nconst config = {\n mode: 'development',\n devtool: 'eval-source-map',\n entry: path.resolve(projectRoot, 'src/dev.tsx'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n // <%= it.commentDevHostMode %>\n plugins: [\n new WebpackPlugin(),\n new PluginDev({ externals: false }),\n ],\n output: {\n filename: 'dev.js',\n path: path.resolve(projectRoot, 'dev-build'),\n publicPath: '/',\n },\n devServer: {\n static: [\n { directory: path.resolve(projectRoot, 'public') },\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n ],\n port: devServerPort,\n hot: false,\n liveReload: true,\n allowedHosts: 'all',\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n // <%= it.commentApiProxy %>\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n },\n },\n ],\n },\n} satisfies Configuration;\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n",
|
|
3594
3612
|
"../../project-templates/shared/partials/plugin-webpack-dev-host.eta": "<% if (it.isLegacyWebpack) { %><%~ include('plugin-webpack-dev-host-legacy', it) %><% } else { %><%~ include('plugin-webpack-dev-host-modern', it) %><% } %>\n",
|
|
3595
3613
|
"../../project-templates/shared/partials/plugin-webpack-index-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> <%= it.indexHtmlTitleSuffix %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script src=\"<%= it.webpackIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
|
|
3596
3614
|
"../../project-templates/shared/partials/plugin-webpack-plugin-build.eta": "<% if (it.isLegacyWebpack) { %>\n<% if (it.pluginFormat === 'umd') { %><%~ include('plugin-wp-legacy-umd', it) %><% } else { %><%~ include('plugin-wp-legacy-module', it) %><% } %>\n<% } else { %>\n<% if (it.pluginFormat === 'umd') { %><%~ include('plugin-wp-modern-umd', it) %><% } else { %><%~ include('plugin-wp-modern-module', it) %><% } %>\n<% } %>\n",
|
|
3597
|
-
"../../project-templates/shared/partials/plugin-webpack-release-host.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n<% if (it.isLegacyWebpack) { %>\n<%~ include('plugin-wp-legacy-externals', it) %>\n<% } %>\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev-release.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n<% if (it.isLegacyWebpack) { %>\n\n externals: getExternals(),\n\n<% } %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n open: '/release.html',\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n\n",
|
|
3615
|
+
"../../project-templates/shared/partials/plugin-webpack-release-host.eta": "import fs from 'node:fs';\n\nimport path from 'node:path';\n\nimport { fileURLToPath } from 'node:url';\n\nimport type { Configuration } from 'webpack';\n\nimport WebpackPlugin from '<%= it.packageConfig.packageName %>/webpack';\nimport { mergeHostEditorDevServer } from '../scripts/hostDevServerHeaders.ts';\n\n\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\nconst projectRoot = path.resolve(__dirname, '..');\n\n<% if (it.isLegacyWebpack) { %>\n<%~ include('plugin-wp-legacy-externals', it) %>\n<% } %>\n\nconst devServerPort = process.env.PLUGIN_DEV_PORT\n\n ? Number(process.env.PLUGIN_DEV_PORT)\n\n : 'auto';\n\n\n\nconst config = {\n\n mode: 'development',\n\n devtool: 'eval-source-map',\n\n entry: path.resolve(projectRoot, 'src/dev-release.tsx'),\n\n module: {\n\n rules: [\n\n {\n\n test: /\\.tsx?$/,\n\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n\n exclude: /node_modules/,\n\n },\n\n {\n\n test: /\\.(html|css)$/,\n\n resourceQuery: /raw/,\n\n type: 'asset/source',\n\n },\n\n ],\n\n },\n\n resolve: {\n\n extensions: ['.ts', '.tsx', '.js'],\n\n },\n\n<% if (it.isLegacyWebpack) { %>\n\n externals: getExternals(),\n\n<% } %>\n\n plugins: [\n\n new WebpackPlugin(),\n\n ],\n\n output: {\n\n filename: 'dev.js',\n\n path: path.resolve(projectRoot, 'dev-build'),\n\n publicPath: '/',\n\n },\n\n devServer: {\n\n static: [\n\n { directory: path.resolve(projectRoot, 'public') },\n\n { directory: path.resolve(projectRoot, 'dist'), publicPath: '/dist' },\n\n ],\n\n port: devServerPort,\n\n open: '/release.html',\n\n hot: false,\n\n liveReload: true,\n\n allowedHosts: 'all',\n\n proxy: [\n\n {\n\n context: ['/api'],\n\n target: <%~ JSON.stringify(it.packageConfig.openApiBaseUrl || '') %>,\n\n secure: false,\n\n changeOrigin: true,\n\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n\n onProxyReq: (proxyReq) => {\n\n // <%= it.commentApiProxy %>\n\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.packageConfig.openApiOrigin || it.packageConfig.openApiBaseUrl || '') %>);\n\n },\n\n },\n\n ],\n\n },\n\n} satisfies Configuration;\n\n\n\nmergeHostEditorDevServer(config);\n\nexport default config;\n\n",
|
|
3598
3616
|
"../../project-templates/shared/partials/plugin-webpack-release-html.eta": "<!doctype html>\n<html lang=\"<%= it.htmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.indexHtmlTitle %> release host</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script src=\"<%= it.webpackIndexScriptSrc %>\"><\/script>\n </body>\n</html>\n",
|
|
3599
3617
|
"../../project-templates/shared/partials/plugin-webpack-sandbox-build.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Configuration } from 'webpack';\n\ninterface WebpackArgv {\n mode?: string;\n}\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = (_env: Record<string, never>, argv: WebpackArgv = {}) => {\n const isDev = argv.mode !== 'production';\n\n return {\n mode: isDev ? 'development' : 'production',\n devtool: 'source-map',\n entry: path.resolve(projectRoot, 'src/sandbox/index.ts'),\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n use: { loader: 'ts-loader', options: { transpileOnly: true } },\n exclude: /node_modules/,\n },\n {\n test: /\\.(html|css)$/,\n resourceQuery: /raw/,\n type: 'asset/source',\n },\n ],\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js'],\n },\n optimization: {\n minimize: !isDev,\n },\n output: {\n filename: 'sandbox.js',\n path: path.resolve(projectRoot, isDev ? 'public' : 'dist'),\n clean: false,\n iife: true,\n },\n } satisfies Configuration;\n};\n\nexport default config;\n",
|
|
3600
3618
|
"../../project-templates/shared/partials/plugin-wp-legacy-externals.eta": "type LegacyExternalValue = string | string[];\ntype LegacyExternals = Record<string, LegacyExternalValue>;\n\nfunction readJsonSync(relativePath: string): LegacyExternals {\n return JSON.parse(fs.readFileSync(path.resolve(projectRoot, relativePath), 'utf8')) as LegacyExternals;\n}\n\nfunction getExternal(packageName: string): LegacyExternals {\n try {\n return readJsonSync(`node_modules/${packageName}/externals.json`);\n } catch {\n return {};\n }\n}\n\nfunction mergeLegacyExternals(): LegacyExternals {\n return {\n ...getExternal('<%= it.packageConfig.extensionsApiPackageName %>'),\n ...getExternal('<%= it.packageConfig.extensionsReactPackageName %>'),\n ...getExternal('<%= it.packageConfig.extensionsSandboxPackageName %>'),\n ...getExternal('<%= it.packageConfig.uiKitPackageName %>'),\n };\n}\n\n/** simple_plugin style: raw externals.json merge (`[\"promise __ns__.modules\", \"Export\"]`). */\nfunction getExternals(): LegacyExternals {\n return mergeLegacyExternals();\n}\n",
|
|
@@ -3611,36 +3629,36 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3611
3629
|
"../../project-templates/shared/partials/stand-dev-host-vite-subpath.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createViteStandConfig } from './lib/createViteStandConfig.ts';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createViteStandConfig({\n projectRoot,\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n closedLoop: <%= it.standClosedLoop %>,\n plugins: [VitePlugin({ outputFolder: <%~ JSON.stringify(it.standViteOutputFolder) %> })],\n extraServerMiddlewares: [],\n build: {\n rollupOptions: {\n input: path.resolve(projectRoot, 'advanced', 'subpath', 'index.html'),\n },\n },\n});\n",
|
|
3612
3630
|
"../../project-templates/shared/partials/stand-dev-host-vite-umd.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createRequire } from 'node:module';\nimport { createViteStandConfig } from './lib/createViteStandConfig.ts';\nimport { createUmdServeMiddleware } from './lib/umdServeMiddleware.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst require = createRequire(import.meta.url);\nconst umdPackageRoot = path.dirname(require.resolve('<%~ it.packageName %>/package.json'));\nconst umdMw = createUmdServeMiddleware({ packageRoot: umdPackageRoot, publicPath: <%~ JSON.stringify(it.standUmdPublicPath) %> });\n\nexport default createViteStandConfig({\n projectRoot,\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n closedLoop: <%= it.standClosedLoop %>,\n plugins: [],\n extraServerMiddlewares: [umdMw],\n});\n",
|
|
3613
3631
|
"../../project-templates/shared/partials/stand-dev-host-vite.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createViteStandConfig } from './lib/createViteStandConfig.ts';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createViteStandConfig({\n projectRoot,\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n closedLoop: <%= it.standClosedLoop %>,\n plugins: [VitePlugin()],\n extraServerMiddlewares: [],\n});\n\n",
|
|
3614
|
-
"../../project-templates/shared/partials/stand-dev-host-webpack-subpath.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>({ publicPath: <%~ JSON.stringify(it.standRoutePath) %> })],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public', 'advanced', 'subpath'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n umd: umdOpts,\n});\n\nexport default config;\n",
|
|
3615
|
-
"../../project-templates/shared/partials/stand-dev-host-webpack-umd.eta": "import path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst require = createRequire(import.meta.url);\nconst umdPackageRoot = path.dirname(require.resolve(<%~ JSON.stringify(it.packageName + '/package.json') %>));\nconst umdOpts = { packageRoot: umdPackageRoot, publicPath: <%~ JSON.stringify(it.standUmdPublicPath) %> };\n\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
|
|
3616
|
-
"../../project-templates/shared/partials/stand-dev-host-webpack.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>()],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
|
|
3632
|
+
"../../project-templates/shared/partials/stand-dev-host-webpack-subpath.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>({ publicPath: <%~ JSON.stringify(it.standRoutePath) %> })],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public', 'advanced', 'subpath'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n umd: umdOpts,\n});\n\nexport default config;\n",
|
|
3633
|
+
"../../project-templates/shared/partials/stand-dev-host-webpack-umd.eta": "import path from 'node:path';\nimport { createRequire } from 'node:module';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst require = createRequire(import.meta.url);\nconst umdPackageRoot = path.dirname(require.resolve(<%~ JSON.stringify(it.packageName + '/package.json') %>));\nconst umdOpts = { packageRoot: umdPackageRoot, publicPath: <%~ JSON.stringify(it.standUmdPublicPath) %> };\n\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
|
|
3634
|
+
"../../project-templates/shared/partials/stand-dev-host-webpack.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createWebpackStandConfig } from './lib/createWebpackStandConfig.ts';\nimport <%= it.standWebpackPluginClassName %> from '<%~ it.packageName %>/webpack';\n\nconst umdOpts = null;\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nconst config = createWebpackStandConfig({\n projectRoot,\n plugins: [new <%= it.standWebpackPluginClassName %>()],\n outputPublicPath: <%~ JSON.stringify(it.standRoutePath) %>,\n staticDirectory: path.resolve(projectRoot, 'public'),\n open: <%~ JSON.stringify(it.standRoutePath) %>,\n<% if (it.standClosedLoop) { %>\n proxy: [],\n<% } else { %>\n proxy: [\n {\n context: ['/api'],\n target: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n pathRewrite: { '^/api': '' },\n onProxyReq: (proxyReq) => {\n proxyReq.setHeader('origin', <%~ JSON.stringify(it.standOpenApiOrigin) %>);\n },\n },\n ],\n<% } %>\n umd: umdOpts,\n});\n\nexport default config;\n",
|
|
3617
3635
|
"../../project-templates/shared/partials/stand-dev-storage-middleware.eta": "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport formidable from 'formidable';\n\ninterface StorageItem {\n id: string;\n name: string;\n folderId: string;\n isFolder: boolean;\n size?: number;\n date: string;\n type?: string;\n url?: string;\n}\n\ninterface StorageRequestBody {\n name?: string;\n newName?: string;\n parentId?: string;\n parentid?: string;\n folderId?: string;\n targetFolderId?: string;\n url?: string;\n path?: string;\n id?: string;\n}\n\nconst STORAGE_DIR = path.resolve(process.cwd(), 'storage');\nconst BASE = '/dev-storage';\n\nfunction ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\nfunction sanitizePath(relativePath: string): string {\n if (!relativePath || relativePath === '/' || relativePath === '.') {\n return '';\n }\n\n return path.normalize(relativePath).replace(/^(\\.\\.(\\/|\\\\|$))+/, '').replace(/\\\\/g, '/').trim();\n}\n\nfunction resolvePath(relativePath: string): string | null {\n const safe = sanitizePath(relativePath);\n const full = path.join(STORAGE_DIR, safe);\n const resolved = path.resolve(full);\n if (!resolved.startsWith(path.resolve(STORAGE_DIR))) {\n return null;\n }\n\n return resolved;\n}\n\nfunction toFileItem(fullPath: string): StorageItem {\n const stat = fs.statSync(fullPath);\n const name = path.basename(fullPath);\n const rel = path.relative(STORAGE_DIR, fullPath).replace(/\\\\/g, '/');\n const folderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n\n return {\n id: rel,\n name,\n folderId,\n isFolder: stat.isDirectory(),\n size: stat.isFile() ? stat.size : undefined,\n date: stat.mtime.toISOString(),\n type: stat.isFile() ? getMimeType(name) : undefined,\n };\n}\n\nfunction getMimeType(name: string): string {\n const ext = path.extname(name).toLowerCase();\n const types = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.pdf': 'application/pdf',\n '.zip': 'application/zip',\n } as const;\n\n return types[ext as keyof typeof types] || 'application/octet-stream';\n}\n\nfunction normalizeJsonBody(rawBody: string): StorageRequestBody {\n if (!rawBody) {\n return {};\n }\n\n const parsed = JSON.parse(rawBody) as Partial<Record<keyof StorageRequestBody, string>>;\n return {\n name: typeof parsed.name === 'string' ? parsed.name : undefined,\n newName: typeof parsed.newName === 'string' ? parsed.newName : undefined,\n parentId: typeof parsed.parentId === 'string' ? parsed.parentId : undefined,\n parentid: typeof parsed.parentid === 'string' ? parsed.parentid : undefined,\n folderId: typeof parsed.folderId === 'string' ? parsed.folderId : undefined,\n targetFolderId: typeof parsed.targetFolderId === 'string' ? parsed.targetFolderId : undefined,\n url: typeof parsed.url === 'string' ? parsed.url : undefined,\n path: typeof parsed.path === 'string' ? parsed.path : undefined,\n id: typeof parsed.id === 'string' ? parsed.id : undefined,\n };\n}\n\nfunction parseJsonBody(req: IncomingMessage): Promise<StorageRequestBody> {\n return new Promise((resolve) => {\n let body = '';\n req.on('data', (chunk: Buffer | string) => {\n body += typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n });\n req.on('end', () => {\n try {\n resolve(normalizeJsonBody(body));\n } catch {\n resolve({});\n }\n });\n });\n}\n\nfunction sendJson<T>(res: ServerResponse, data: T, status = 200): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(data));\n}\n\nfunction sendStorageError(res: ServerResponse, error: unknown, status = 500): void {\n const message = error instanceof Error ? error.message : String(error);\n sendJson(res, { error: message }, status);\n}\n\nfunction runStorageHandler(\n res: ServerResponse,\n handler: () => Promise<void>,\n): void {\n void handler().catch((error) => {\n sendStorageError(res, error);\n });\n}\n\nfunction resolveItemPath(body: StorageRequestBody, fallbackPath = ''): string {\n return (fallbackPath || body.path || body.id || '').trim();\n}\n\nfunction isValidItemName(name: string): boolean {\n return Boolean(name) && !/[\\\\/:*?\"<>|]/.test(name);\n}\n\nfunction sendItemsResponse(res: ServerResponse, items: StorageItem[]): void {\n sendJson(res, {\n items,\n pagination: { page: 1, limit: 1000, total: items.length, totalPages: 1 },\n });\n}\n\nasync function handleGetItems(_req: IncomingMessage, res: ServerResponse, url: string): Promise<void> {\n const folderId = (new URL(url, 'http://x').searchParams.get('folderId') || '').trim();\n const dir = folderId ? resolvePath(folderId) : path.resolve(STORAGE_DIR);\n if (!dir || !fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {\n sendItemsResponse(res, []);\n return;\n }\n\n const items = fs.readdirSync(dir).map((name) => toFileItem(path.join(dir, name)));\n sendItemsResponse(res, items);\n}\n\nasync function handleCreateFolder(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const name = (body.name || '').trim();\n const parentId = (body.parentId ?? body.parentid ?? '').trim();\n if (!name || /[\\\\/:*?\"<>|]/.test(name)) {\n sendJson(res, { error: 'Invalid folder name' }, 400);\n return;\n }\n\n const parentDir = parentId ? resolvePath(parentId) : STORAGE_DIR;\n if (!parentDir || !fs.existsSync(parentDir)) {\n sendJson(res, { error: 'Parent folder not found' }, 404);\n return;\n }\n\n const folderPath = path.join(parentDir, name);\n ensureDir(folderPath);\n const rel = path.relative(STORAGE_DIR, folderPath).replace(/\\\\/g, '/');\n const folderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n sendJson(res, {\n id: rel,\n name,\n folderId,\n isFolder: true,\n date: fs.statSync(folderPath).mtime.toISOString(),\n });\n}\n\nfunction readFormField(field: string | string[] | undefined): string {\n if (typeof field === 'string') {\n return field.trim();\n }\n\n if (Array.isArray(field) && typeof field[0] === 'string') {\n return field[0].trim();\n }\n\n return '';\n}\n\nasync function handleUpload(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const form = formidable({ multiples: true });\n const [fields, files] = await new Promise<[formidable.Fields, formidable.Files]>((resolve, reject) => {\n form.parse(req, (error, parsedFields, parsedFiles) => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve([parsedFields, parsedFiles]);\n });\n });\n\n const folderId = readFormField(fields.folderId);\n const targetDir = folderId ? resolvePath(folderId) : STORAGE_DIR;\n if (!targetDir || !fs.existsSync(targetDir)) {\n sendJson(res, { error: 'Folder not found' }, 404);\n return;\n }\n\n const fileEntries = Array.isArray(files.file)\n ? files.file\n : files.file\n ? [files.file]\n : [];\n const items: StorageItem[] = [];\n\n for (const file of fileEntries) {\n if (!file.filepath || !fs.existsSync(file.filepath)) {\n continue;\n }\n\n const originalName = file.originalFilename || file.newFilename || path.basename(file.filepath);\n const name = originalName.replace(/[\\\\/:*?\"<>|]/g, '_');\n const destination = path.join(targetDir, name);\n fs.copyFileSync(file.filepath, destination);\n\n const rel = path.relative(STORAGE_DIR, destination).replace(/\\\\/g, '/');\n const responseFolderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n items.push({\n id: rel,\n name,\n folderId: responseFolderId,\n isFolder: false,\n size: fs.statSync(destination).size,\n date: fs.statSync(destination).mtime.toISOString(),\n type: getMimeType(name),\n });\n }\n\n if (items.length === 0) {\n sendJson(res, { error: 'No files received' }, 400);\n return;\n }\n\n sendJson(res, { items, success: true });\n}\n\nasync function handleUploadByUrl(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const url = (body.url || '').trim();\n const folderId = (body.folderId || '').trim();\n if (!url) {\n sendJson(res, { error: 'Missing url' }, 400);\n return;\n }\n\n const targetDir = folderId ? resolvePath(folderId) : STORAGE_DIR;\n if (!targetDir || !fs.existsSync(targetDir)) {\n sendJson(res, { error: 'Folder not found' }, 404);\n return;\n }\n\n try {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error('Fetch failed');\n }\n\n const buffer = Buffer.from(await response.arrayBuffer());\n const name = (url.split('/').pop() || 'file').split('?')[0] || 'file';\n const destination = path.join(targetDir, name);\n fs.writeFileSync(destination, buffer);\n\n const rel = path.relative(STORAGE_DIR, destination).replace(/\\\\/g, '/');\n const responseFolderId = path.dirname(rel) === '.' ? '' : path.dirname(rel).replace(/\\\\/g, '/');\n sendJson(res, {\n id: rel,\n name,\n folderId: responseFolderId,\n isFolder: false,\n size: buffer.length,\n date: fs.statSync(destination).mtime.toISOString(),\n type: getMimeType(name),\n url: `/dev-storage/file/${encodeURIComponent(rel)}`,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n sendJson(res, { error: message }, 500);\n }\n}\n\nasync function handleDeleteItem(req: IncomingMessage, res: ServerResponse, pathOverride = ''): Promise<void> {\n let targetPath = pathOverride.trim();\n\n if (!targetPath) {\n const pathParam = (new URL(req.url || '/', 'http://x').searchParams.get('path') || '').trim();\n const body = await parseJsonBody(req);\n targetPath = pathParam || (body.path || body.id || '').trim();\n }\n\n if (!targetPath) {\n sendJson(res, { error: 'Missing path' }, 400);\n return;\n }\n\n const fullPath = resolvePath(targetPath);\n if (!fullPath || !fs.existsSync(fullPath)) {\n sendJson(res, { error: 'Not found' }, 404);\n return;\n }\n\n fs.rmSync(fullPath, { recursive: true });\n sendJson(res, { success: true });\n}\n\nasync function handleRenameItem(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const targetPath = resolveItemPath(body);\n const newName = (body.newName || body.name || '').trim();\n if (!targetPath) {\n sendJson(res, { error: 'Missing path' }, 400);\n return;\n }\n if (!isValidItemName(newName)) {\n sendJson(res, { error: 'Invalid item name' }, 400);\n return;\n }\n\n const fullPath = resolvePath(targetPath);\n if (!fullPath || !fs.existsSync(fullPath)) {\n sendJson(res, { error: 'Not found' }, 404);\n return;\n }\n\n const destination = path.join(path.dirname(fullPath), newName);\n if (fs.existsSync(destination)) {\n sendJson(res, { error: 'Target already exists' }, 409);\n return;\n }\n\n fs.renameSync(fullPath, destination);\n sendJson(res, toFileItem(destination));\n}\n\nasync function handleMoveItem(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await parseJsonBody(req);\n const targetPath = resolveItemPath(body);\n const folderId = (body.targetFolderId ?? body.folderId ?? '').trim();\n if (!targetPath) {\n sendJson(res, { error: 'Missing path' }, 400);\n return;\n }\n\n const fullPath = resolvePath(targetPath);\n if (!fullPath || !fs.existsSync(fullPath)) {\n sendJson(res, { error: 'Not found' }, 404);\n return;\n }\n\n const targetDir = folderId ? resolvePath(folderId) : STORAGE_DIR;\n if (!targetDir || !fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {\n sendJson(res, { error: 'Target folder not found' }, 404);\n return;\n }\n\n const destination = path.join(targetDir, path.basename(fullPath));\n if (fs.existsSync(destination)) {\n sendJson(res, { error: 'Target already exists' }, 409);\n return;\n }\n\n fs.renameSync(fullPath, destination);\n sendJson(res, toFileItem(destination));\n}\n\nfunction handleGetFile(res: ServerResponse, pathPart: string): void {\n const decoded = decodeURIComponent(pathPart);\n const fullPath = resolvePath(decoded);\n if (!fullPath || !fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n res.writeHead(404);\n res.end();\n return;\n }\n\n const stream = fs.createReadStream(fullPath);\n const mime = getMimeType(path.basename(fullPath));\n res.writeHead(200, { 'Content-Type': mime });\n stream.pipe(res);\n}\n\nexport default function devStorageMiddleware() {\n ensureDir(STORAGE_DIR);\n\n return (req: IncomingMessage, res: ServerResponse, next: () => void): void => {\n if (!req.url || !req.url.startsWith(BASE)) {\n next();\n return;\n }\n\n const pathPart = req.url.slice(BASE.length).replace(/^\\//, '');\n const method = req.method || 'GET';\n\n if (method === 'GET' && (pathPart === 'items' || pathPart.startsWith('items?'))) {\n runStorageHandler(res, () => handleGetItems(req, res, req.url || ''));\n return;\n }\n\n if (method === 'GET' && pathPart.startsWith('file/')) {\n handleGetFile(res, pathPart.slice(5));\n return;\n }\n\n if (method === 'POST' && pathPart === 'folder') {\n runStorageHandler(res, () => handleCreateFolder(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'upload') {\n runStorageHandler(res, () => handleUpload(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'upload-by-url') {\n runStorageHandler(res, () => handleUploadByUrl(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'rename') {\n runStorageHandler(res, () => handleRenameItem(req, res));\n return;\n }\n\n if (method === 'POST' && pathPart === 'move') {\n runStorageHandler(res, () => handleMoveItem(req, res));\n return;\n }\n\n if (method === 'DELETE' && pathPart === 'item') {\n runStorageHandler(res, () => handleDeleteItem(req, res));\n return;\n }\n\n if (method === 'DELETE' && pathPart.startsWith('item/')) {\n runStorageHandler(res, () => handleDeleteItem(req, res, decodeURIComponent(pathPart.slice(5))));\n return;\n }\n\n next();\n };\n}\n",
|
|
3618
3636
|
"../../project-templates/shared/partials/stand-editor-config-resource-proxy.eta": "import type { Config } from '<%~ it.packageName %>';\nimport { demoStandConfig } from './demoStandConfig';\n\nconst defaultCdnBase = <%~ JSON.stringify(it.standCdnUrl) %>.replace(/\\/+$/, '');\nconst cdnProjectId = demoStandConfig.cdnSampleProjectId;\nconst proxyCdnEnabled = <%= JSON.stringify(it.standProxyCdnEnabled) %>;\n\nfunction getProxyBase() {\n const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost:<%= it.standDevServerPort %>';\n return `${origin}/proxy`;\n}\n\nfunction buildProxyRule(proxyBase: string, routeKey: string) {\n return {\n proxyBase: `${proxyBase}/${routeKey}`,\n rewrite: '{path}?proxy_url={origin}{search}{hash}',\n };\n}\n\nconst directHostDemoHostname = <%~ JSON.stringify(it.resourceProxyDemoDirectHost) %>;\n\nfunction createResourceProxyEditorConfig(): Partial<Config> {\n const proxyBase = getProxyBase();\n\n const resourceProxy = [\n {\n id: 'cdn',\n match: `${defaultCdnBase}/${cdnProjectId}/{path}`,\n proxyBase: `${proxyBase}/cdn`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'stock-images-api',\n match: 'https://api.unsplash.com/{path}',\n ...buildProxyRule(proxyBase, 'stock-images-api'),\n },\n {\n id: 'stock-images-cdn',\n match: 'https://images.unsplash.com/{path}',\n ...buildProxyRule(proxyBase, 'stock-images-cdn'),\n },\n {\n id: 'generic-primary',\n ...buildProxyRule(proxyBase, 'generic-primary'),\n },\n {\n id: 'generic-backup',\n ...buildProxyRule(proxyBase, 'generic-backup'),\n },\n ];\n\n const backendProxy = [\n {\n id: 'em-files-primary',\n match: ['{origin}/api/wp-json/em-files/{path}', '{origin}/wp-json/em-files/{path}'],\n proxyBase: `${proxyBase}/em-files-primary`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'em-files-backup',\n match: ['{origin}/api/wp-json/em-files/{path}', '{origin}/wp-json/em-files/{path}'],\n proxyBase: `${proxyBase}/em-files-backup`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'ai-primary',\n match: ['{origin}/api/wp-json/ai-generator/{path}', '{origin}/wp-json/ai-generator/{path}'],\n proxyBase: `${proxyBase}/ai-primary`,\n rewrite: '{matched_path}{search}{hash}',\n },\n {\n id: 'ai-backup',\n match: ['{origin}/api/wp-json/ai-generator/{path}', '{origin}/wp-json/ai-generator/{path}'],\n proxyBase: `${proxyBase}/ai-backup`,\n rewrite: '{matched_path}{search}{hash}',\n },\n ];\n\n return {\n mode: 'pro',\n locale: <%~ JSON.stringify(it.standEditorLocale) %>,\n imageCenterStockEnabled: true,\n imageCenterGifEnabled: true,\n imageCenterIconStockEnabled: true,\n imageCenterLocalUploadEnabled: true,\n resourceProxy,\n backendProxy,\n resourceProxyPolicy: {\n inheritDefaults: false,\n directHosts: [directHostDemoHostname],\n recoveryTtlMs: 300000,\n proxyBlobFetch: true,\n proxyImgSrc: true,\n // Intentional for lab: same-origin /dev-storage assets also exercise /proxy routes.\n proxySameOrigin: true,\n proxyCdn: proxyCdnEnabled,\n proxyStockImages: true,\n },\n backendProxyPolicy: {\n proxyEmFiles: true,\n proxyAi: true,\n },\n fileManager: {\n previewFallbackToFileUrl: true,\n dedupeUploadNamesOnClient: true,\n },\n };\n}\n\nexport const editorConfig = createResourceProxyEditorConfig();\n",
|
|
3619
3637
|
"../../project-templates/shared/partials/stand-editor-config.eta": "import type { Config } from '<%~ it.packageName %>';\n\nconst mergeTagItems = [\n {\n label: 'Profile',\n value: 'profile',\n children: [\n { label: 'First name', value: 'profile.firstName' },\n { label: 'Last name', value: 'profile.lastName' },\n { label: 'Email', value: 'profile.email' },\n ],\n },\n {\n label: 'Company',\n value: 'company',\n children: [\n { label: 'Name', value: 'company.name' },\n { label: 'Industry', value: 'company.industry' },\n { label: 'Website', value: 'company.website' },\n ],\n },\n {\n label: 'Campaign',\n value: 'campaign',\n children: [\n { label: 'Title', value: 'campaign.title' },\n { label: 'Promo code', value: 'campaign.promoCode' },\n { label: 'CTA URL', value: 'campaign.ctaUrl' },\n ],\n },\n];\n\nconst baseEditorConfig = {\n theme: 'light',\n locale: 'ru_RU',\n autosaveTimeout: 15000,\n commonStylesEnabled: true,\n mergeTagsShow: true,\n imageCenterFileManagerView: true,\n fileManager: {\n defaultFolderName: 'demo-assets',\n enableMoveFolder: true,\n enableEdit: true,\n enableTrash: true,\n enableCopyFile: true,\n enableCopyFolder: true,\n },\n mergeTags: {\n syntax: ['{{' + '%value%' + '}}'],\n items: mergeTagItems,\n },\n} satisfies Partial<Config>;\n\nexport function createEditorConfig(): Partial<Config> {\n return baseEditorConfig;\n}\n\nexport const editorConfig = createEditorConfig();\n",
|
|
3620
|
-
"../../project-templates/shared/partials/stand-ensure-locale-script.eta": "import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { editorConfig } from '../src/dev/editorConfig';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst locale = String(editorConfig.locale || '').trim();\nconst localeDir = path.resolve(projectRoot, 'public', 'locales');\nconst localeFilePath = path.resolve(localeDir, `${locale}.po`);\nconst apiBaseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\nconst localeUrl = new URL(`wp-json/translations/v1/react_app/${encodeURIComponent(locale)}`, `${apiBaseUrl.replace(/\\/+$/, '')}/`).href;\n\nfunction normalizeLocaleText(text: string): string {\n const normalized = text.replace(/\\uFEFF/g, '').replace(/\\r\\n?/g, '\\n');\n return normalized.endsWith('\\n') ? normalized : `${normalized}\\n`;\n}\n\nfunction isPoCatalog(text: string): boolean {\n const normalized = normalizeLocaleText(text);\n return normalized.startsWith('msgid \"\"\\nmsgstr \"\"\\n') || normalized.includes('\\n\"Plural-Forms:');\n}\n\nasync function ensureLocaleFile(): Promise<void> {\n if (!locale) {\n throw new Error('editorConfig.locale is required for the closed-loop stand.');\n }\n\n try {\n const existing = await fs.readFile(localeFilePath, 'utf8');\n if (existing.trim() && isPoCatalog(existing)) {\n console.log(`[stand-locale] using existing public/locales/${locale}.po`);\n return;\n }\n } catch {\n // Download on first start when the file is absent.\n }\n\n const res = await fetch(localeUrl);\n if (!res.ok) {\n throw new Error(`Failed to download locale ${locale}: ${res.status} ${res.statusText}`);\n }\n\n const localeText = await res.text();\n if (!isPoCatalog(localeText)) {\n throw new Error(`Downloaded locale ${locale} is not a gettext catalog.`);\n }\n\n await fs.mkdir(localeDir, { recursive: true });\n await fs.writeFile(localeFilePath, normalizeLocaleText(localeText), 'utf8');\n console.log(`[stand-locale] saved public/locales/${locale}.po`);\n}\n\nensureLocaleFile().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[stand-locale] ${message}`);\n process.exit(1);\n});\n",
|
|
3621
|
-
"../../project-templates/shared/partials/stand-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n\n const formData = new
|
|
3622
|
-
"../../project-templates/shared/partials/stand-host-closed.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst baseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-closed-loop',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n\n const instance = await <%= it.standProductApiName %>.init({\n standaloneKey: standaloneCredentials.standaloneKey,\n baseUrl,\n handleReadLocale: async (locale: string) => {\n const url = `/locales/${encodeURIComponent(locale)}.po`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`Locale file not found: ${url}`);\n }\n return res.text();\n },\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostClosedLoopDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n
|
|
3638
|
+
"../../project-templates/shared/partials/stand-ensure-locale-script.eta": "import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { editorConfig } from '../src/dev/editorConfig';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\nconst locale = String(editorConfig.locale || '').trim();\nconst localeDir = path.resolve(projectRoot, 'public', 'locales');\nconst localeFilePath = path.resolve(localeDir, `${locale}.po`);\nconst apiBaseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\nconst localeUrl = new URL(`wp-json/translations/v1/react_app/${encodeURIComponent(locale)}`, `${apiBaseUrl.replace(/\\/+$/, '')}/`).href;\n\nfunction normalizeLocaleText(text: string): string {\n const normalized = text.replace(/\\uFEFF/g, '').replace(/\\r\\n?/g, '\\n');\n return normalized.endsWith('\\n') ? normalized : `${normalized}\\n`;\n}\n\nfunction isPoCatalog(text: string): boolean {\n const normalized = normalizeLocaleText(text);\n return normalized.startsWith('msgid \"\"\\nmsgstr \"\"\\n') || normalized.includes('\\n\"Plural-Forms:');\n}\n\n// The translations endpoint answers with application/json: the .po text arrives as a JSON string.\nfunction unwrapJsonCatalog(body: string, contentType: string | null): string {\n const trimmed = body.trim();\n const isJson = /\\bjson\\b/i.test(contentType || '') || trimmed.startsWith('\"');\n if (!isJson) {\n return body;\n }\n try {\n const parsed: unknown = JSON.parse(trimmed);\n return typeof parsed === 'string' ? parsed : body;\n } catch {\n return body;\n }\n}\n\nasync function ensureLocaleFile(): Promise<void> {\n if (!locale) {\n throw new Error('editorConfig.locale is required for the closed-loop stand.');\n }\n\n try {\n const existing = await fs.readFile(localeFilePath, 'utf8');\n if (existing.trim() && isPoCatalog(existing)) {\n console.log(`[stand-locale] using existing public/locales/${locale}.po`);\n return;\n }\n } catch {\n // Download on first start when the file is absent.\n }\n\n const res = await fetch(localeUrl);\n if (!res.ok) {\n throw new Error(`Failed to download locale ${locale}: ${res.status} ${res.statusText}`);\n }\n\n const localeText = unwrapJsonCatalog(await res.text(), res.headers.get('content-type'));\n if (!isPoCatalog(localeText)) {\n throw new Error(`Downloaded locale ${locale} is not a gettext catalog.`);\n }\n\n await fs.mkdir(localeDir, { recursive: true });\n await fs.writeFile(localeFilePath, normalizeLocaleText(localeText), 'utf8');\n console.log(`[stand-locale] saved public/locales/${locale}.po`);\n}\n\nensureLocaleFile().catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`[stand-locale] ${message}`);\n process.exit(1);\n});\n",
|
|
3639
|
+
"../../project-templates/shared/partials/stand-get-auth-token.eta": "import { hasOAuthCredentials, oauthCredentials } from './oauthCredentials';\n\nexport async function getAuthToken() {\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n\n const formData = new URLSearchParams();\n formData.append('grant_type', 'client_credentials');\n formData.append('client_id', oauthCredentials.clientId);\n formData.append('client_secret', oauthCredentials.clientSecret);\n\n const response = await fetch('/api/oauth/token', {\n method: 'POST',\n body: formData,\n redirect: 'follow',\n });\n const payload = await response.json().catch(() => null);\n\n if (!response.ok || !payload || typeof payload.access_token !== 'string') {\n throw new Error(\n <%~ JSON.stringify(it.devAuthOauthTokenFetchFailed) %>,\n );\n }\n\n return payload.access_token;\n}\n",
|
|
3640
|
+
"../../project-templates/shared/partials/stand-host-closed.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst baseUrl = <%~ JSON.stringify(it.standClosedLoopBaseUrl) %>;\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-closed-loop',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n\n const instance = await <%= it.standProductApiName %>.init({\n standaloneKey: standaloneCredentials.standaloneKey,\n baseUrl,\n handleReadLocale: async (locale: string) => {\n const url = `/locales/${encodeURIComponent(locale)}.po`;\n const res = await fetch(url);\n if (!res.ok) {\n throw new Error(`Locale file not found: ${url}`);\n }\n return res.text();\n },\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostClosedLoopDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3623
3641
|
"../../project-templates/shared/partials/stand-host-dev-server-webpack.eta": "/**\n * webpack-dev-server 5.2+ blocks cross-site script loads (403) unless assets\n * declare CORP cross-origin. Required for sandboxed editor iframe (no allow-same-origin).\n */\nexport const HOST_EDITOR_ASSET_HEADERS = Object.freeze({\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n});\n\ntype DevServerConfig = {\n allowedHosts?: unknown;\n headers?: Record<string, string>;\n devMiddleware?: { headers?: Record<string, string> } & Record<string, unknown>;\n setupMiddlewares?: SetupMiddlewaresFn;\n} & Record<string, unknown>;\n\ntype WebpackConfig = {\n devServer?: DevServerConfig;\n};\n\ntype DevServerLike = {\n app?: {\n use: (middleware: HostEditorHeaderMiddleware) => void;\n };\n};\n\ntype HostEditorHeaderMiddleware = (\n req: unknown,\n res: { setHeader: (name: string, value: string) => void },\n next: () => void,\n) => void;\n\ntype SetupMiddlewaresFn = (\n middlewares: unknown[],\n devServer: DevServerLike,\n) => unknown[];\n\nexport function createHostEditorDevServerHeaderMiddleware(): HostEditorHeaderMiddleware {\n return (_req, res, next) => {\n for (const [key, value] of Object.entries(HOST_EDITOR_ASSET_HEADERS)) {\n res.setHeader(key, value);\n }\n next();\n };\n}\n\nexport function chainHostEditorDevServerSetupMiddleware(\n setupMiddlewares?: SetupMiddlewaresFn,\n): SetupMiddlewaresFn {\n return (middlewares, devServer) => {\n devServer.app?.use(createHostEditorDevServerHeaderMiddleware());\n if (typeof setupMiddlewares === 'function') {\n return setupMiddlewares(middlewares, devServer);\n }\n return middlewares;\n };\n}\n\nexport function mergeHostEditorDevServer(config: WebpackConfig): WebpackConfig {\n const existing = config.devServer || {};\n const existingDevMiddleware = existing.devMiddleware || {};\n\n config.devServer = {\n ...existing,\n allowedHosts: existing.allowedHosts ?? 'all',\n headers: {\n ...(existing.headers || {}),\n ...HOST_EDITOR_ASSET_HEADERS,\n },\n devMiddleware: {\n ...existingDevMiddleware,\n headers: {\n ...(existingDevMiddleware.headers || {}),\n ...HOST_EDITOR_ASSET_HEADERS,\n },\n },\n setupMiddlewares: chainHostEditorDevServerSetupMiddleware(existing.setupMiddlewares),\n };\n\n return config;\n}\n",
|
|
3624
|
-
"../../project-templates/shared/partials/stand-host-oauth-default-banners.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-default-banners',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{
|
|
3625
|
-
"../../project-templates/shared/partials/stand-host-oauth.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-oauth',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{
|
|
3626
|
-
"../../project-templates/shared/partials/stand-host-react-adapter.eta": "import { createRoot } from 'react-dom/client';\nimport <%= it.standReactAdapterComponentName %> from '<%~ it.standReactAdapterPackage %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('stand-demo-email-id', it) %>\n\nfunction StandHostApp() {\n return (\n <div style={{
|
|
3627
|
-
"../../project-templates/shared/partials/stand-host-resource-proxy-body.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\n<% if (it.standResourceProxyAuth === 'oauth') { %>\nimport { hasOAuthCredentials } from './dev/oauthCredentials';\n<% } else { %>\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\n<% } %>\nimport { demoStandConfig, hasDemoStandConfig } from './dev/demoStandConfig';\nimport { createResourceProxyDemoStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: <% if (it.standResourceProxyAuth === 'oauth') { %>'stand-resource-proxy-oauth'<% } else { %>'stand-resource-proxy-standalone'<% } %>,\n mountLabel: '#editor-root',\n } as const;\n\n try {\n<% if (it.standResourceProxyAuth === 'oauth') { %>\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n<% } else { %>\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n<% } %>\n if (!hasDemoStandConfig()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingDemoStandConfig) %>);\n }\n\n const emailCode = baseEmailHtml.replaceAll(\n 'YOUR_CDN_SAMPLE_PROJECT_ID',\n demoStandConfig.cdnSampleProjectId,\n );\n\n const instance = await <%= it.standProductApiName %>.init({\n<% if (it.standResourceProxyAuth !== 'oauth') { %>\n standaloneKey: standaloneCredentials.standaloneKey,\n<% } %>\n getAuthToken,\n storageProvider: createResourceProxyDemoStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: emailCode,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{
|
|
3642
|
+
"../../project-templates/shared/partials/stand-host-oauth-default-banners.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-default-banners',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n<% if (it.standShowMemoryUsageBanner) { %>\n <div style={{ marginBottom: '12px', color: '#7c2d12', fontSize: '14px' }}>\n Memory usage stand: eager editor import + Vite 8 + host-side asset plugins for build reproduction.\n </div>\n<% } %>\n<% if (it.standShowSubpathBanner) { %>\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n Advanced subpath stand: page route and editor publicPath are intentionally not at server root.\n </div>\n<% } %>\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3643
|
+
"../../project-templates/shared/partials/stand-host-oauth.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-oauth',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3644
|
+
"../../project-templates/shared/partials/stand-host-react-adapter.eta": "import { createRoot } from 'react-dom/client';\nimport <%= it.standReactAdapterComponentName %> from '<%~ it.standReactAdapterPackage %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\nconst EDITOR_MOUNT_ID = 'editor-root';\nconst smokeMeta = {\n hostKind: 'stand-host',\n variant: 'react-adapter',\n mountLabel: `#${EDITOR_MOUNT_ID}`,\n} as const;\n\n// The adapter fires handleLoad once the editor app is up; that is the readiness signal.\nfunction handleEditorLoad(): void {\n reportEditorReady(smokeMeta, document.getElementById(EDITOR_MOUNT_ID));\n}\n\nfunction StandHostApp() {\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n React adapter demo stand\n </div>\n <<%= it.standReactAdapterComponentName %>\n getAuthToken={getAuthToken}\n storageProvider={createLocalFolderStorageProvider()}\n content={{\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n }}\n config={editorConfig}\n handleLoad={handleEditorLoad}\n container={{ id: EDITOR_MOUNT_ID, style: { flex: 1, minHeight: 0 } }}\n />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<StandHostApp />);\n",
|
|
3645
|
+
"../../project-templates/shared/partials/stand-host-resource-proxy-body.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\n<% if (it.standResourceProxyAuth === 'oauth') { %>\nimport { hasOAuthCredentials } from './dev/oauthCredentials';\n<% } else { %>\nimport { hasStandaloneCredentials, standaloneCredentials } from './dev/standaloneCredentials';\n<% } %>\nimport { demoStandConfig, hasDemoStandConfig } from './dev/demoStandConfig';\nimport { createResourceProxyDemoStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: <% if (it.standResourceProxyAuth === 'oauth') { %>'stand-resource-proxy-oauth'<% } else { %>'stand-resource-proxy-standalone'<% } %>,\n mountLabel: '#editor-root',\n } as const;\n\n try {\n<% if (it.standResourceProxyAuth === 'oauth') { %>\n if (!hasOAuthCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingOAuthCredentials) %>);\n }\n<% } else { %>\n if (!hasStandaloneCredentials()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingStandaloneCredentials) %>);\n }\n<% } %>\n if (!hasDemoStandConfig()) {\n throw new Error(<%~ JSON.stringify(it.devAuthMissingDemoStandConfig) %>);\n }\n\n const emailCode = baseEmailHtml.replaceAll(\n 'YOUR_CDN_SAMPLE_PROJECT_ID',\n demoStandConfig.cdnSampleProjectId,\n );\n\n const instance = await <%= it.standProductApiName %>.init({\n<% if (it.standResourceProxyAuth !== 'oauth') { %>\n standaloneKey: standaloneCredentials.standaloneKey,\n<% } %>\n getAuthToken,\n storageProvider: createResourceProxyDemoStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: emailCode,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n <div\n style={{\n marginBottom: '12px',\n padding: '12px 16px',\n borderRadius: '8px',\n background: '#eef4ff',\n color: '#1e3a8a',\n fontSize: '13px',\n lineHeight: '20px',\n }}\n >\n <strong>Resource proxy demo:</strong>{' '}\n <code>placehold.co</code> is in <code>directHosts</code> (direct fetch);{' '}\n <code>dummyimage.com</code> goes through <code>/proxy/</code>.\n Open File Manager for seeded demo files or inspect the letter images.\n </div>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3628
3646
|
"../../project-templates/shared/partials/stand-host-resource-proxy.eta": "<%~ include('stand-host-resource-proxy-body', it) %>\n",
|
|
3629
|
-
"../../project-templates/shared/partials/stand-host-shadow-dom.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const shadowHostRef = useRef<HTMLDivElement | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n const shadowHost = shadowHostRef.current;\n if (!shadowHost || shadowHost.dataset.mounted === 'true' || instanceRef.current) {\n return;\n }\n\n shadowHost.dataset.mounted = 'true';\n\n const shadowRoot = shadowHost.attachShadow({ mode: 'closed' });\n const shadowStyle = document.createElement('style');\n shadowStyle.textContent = [\n ':host { display: block;
|
|
3630
|
-
"../../project-templates/shared/partials/stand-host-umd.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst editorGlobalName = <%~ JSON.stringify(it.standUmdEditorGlobalName) %>;\n\nfunction getEditorApi() {\n const editorApi = globalThis[editorGlobalName];\n if (!editorApi || typeof editorApi.init !== 'function') {\n throw new Error(`UMD bundle \"${editorGlobalName}\" was not found on window. Check <%~ it.standUmdScriptPath %>.`);\n }\n\n return editorApi;\n}\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorApi = ReturnType<typeof getEditorApi>;\ntype EditorInstance = Awaited<ReturnType<EditorApi['init']>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-umd',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await getEditorApi().init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{
|
|
3647
|
+
"../../project-templates/shared/partials/stand-host-shadow-dom.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const shadowHostRef = useRef<HTMLDivElement | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n const shadowHost = shadowHostRef.current;\n if (!shadowHost || shadowHost.dataset.mounted === 'true' || instanceRef.current) {\n return;\n }\n\n shadowHost.dataset.mounted = 'true';\n\n const shadowRoot = shadowHost.attachShadow({ mode: 'closed' });\n const shadowStyle = document.createElement('style');\n shadowStyle.textContent = [\n ':host { display: block; background: #ffffff; color: #111827; }',\n '#editor-root { height: 100%; }',\n ].join(' ');\n\n const editorRoot = document.createElement('div');\n editorRoot.id = 'editor-root';\n\n shadowRoot.appendChild(shadowStyle);\n shadowRoot.appendChild(editorRoot);\n\n async function run() {\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-shadow-dom',\n mountLabel: '#shadow-host -> #editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: editorRoot,\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, editorRoot);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, editorRoot);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <>\n <style>{`\n html, body, #root {\n margin: 0;\n min-height: 100%;\n }\n\n body {\n background:\n linear-gradient(135deg, rgba(255, 84, 89, 0.15), rgba(91, 146, 255, 0.18)),\n repeating-linear-gradient(90deg, rgba(17, 24, 39, 0.04) 0 8px, transparent 8px 16px);\n }\n\n body * {\n box-sizing: border-box;\n font-family: 'Courier New', monospace !important;\n letter-spacing: 0.02em;\n }\n\n button, input, select, textarea {\n border-radius: 0 !important;\n }\n `}</style>\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', padding: '24px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div style={{ marginBottom: '12px', color: '#111827', fontSize: '14px' }}>\n Advanced shadow-dom stand: closed shadow root + OAuth credentials + hostile host CSS\n </div>\n <div\n ref={shadowHostRef}\n id=\"shadow-host\"\n style={{ flex: 1, minHeight: 0, border: '2px dashed #111827', background: '#ffffff' }}\n />\n </div>\n </>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3648
|
+
"../../project-templates/shared/partials/stand-host-umd.eta": "import { useEffect, useRef, useState } from 'react';\nimport { createRoot } from 'react-dom/client';\nimport baseEmailHtml from './dev/email.html?raw';\nimport { editorConfig } from './dev/editorConfig';\nimport { getAuthToken } from './dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from './dev/storageProvider';\n\nconst editorGlobalName = <%~ JSON.stringify(it.standUmdEditorGlobalName) %>;\n\nfunction getEditorApi() {\n const editorApi = globalThis[editorGlobalName];\n if (!editorApi || typeof editorApi.init !== 'function') {\n throw new Error(`UMD bundle \"${editorGlobalName}\" was not found on window. Check <%~ it.standUmdScriptPath %>.`);\n }\n\n return editorApi;\n}\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorApi = ReturnType<typeof getEditorApi>;\ntype EditorInstance = Awaited<ReturnType<EditorApi['init']>>;\n\nfunction EditorApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'stand-advanced-umd',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await getEditorApi().init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: editorConfig,\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div style={{ marginBottom: '12px', color: '#44506b', fontSize: '14px' }}>\n Advanced UMD stand: editor loads from <%= it.standUmdScriptPath %> via a plain script tag.\n </div>\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3631
3649
|
"../../project-templates/shared/partials/stand-package-json.eta": "<%~ JSON.stringify(it.standPackageJson, null, 2) + '\\n' %>\n",
|
|
3632
3650
|
"../../project-templates/shared/partials/stand-readme.eta": "# <%= it.readmePluginPackageName %>\n\n<%= it.readmeGenerated %>\n\n<%= it.readmeWhatIncluded %>\n\n<%= it.readmeSimpleProject %>\n<%= it.readmeStorageProvider %>\n<%= it.readmeDevServer %>\n<% if (it.standAngular) { %>\n<%= it.readmeAngularHost %>\n<% } else { %>\n<%= it.readmeReactWrapper %>\n<%= it.readmeRouteHint %>\n<% } %>\n<% if (it.standReadmeIsResourceProxy === 'true') { %>\n\n<%= it.readmeStandResourceProxyAuth %>\n\n<%= it.readmeOauthTokenFile %>\n<% } else if (it.standReadmeIsClosedLoop === 'true') { %>\n<%= it.readmeClosedStandaloneKey %>\n<%= it.readmeClosedHandleReadLocale %>\n\n<%= it.readmeConfiguration %>\n\n<%= it.readmeClosedConfigHint %>\n<% } else { %>\n<%= it.readmeOauthProxy %>\n\n<%= it.readmeOauthTitle %>\n\n<%= it.readmeOauthHint %>\n<% } %>\n<% if (it.standReadmeIsResourceProxy === 'true') { %>\n\n<%= it.readmeStandResourceProxyHint %>\n\n<%= it.readmeStandResourceProxySecurityWarning %>\n\n<%= it.readmeStandResourceProxyDevRoutes %>\n\n<%= it.readmeStandResourceProxySampleProject %>\n<% } %>\n\n<%= it.readmeCommands %>\n\n```bash\nnpm install\n```\n\n<%= it.readmeCommandsDevelopment %>\n\n```bash\nnpm start\n```\n\n<%= it.readmeCommandsProduction %>\n\n<% if (it.standBundler === 'vite') { %>\n```bash\nnpm run build\nnpm run preview\n# alias: npm run serve:dist\n```\n<% } else { %>\n```bash\nnpm run build\nnpm run serve:dist\n```\n<% } %>\n\n<%= it.readmeCommandsProductionNote %>\n\n<% if (it.readmeModuleFederationHint) { %>\n\n<%= it.readmeModuleFederationHint %>\n\n<% } %>\n\n<% if (it.standAngular) { %>\n<%= it.readmeAngularCommandsDevUrl %>\n<%= it.readmeAngularCommandsProdUrl %>\n<% if (it.readmeAngularEsbuildClientProd) { %>\n<%= it.readmeAngularEsbuildClientProd %>\n<% } %>\n<% } else { %>\n> Production-like URL: `http://localhost:<%~ it.standPreviewPort %>/` (webpack/vite). Subpath stands may need the route suffix from dev mode.\n<% } %>\n\n<%= it.readmeStructure %>\n\n<%= it.readmeEntryPoint %>\n<%= it.readmeEmailTemplate %>\n<%= it.readmeEditorConfigFile %>\n<%= it.readmeStorageProviderFile %>\n<%= it.readmeStorageMiddleware %>\n<%= it.readmeStorageFolder %>\n<%= it.readmeConfigDir %>\n<% if (it.standReadmeIsClosedLoop === 'true') { %>\n<%= it.readmeStandaloneCredentialsFile %>\n<% } else if (it.standReadmeIsResourceProxy !== 'true') { %>\n<%= it.readmeOauthCredentialsFile %>\n<%= it.readmeOauthTokenFile %>\n<% } %>\n",
|
|
3633
3651
|
"../../project-templates/shared/partials/stand-resource-proxy-demo-storage-provider.eta": "/** Demo URLs from buildResourceProxyStandPolicy (email + FM seed). */\nconst RESOURCE_PROXY_DEMO_DIRECT_URL = <%~ JSON.stringify(it.resourceProxyDemoDirectUrl) %>;\nconst RESOURCE_PROXY_DEMO_PROXY_URL = <%~ JSON.stringify(it.resourceProxyDemoProxyUrl) %>;\n\nfunction createResourceProxyDemoSeedFiles(): FileSystemItem[] {\n const date = new Date().toISOString();\n return [\n {\n id: 'demo-direct-placehold',\n name: 'directHosts (placehold.co).png',\n folderId: '',\n isFolder: false,\n type: 'image/png',\n size: 0,\n date,\n url: RESOURCE_PROXY_DEMO_DIRECT_URL,\n thumbnailUrl: RESOURCE_PROXY_DEMO_DIRECT_URL,\n },\n {\n id: 'demo-proxy-dummyimage',\n name: 'via proxy (dummyimage.com).png',\n folderId: '',\n isFolder: false,\n type: 'image/png',\n size: 0,\n date,\n url: RESOURCE_PROXY_DEMO_PROXY_URL,\n thumbnailUrl: RESOURCE_PROXY_DEMO_PROXY_URL,\n },\n ];\n}\n\nfunction isResourceProxyDemoFileId(id: string | undefined): boolean {\n return id === 'demo-direct-placehold' || id === 'demo-proxy-dummyimage';\n}\n\nfunction normalizeFolderId(folderId: string | undefined, rootId: string | undefined): string {\n if (!folderId || folderId === rootId) {\n return '';\n }\n return folderId;\n}\n\nfunction filterDemoItems(\n demoFiles: FileSystemItem[],\n folderId: string | undefined,\n rootId: string | undefined,\n options: { search?: string; itemType?: 'all' | 'file' | 'folder' },\n): FileSystemItem[] {\n const normalizedFolderId = normalizeFolderId(folderId, rootId);\n if (options.itemType === 'folder') {\n return [];\n }\n\n let items = demoFiles.filter((item) => item.folderId === normalizedFolderId);\n const search = (options.search || '').trim().toLowerCase();\n if (search) {\n items = items.filter((item) => item.name.toLowerCase().includes(search));\n }\n return items;\n}\n\nfunction removeDemoFile(demoFiles: FileSystemItem[], id: string): void {\n const index = demoFiles.findIndex((demoItem) => demoItem.id === id);\n if (index >= 0) {\n demoFiles.splice(index, 1);\n }\n}\n\n/**\n * Local folder storage with two seeded external-image demo files for resource-proxy stand.\n * Demo files can be deleted or moved during the session; they reappear after page reload.\n */\nexport function createResourceProxyDemoStorageProvider(): StorageProvider {\n const inner = createLocalFolderStorageProvider();\n const demoFiles = createResourceProxyDemoSeedFiles();\n\n return {\n ...inner,\n\n async getItems(options) {\n const result = await inner.getItems(options);\n const demoItems = filterDemoItems(demoFiles, options.folderId, inner.rootId, options);\n const items = [...demoItems, ...(result.items || [])];\n const pagination = result.pagination\n ? {\n ...result.pagination,\n total: (result.pagination.total ?? result.items?.length ?? 0) + demoItems.length,\n }\n : result.pagination;\n\n return { items, pagination };\n },\n\n async deleteItem(item, options) {\n if (isResourceProxyDemoFileId(item.id)) {\n removeDemoFile(demoFiles, item.id);\n return;\n }\n\n return inner.deleteItem!(item, options);\n },\n\n async deleteItems(items, options) {\n const demoItems = items.filter((item) => isResourceProxyDemoFileId(item.id));\n for (const item of demoItems) {\n removeDemoFile(demoFiles, item.id);\n }\n\n const remaining = items.filter((item) => !isResourceProxyDemoFileId(item.id));\n if (remaining.length === 0) {\n return {\n success: demoItems.every(() => true),\n detailed: demoItems.map((item) => ({ success: true, requestId: item.id })),\n };\n }\n\n const innerResult = await inner.deleteItems!(remaining, options);\n const demoDetailed = demoItems.map((item) => ({ success: true, requestId: item.id }));\n return {\n success: innerResult.success && demoDetailed.every((entry) => entry.success),\n detailed: [...demoDetailed, ...(innerResult.detailed || [])],\n };\n },\n\n async moveItem(item, targetFolderId) {\n if (isResourceProxyDemoFileId(item.id)) {\n const demoItem = demoFiles.find((entry) => entry.id === item.id);\n if (!demoItem) {\n throw new Error('Demo file not found');\n }\n demoItem.folderId = normalizeFolderId(targetFolderId, inner.rootId);\n return { id: demoItem.id, folderId: demoItem.folderId };\n }\n\n return inner.moveItem!(item, targetFolderId);\n },\n\n async renameItem(item, newName) {\n if (isResourceProxyDemoFileId(item.id)) {\n const demoItem = demoFiles.find((entry) => entry.id === item.id);\n if (!demoItem) {\n throw new Error('Demo file not found');\n }\n demoItem.name = newName;\n return { id: demoItem.id, name: newName };\n }\n\n return inner.renameItem!(item, newName);\n },\n };\n}\n",
|
|
3634
3652
|
"../../project-templates/shared/partials/stand-storage-provider.eta": "import type {\n BatchResult,\n FileSystemItem,\n OperationResult,\n StorageProvider,\n UploadFilesRequest,\n} from '<%~ it.storageTypesPackage %>';\n\n/**\n * StorageProvider for dev stand. Stores files in ./storage via /dev-storage.\n * Uses pathMode: true - folderId and id are path strings.\n */\nexport function createLocalFolderStorageProvider(): StorageProvider {\n const base = '/dev-storage';\n\n const toPath = (id: string | null | undefined): string => {\n if (!id || id === '/' || id === '.') return '';\n return id.replace(/^\\/+/, '');\n };\n\n const readErrorMessage = async (res: Response, fallback: string): Promise<string> => {\n const err = await res.json().catch(() => ({})) as { error?: string };\n return err.error || fallback;\n };\n\n return {\n pathMode: true,\n rootId: '',\n ensureFolderTrailingSlash: true,\n\n async getItems(options) {\n const folderId = toPath(options.folderId);\n const q = folderId ? `?folderId=${encodeURIComponent(folderId)}` : '';\n const res = await fetch(`${base}/items${q}`);\n if (!res.ok) throw new Error(`getItems failed: ${res.status}`);\n const data = await res.json();\n return {\n items: (data.items || []).map((it: Record<string, unknown>) => ({\n ...it,\n folderId: it['folderId'] ?? '',\n })),\n pagination: data.pagination,\n };\n },\n\n async createFolder(name: string, parentid?: string) {\n const res = await fetch(`${base}/folder`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n name,\n parentId: toPath(parentid),\n }),\n });\n if (!res.ok) {\n const err = await res.json().catch(() => ({}));\n throw new Error(err.error || `createFolder failed: ${res.status}`);\n }\n const item = await res.json();\n return item as FileSystemItem;\n },\n\n async uploadFile(file: {\n name: string;\n size: number;\n type: string;\n folderId?: string;\n data: Blob | File;\n }) {\n const form = new FormData();\n form.append('file', file.data instanceof Blob ? new File([file.data], file.name, { type: file.type }) : file.data);\n form.append('folderId', toPath(file.folderId) || '');\n const res = await fetch(`${base}/upload`, {\n method: 'POST',\n body: form,\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `uploadFile failed: ${res.status}`));\n }\n const data = await res.json();\n const items = data.items || [];\n const first = items[0];\n if (!first) throw new Error('No file returned');\n return { id: first.id, ...first } as FileSystemItem;\n },\n\n async uploadFiles(request: UploadFilesRequest): Promise<BatchResult<FileSystemItem>> {\n const form = new FormData();\n form.append('folderId', toPath(request.folderId) || '');\n for (const it of request.items) {\n const file = it.data instanceof Blob ? new File([it.data], it.name, { type: it.type }) : it.data;\n form.append('file', file);\n }\n const res = await fetch(`${base}/upload`, {\n method: 'POST',\n body: form,\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `uploadFiles failed: ${res.status}`));\n }\n const data = await res.json();\n const items = (data.items || []).map((it: Record<string, unknown>) => ({\n ...it,\n id: String(it['id'] || ''),\n })) as FileSystemItem[];\n if (request.items.length > 0 && items.length === 0) {\n throw new Error('No files returned');\n }\n const detailed: OperationResult<FileSystemItem>[] = items.map((it, index) => ({\n success: true,\n requestId: request.items[index]?.requestId,\n data: it,\n }));\n return { success: true, detailed };\n },\n\n async uploadFileByUrl(url: string, folderId?: string) {\n const res = await fetch(`${base}/upload-by-url`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ url, folderId: toPath(folderId) }),\n });\n if (!res.ok) {\n const err = await res.json().catch(() => ({}));\n throw new Error(err.error || `uploadFileByUrl failed: ${res.status}`);\n }\n const item = await res.json();\n return item as FileSystemItem;\n },\n\n async deleteItem(item: FileSystemItem, _options: { permanent: boolean }) {\n const res = await fetch(`${base}/item`, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: item.id }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `deleteItem failed: ${res.status}`));\n }\n },\n\n async deleteItems(\n items: FileSystemItem[],\n _options: { permanent: boolean },\n ): Promise<BatchResult<never>> {\n const detailed: OperationResult<never>[] = await Promise.all(\n items.map(async (item) => {\n try {\n const res = await fetch(`${base}/item`, {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: item.id }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `deleteItem failed: ${res.status}`));\n }\n return { success: true, requestId: item.id };\n } catch (error) {\n return {\n success: false,\n requestId: item.id,\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n }),\n );\n\n return {\n success: detailed.every((entry) => entry.success),\n detailed,\n };\n },\n\n async renameItem(item: FileSystemItem, newName: string) {\n const res = await fetch(`${base}/rename`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: item.id, newName }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `renameItem failed: ${res.status}`));\n }\n const updated = await res.json();\n return updated as FileSystemItem;\n },\n\n async moveItem(item: FileSystemItem, targetFolderId?: string) {\n const res = await fetch(`${base}/move`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n path: item.id,\n targetFolderId: toPath(targetFolderId),\n }),\n });\n if (!res.ok) {\n throw new Error(await readErrorMessage(res, `moveItem failed: ${res.status}`));\n }\n const updated = await res.json();\n return updated as FileSystemItem;\n },\n\n getUrl(file: FileSystemItem) {\n return `${base}/file/${encodeURIComponent(file.id)}`;\n },\n };\n}\n",
|
|
3635
3653
|
"../../project-templates/shared/partials/stand-vite-index-body.eta": "<% if (it.standAdvancedUmd) { %>\n <script src=\"<%= it.standUmdScriptPath %>\"><\/script>\n<% } %>\n <script type=\"module\" src=\"<%~ it.standIndexScriptSrc %>\"><\/script>\n",
|
|
3636
|
-
"../../project-templates/shared/partials/stand-vite-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-vite-index-body', it) %>\n </body>\n</html>\n",
|
|
3654
|
+
"../../project-templates/shared/partials/stand-vite-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n <style>\n body {\n margin: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-vite-index-body', it) %>\n </body>\n</html>\n",
|
|
3637
3655
|
"../../project-templates/shared/partials/stand-webpack-index-body.eta": "<% if (it.standAdvancedUmd) { %>\n <script src=\"<%= it.standUmdScriptPath %>\"><\/script>\n<% } %>\n <script src=\"<%= it.standWebpackScriptSrc %>\"><\/script>\n",
|
|
3638
|
-
"../../project-templates/shared/partials/stand-webpack-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-webpack-index-body', it) %>\n </body>\n</html>\n",
|
|
3656
|
+
"../../project-templates/shared/partials/stand-webpack-index-shell.eta": "<!doctype html>\n<html lang=\"<%= it.standIndexHtmlLang %>\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title><%= it.standIndexHtmlTitle %></title>\n <style>\n body {\n margin: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"root\"></div>\n<%~ include('stand-webpack-index-body', it) %>\n </body>\n</html>\n",
|
|
3639
3657
|
"../../project-templates/shared/stand-assets/scripts/assertDistReady.cjs": "#!/usr/bin/env node\n/**\n * Guards `serve:dist` / `vite preview` — fails fast when build output is missing.\n *\n * Usage: node ./scripts/assertDistReady.cjs [distRelativePath]\n * Default path: `dist`\n */\nconst fs = require('node:fs');\nconst path = require('node:path');\n\nconst distRelative = process.argv[2] || 'dist';\nconst distDir = path.resolve(process.cwd(), distRelative);\n\nfunction hasIndexHtml(dir) {\n if (fs.existsSync(path.join(dir, 'index.html'))) {\n return true;\n }\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n if (hasIndexHtml(path.join(dir, entry.name))) {\n return true;\n }\n }\n return false;\n}\n\nif (!fs.existsSync(distDir)) {\n console.error(`[serve:dist] Missing ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n}\n\nif (!fs.statSync(distDir).isDirectory()) {\n console.error(`[serve:dist] Expected ${distRelative}/ to be a directory.`);\n process.exit(1);\n}\n\nif (!hasIndexHtml(distDir)) {\n console.error(`[serve:dist] No index.html under ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n}\n",
|
|
3640
3658
|
"../../project-templates/shared/stand-assets/scripts/serveDist.cjs.eta": "#!/usr/bin/env node\n/**\n * Production-like static server for demo stands (`serve:dist`).\n * Serves built `dist/`, mirrors dev-server `/api` proxy for OAuth (`getAuthToken`),\n * and mounts local `./storage` via `/dev-storage` (same middleware as `ng serve`).\n *\n * Usage: node ./scripts/serveDist.cjs [distRelativePath] [port]\n */\nconst http = require('node:http');\nconst https = require('node:https');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { URL } = require('node:url');\n\nconst API_PROXY_ENABLED = <%= it.standClosedLoop ? 'false' : 'true' %>;\nconst API_TARGET = <%~ JSON.stringify(it.standOpenApiBaseUrl) %>;\nconst API_ORIGIN = <%~ JSON.stringify(it.standOpenApiOrigin) %>;\nconst DEFAULT_PORT = <%~ it.standPreviewPort %>;\n\nconst STATIC_HEADERS = {\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n};\n\nconst MIME_TYPES = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.ico': 'image/x-icon',\n '.map': 'application/json; charset=utf-8',\n};\n\nfunction resolveContentType(filePath) {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] || 'application/octet-stream';\n}\n\nfunction hasIndexHtml(dir) {\n if (fs.existsSync(path.join(dir, 'index.html'))) {\n return true;\n }\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n if (hasIndexHtml(path.join(dir, entry.name))) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveStaticFile(distDir, requestPath) {\n const safeSuffix = path.normalize(requestPath).replace(/^(\\.\\.[/\\\\])+/, '');\n const candidate = path.join(distDir, safeSuffix);\n if (!candidate.startsWith(distDir)) {\n return null;\n }\n if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n return candidate;\n }\n if (fs.existsSync(path.join(candidate, 'index.html'))) {\n return path.join(candidate, 'index.html');\n }\n return null;\n}\n\nfunction sendFile(res, filePath) {\n res.writeHead(200, {\n ...STATIC_HEADERS,\n 'Content-Type': resolveContentType(filePath),\n });\n fs.createReadStream(filePath).pipe(res);\n}\n\nfunction readRequestBody(req) {\n return new Promise((resolve, reject) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n}\n\nfunction buildProxyRequestHeaders(req, targetUrl, bodyLength) {\n const headers = { ...req.headers, host: targetUrl.host };\n if (headers.origin) {\n headers.origin = API_ORIGIN;\n }\n delete headers.connection;\n delete headers['transfer-encoding'];\n if (bodyLength > 0) {\n headers['content-length'] = String(bodyLength);\n } else {\n delete headers['content-length'];\n }\n return headers;\n}\n\nfunction drainResponse(proxyRes) {\n return new Promise((resolve) => {\n proxyRes.on('end', resolve);\n proxyRes.resume();\n });\n}\n\nfunction proxyApiRequest(req, res, targetUrl, body, redirectCount, method) {\n const MAX_REDIRECTS = 5;\n if (redirectCount > MAX_REDIRECTS) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Too many redirects');\n return;\n }\n\n const requestMethod = method || req.method || 'GET';\n const transport = targetUrl.protocol === 'https:' ? https : http;\n const headers = buildProxyRequestHeaders(req, targetUrl, body.length);\n\n const proxyReq = transport.request(\n targetUrl,\n { method: requestMethod, headers },\n (proxyRes) => {\n const status = proxyRes.statusCode || 502;\n const location = proxyRes.headers.location;\n if (status >= 300 && status < 400 && location) {\n drainResponse(proxyRes).then(() => {\n const nextUrl = new URL(location, targetUrl);\n const useGet = status === 303;\n proxyApiRequest(\n req,\n res,\n nextUrl,\n useGet ? Buffer.alloc(0) : body,\n redirectCount + 1,\n useGet ? 'GET' : requestMethod,\n );\n });\n return;\n }\n\n const outHeaders = { ...proxyRes.headers };\n delete outHeaders.location;\n res.writeHead(status, outHeaders);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on('error', (error) => {\n console.error('[serveDist] API proxy error:', error.message);\n if (!res.headersSent) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Bad Gateway');\n }\n });\n\n if (body.length > 0) {\n proxyReq.write(body);\n }\n proxyReq.end();\n}\n\nasync function proxyApi(req, res) {\n const body = await readRequestBody(req);\n const targetUrl = new URL(req.url || '/', API_TARGET);\n proxyApiRequest(req, res, targetUrl, body, 0);\n}\n\nfunction loadDevStorageMiddleware() {\n const middlewarePath = path.join(__dirname, 'devStorageMiddleware.ts');\n if (!fs.existsSync(middlewarePath)) {\n return null;\n }\n\n try {\n const { register } = require('tsx/cjs/api');\n register();\n const mod = require(middlewarePath);\n const factory = mod && (mod.default || mod);\n return typeof factory === 'function' ? factory() : null;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[serveDist] dev-storage middleware not loaded: ${message}`);\n return null;\n }\n}\n\nfunction handleStaticRequest(distDir, req, res, pathname) {\n if (API_PROXY_ENABLED && pathname.startsWith('/api')) {\n proxyApi(req, res);\n return;\n }\n\n const filePath = resolveStaticFile(distDir, pathname === '/' ? '/index.html' : pathname);\n if (filePath) {\n sendFile(res, filePath);\n return;\n }\n\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Not Found');\n}\n\nfunction createServer(distDir, devStorageMiddleware) {\n return http.createServer((req, res) => {\n const requestUrl = new URL(req.url || '/', 'http://localhost');\n const pathname = decodeURIComponent(requestUrl.pathname);\n\n if (pathname.startsWith('/dev-storage')) {\n if (!devStorageMiddleware) {\n res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('dev-storage middleware unavailable (missing scripts/devStorageMiddleware.ts or tsx)');\n return;\n }\n\n devStorageMiddleware(req, res, () => {\n if (!res.headersSent) {\n res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Not Found');\n }\n });\n return;\n }\n\n handleStaticRequest(distDir, req, res, pathname);\n });\n}\n\nfunction main() {\n const distRelative = process.argv[2] || 'dist';\n const portArg = process.argv[3];\n const port = portArg !== undefined ? Number(portArg) : DEFAULT_PORT;\n const distDir = path.resolve(process.cwd(), distRelative);\n\n if (!fs.existsSync(distDir) || !fs.statSync(distDir).isDirectory()) {\n console.error(`[serveDist] Missing ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n }\n\n if (!hasIndexHtml(distDir)) {\n console.error(`[serveDist] No index.html under ${distRelative}/ — run \\`npm run build\\` first.`);\n process.exit(1);\n }\n\n const devStorageMiddleware = loadDevStorageMiddleware();\n const server = createServer(distDir, devStorageMiddleware);\n server.listen(port, () => {\n console.log(`[serveDist] ${distRelative} → http://localhost:${port}/`);\n if (API_PROXY_ENABLED) {\n console.log(`[serveDist] /api → ${API_TARGET}`);\n }\n if (devStorageMiddleware) {\n console.log('[serveDist] /dev-storage → ./storage');\n }\n });\n}\n\nmain();\n",
|
|
3641
3659
|
"../../project-templates/shared/stand-assets/serve.json": "{\n \"headers\": [\n {\n \"source\": \"**/*\",\n \"headers\": [\n {\n \"key\": \"Cross-Origin-Resource-Policy\",\n \"value\": \"cross-origin\"\n },\n {\n \"key\": \"Access-Control-Allow-Origin\",\n \"value\": \"*\"\n }\n ]\n }\n ]\n}\n",
|
|
3642
3660
|
"../../project-templates/shared/stand-vite-base/config/lib/createViteStandConfig.ts": "import type { IncomingMessage, ServerResponse } from 'node:http';\nimport react from '@vitejs/plugin-react';\nimport type { PluginOption, UserConfig, UserConfigExport, ViteDevServer } from 'vite';\nimport { defineConfig } from 'vite';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_PREVIEW_HEADERS, STAND_PREVIEW_PORT } from './standPreviewSettings.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\n\ntype DevServerMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;\n\ninterface CreateViteStandConfigOptions {\n projectRoot: string;\n open?: string;\n apiBaseUrl: string;\n apiOrigin: string;\n closedLoop?: boolean;\n plugins?: PluginOption[];\n extraServerMiddlewares?: DevServerMiddleware[];\n extraProxy?: Record<string, import('vite').ProxyOptions>;\n onConfigureServer?: (server: ViteDevServer) => void | (() => void);\n build?: UserConfig['build'];\n resolve?: UserConfig['resolve'];\n serverPort?: number;\n}\n\nexport function createViteStandConfig(options: CreateViteStandConfigOptions): UserConfigExport {\n const {\n projectRoot,\n open,\n apiBaseUrl,\n apiOrigin,\n closedLoop,\n plugins = [],\n extraServerMiddlewares = [],\n extraProxy = {},\n onConfigureServer,\n build,\n resolve,\n serverPort = 3000,\n } = options;\n\n return defineConfig(() => {\n const apiProxy = closedLoop\n ? undefined\n : {\n ...createStandApiProxyOptions(apiBaseUrl, apiOrigin),\n ...extraProxy,\n };\n\n return {\n root: projectRoot,\n plugins: [\n react(),\n ...plugins,\n {\n name: 'dev-storage',\n configureServer(server) {\n let disposeConfigureServer: void | (() => void);\n if (open && open !== '/') {\n server.middlewares.use((req, res, next) => {\n if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {\n res.statusCode = 302;\n res.setHeader('Location', open);\n res.end();\n return;\n }\n next();\n });\n }\n server.middlewares.use(devStorageMiddleware());\n for (const middleware of extraServerMiddlewares) {\n server.middlewares.use(middleware);\n }\n disposeConfigureServer = onConfigureServer?.(server);\n return () => {\n disposeConfigureServer?.();\n };\n },\n },\n ],\n ...(resolve ? { resolve } : {}),\n server: {\n ...(open !== undefined && open !== null ? { open } : {}),\n port: serverPort,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n ...build,\n },\n preview: {\n port: STAND_PREVIEW_PORT,\n ...(open && open !== '/' ? { open } : {}),\n headers: STAND_PREVIEW_HEADERS,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n };\n });\n}\n",
|
|
3643
|
-
"../../project-templates/shared/stand-vite-base/config/lib/standApiProxy.ts": "import type { ProxyOptions } from 'vite';\n\nexport function createStandApiProxyOptions(\n apiBaseUrl: string,\n apiOrigin: string,\n): Record<string, ProxyOptions> {\n return {\n '/api': {\n target: apiBaseUrl,\n secure: false,\n changeOrigin: true,\n configure: (proxyInstance) => {\n proxyInstance.on('proxyReq', (proxyRequest) => {\n if (proxyRequest.getHeader('origin')) {\n proxyRequest.setHeader('origin', apiOrigin);\n }\n });\n },\n },\n };\n}\n",
|
|
3661
|
+
"../../project-templates/shared/stand-vite-base/config/lib/standApiProxy.ts": "import type { ProxyOptions } from 'vite';\n\nexport function createStandApiProxyOptions(\n apiBaseUrl: string,\n apiOrigin: string,\n): Record<string, ProxyOptions> {\n return {\n '/api': {\n target: apiBaseUrl,\n secure: false,\n changeOrigin: true,\n // The target already ends with `/api/`: strip the rule prefix, otherwise requests land on `/api/api/…`.\n rewrite: (path) => path.replace(/^\\/api/, '') || '/',\n configure: (proxyInstance) => {\n proxyInstance.on('proxyReq', (proxyRequest) => {\n if (proxyRequest.getHeader('origin')) {\n proxyRequest.setHeader('origin', apiOrigin);\n }\n });\n },\n },\n };\n}\n",
|
|
3644
3662
|
"../../project-templates/shared/stand-vite-base/config/lib/standPreviewSettings.ts.eta": "/**\n * Preview port for production-like stand runs (`npm run preview` / `serve:dist`).\n * Rendered from CLI `standScriptPorts.ts` at stand generation time.\n */\nexport const STAND_PREVIEW_PORT = <%~ it.standPreviewPort %>;\n\nexport const STAND_PREVIEW_HEADERS = {\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n} as const;\n",
|
|
3645
3663
|
"../../project-templates/shared/stand-vite-base/config/lib/standProductionBuild.ts": "import type { BuildOptions } from 'vite';\n\n/** Production build defaults for demo stands (`vite build` / `vite preview`). */\nexport const STAND_VITE_PRODUCTION_BUILD = {\n minify: 'esbuild',\n cssMinify: true,\n sourcemap: false,\n} satisfies BuildOptions;\n",
|
|
3646
3664
|
"../../project-templates/shared/stand-vite-base/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
|
|
@@ -3667,11 +3685,11 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3667
3685
|
"../../project-templates/stand/advanced/module-federation/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
|
|
3668
3686
|
"../../project-templates/stand/advanced/module-federation/vite/config/dev-host.ts.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { createModuleFederationHostConfig } from './lib/createModuleFederationHostConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createModuleFederationHostConfig({\n projectRoot,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n});\n",
|
|
3669
3687
|
"../../project-templates/stand/advanced/module-federation/vite/config/dev-remote.ts.eta": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport VitePlugin from '<%~ it.standVitePluginPackage %>/vite';\nimport { createModuleFederationRemoteConfig } from './lib/createModuleFederationRemoteConfig.ts';\n\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst projectRoot = path.resolve(__dirname, '..');\n\nexport default createModuleFederationRemoteConfig({\n projectRoot,\n vitePlugin: VitePlugin,\n closedLoop: <%= it.standClosedLoop %>,\n apiBaseUrl: <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n apiOrigin: <%~ JSON.stringify(it.standOpenApiOrigin) %>,\n});\n",
|
|
3670
|
-
"../../project-templates/stand/advanced/module-federation/vite/config/lib/createModuleFederationHostConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\nimport { federation } from '@module-federation/vite';\nimport type { UserConfigExport } from 'vite';\nimport { defineConfig } from 'vite';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\nimport { crossOriginAssetCorsPlugin } from './crossOriginAssetCorsPlugin.ts';\nimport {\n MF_STAND_HOST,\n MF_STAND_HOST_PORT,\n moduleFederationHostRemotes,\n moduleFederationRemoteEntryUrl,\n} from './moduleFederationHosts.ts';\nimport { MODULE_FEDERATION_HOST_SHARED } from './moduleFederationShared.ts';\nimport { getModuleFederationHostOptimizeDepsEntries } from './moduleFederationOptimizeDeps.ts';\nimport { STAND_PREVIEW_HEADERS } from './standPreviewSettings.ts';\n\ninterface CreateModuleFederationHostConfigOptions {\n projectRoot: string;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nexport function createModuleFederationHostConfig(options: CreateModuleFederationHostConfigOptions): UserConfigExport {\n const { projectRoot, apiBaseUrl, apiOrigin } = options;\n const remoteEntry = moduleFederationRemoteEntryUrl();\n\n return defineConfig(() => {\n const apiProxy = createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n base: '/',\n plugins: [\n react(),\n federation({\n name: 'mf_stand_host',\n manifest: true,\n dts: false,\n shareStrategy: 'loaded-first',\n remotes: moduleFederationHostRemotes(remoteEntry),\n shared: MODULE_FEDERATION_HOST_SHARED,\n }),\n crossOriginAssetCorsPlugin(),\n {\n name: 'dev-storage',\n configureServer(server) {\n server.middlewares.use(devStorageMiddleware());\n },\n },\n ],\n resolve: {\n alias: {\n '@': path.join(projectRoot, 'src'),\n },\n dedupe: ['react', 'react-dom'],\n },\n optimizeDeps: {\n entries: getModuleFederationHostOptimizeDepsEntries(projectRoot),\n include: ['react', 'react-dom', 'react/jsx-dev-runtime'],\n exclude: ['editor/Editor'],\n },\n server: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n proxy: apiProxy,\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n target: 'esnext',\n outDir: './dist/host',\n },\n preview: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n headers: STAND_PREVIEW_HEADERS,\n proxy: apiProxy,\n },\n };\n });\n}\n",
|
|
3688
|
+
"../../project-templates/stand/advanced/module-federation/vite/config/lib/createModuleFederationHostConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\nimport { federation } from '@module-federation/vite';\nimport type { UserConfigExport } from 'vite';\nimport { defineConfig } from 'vite';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\nimport { crossOriginAssetCorsPlugin } from './crossOriginAssetCorsPlugin.ts';\nimport {\n MF_STAND_HOST,\n MF_STAND_HOST_PORT,\n moduleFederationHostRemotes,\n moduleFederationRemoteEntryUrl,\n waitForModuleFederationRemote,\n} from './moduleFederationHosts.ts';\nimport { MODULE_FEDERATION_HOST_SHARED } from './moduleFederationShared.ts';\nimport { getModuleFederationHostOptimizeDepsEntries } from './moduleFederationOptimizeDeps.ts';\nimport { STAND_PREVIEW_HEADERS } from './standPreviewSettings.ts';\n\ninterface CreateModuleFederationHostConfigOptions {\n projectRoot: string;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nexport function createModuleFederationHostConfig(options: CreateModuleFederationHostConfigOptions): UserConfigExport {\n const { projectRoot, apiBaseUrl, apiOrigin } = options;\n const remoteEntry = moduleFederationRemoteEntryUrl();\n\n return defineConfig(() => {\n const apiProxy = createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n base: '/',\n plugins: [\n react(),\n federation({\n name: 'mf_stand_host',\n manifest: true,\n dts: false,\n shareStrategy: 'loaded-first',\n remotes: moduleFederationHostRemotes(remoteEntry),\n shared: MODULE_FEDERATION_HOST_SHARED,\n }),\n crossOriginAssetCorsPlugin(),\n {\n name: 'wait-for-module-federation-remote',\n apply: 'serve',\n async configureServer() {\n await waitForModuleFederationRemote(remoteEntry);\n },\n },\n {\n name: 'dev-storage',\n configureServer(server) {\n server.middlewares.use(devStorageMiddleware());\n },\n },\n ],\n resolve: {\n alias: {\n '@': path.join(projectRoot, 'src'),\n },\n dedupe: ['react', 'react-dom'],\n },\n optimizeDeps: {\n entries: getModuleFederationHostOptimizeDepsEntries(projectRoot),\n include: ['react', 'react-dom', 'react/jsx-dev-runtime'],\n exclude: ['editor/Editor'],\n },\n server: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n proxy: apiProxy,\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n target: 'esnext',\n outDir: './dist/host',\n },\n preview: {\n port: MF_STAND_HOST_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_HOST_PORT}`,\n headers: STAND_PREVIEW_HEADERS,\n proxy: apiProxy,\n },\n };\n });\n}\n",
|
|
3671
3689
|
"../../project-templates/stand/advanced/module-federation/vite/config/lib/createModuleFederationRemoteConfig.ts": "import path from 'node:path';\nimport react from '@vitejs/plugin-react';\nimport { federation } from '@module-federation/vite';\nimport { v4 as uuid } from 'uuid';\nimport type { PluginOption, UserConfigExport } from 'vite';\nimport { defineConfig } from 'vite';\nimport cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';\nimport devStorageMiddleware from '../../scripts/devStorageMiddleware.ts';\nimport { createStandApiProxyOptions } from './standApiProxy.ts';\nimport { STAND_VITE_PRODUCTION_BUILD } from './standProductionBuild.ts';\nimport { crossOriginAssetCorsPlugin } from './crossOriginAssetCorsPlugin.ts';\nimport { editorWorkerCorsPlugin } from './editorWorkerCorsPlugin.ts';\nimport {\n MF_STAND_HOST,\n MF_STAND_REMOTE_PORT,\n moduleFederationCdnPublicPath,\n} from './moduleFederationHosts.ts';\nimport { MODULE_FEDERATION_REMOTE_SHARED } from './moduleFederationShared.ts';\nimport { getModuleFederationRemoteOptimizeDepsEntries } from './moduleFederationOptimizeDeps.ts';\nimport { STAND_PREVIEW_HEADERS } from './standPreviewSettings.ts';\n\ninterface CreateModuleFederationRemoteConfigOptions {\n projectRoot: string;\n vitePlugin: (options?: { publicPath?: string }) => PluginOption[];\n closedLoop?: boolean;\n apiBaseUrl: string;\n apiOrigin: string;\n}\n\nfunction remoteIndexHtmlPlugin(): PluginOption {\n return {\n name: 'module-federation-remote-index-html',\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n if (req.url === '/' || req.url === '/index.html') {\n req.url = '/remote-index.html';\n }\n next();\n });\n },\n };\n}\n\nexport function createModuleFederationRemoteConfig(options: CreateModuleFederationRemoteConfigOptions): UserConfigExport {\n const {\n projectRoot,\n vitePlugin,\n closedLoop,\n apiBaseUrl,\n apiOrigin,\n } = options;\n const cdnPublicPath = moduleFederationCdnPublicPath();\n\n return defineConfig(() => {\n const apiProxy = closedLoop\n ? undefined\n : createStandApiProxyOptions(apiBaseUrl, apiOrigin);\n\n return {\n root: projectRoot,\n base: '/',\n plugins: [\n react(),\n federation({\n name: 'editor',\n filename: 'remoteEntry.js',\n manifest: true,\n dts: false,\n publicPath: cdnPublicPath,\n shareStrategy: 'loaded-first',\n exposes: {\n './Editor': './src/remote/EditorApp.tsx',\n },\n shared: MODULE_FEDERATION_REMOTE_SHARED,\n }),\n ...vitePlugin({\n publicPath: cdnPublicPath,\n }),\n cssInjectedByJsPlugin({\n injectCode: (content) => ``\n + `if (document) {`\n + `const style = document.createElement('style');`\n + `style.setAttribute('data-mf-app', 'module-federation-editor-remote');`\n + `style.innerHTML = ${content};`\n + `document.body.append(style);`\n + `}`,\n }),\n editorWorkerCorsPlugin(),\n crossOriginAssetCorsPlugin(),\n remoteIndexHtmlPlugin(),\n {\n name: 'dev-storage',\n configureServer(server) {\n server.middlewares.use(devStorageMiddleware());\n },\n },\n ],\n resolve: {\n alias: {\n '@': path.join(projectRoot, 'src'),\n },\n dedupe: ['react', 'react-dom'],\n },\n optimizeDeps: {\n entries: getModuleFederationRemoteOptimizeDepsEntries(projectRoot),\n include: ['react', 'react-dom', 'react/jsx-dev-runtime'],\n },\n server: {\n port: MF_STAND_REMOTE_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_REMOTE_PORT}`,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n build: {\n ...STAND_VITE_PRODUCTION_BUILD,\n target: 'esnext',\n outDir: './dist/remote',\n rollupOptions: {\n input: {\n remote: path.join(projectRoot, 'remote-index.html'),\n },\n output: {\n entryFileNames: `[name]${uuid()}.js`,\n chunkFileNames: `[name]${uuid()}.js`,\n assetFileNames: `[name]${uuid()}.[ext]`,\n },\n },\n },\n preview: {\n port: MF_STAND_REMOTE_PORT,\n host: MF_STAND_HOST,\n strictPort: true,\n origin: `http://${MF_STAND_HOST}:${MF_STAND_REMOTE_PORT}`,\n headers: STAND_PREVIEW_HEADERS,\n ...(apiProxy ? { proxy: apiProxy } : {}),\n },\n };\n });\n}\n",
|
|
3672
3690
|
"../../project-templates/stand/advanced/module-federation/vite/config/lib/crossOriginAssetCorsPlugin.ts": "import type { Plugin } from 'vite';\nimport type { ServerResponse } from 'node:http';\n\nfunction applyCrossOriginAssetHeaders(res: ServerResponse): void {\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');\n}\n\n/** CORS on the CDN dev/preview server: lets the host origin load static assets cross-origin. */\nexport function crossOriginAssetCorsPlugin(): Plugin {\n return {\n name: 'cross-origin-asset-cors',\n enforce: 'pre',\n configureServer(server) {\n server.middlewares.use((_req, res, next) => {\n applyCrossOriginAssetHeaders(res);\n next();\n });\n },\n configurePreviewServer(server) {\n server.middlewares.use((_req, res, next) => {\n applyCrossOriginAssetHeaders(res);\n next();\n });\n },\n };\n}\n",
|
|
3673
3691
|
"../../project-templates/stand/advanced/module-federation/vite/config/lib/editorWorkerCorsPlugin.ts": "import type { Plugin } from 'vite';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\n\nconst EDITOR_WORKER_PATH = '/monacoeditorwork/';\n\nfunction applyEditorWorkerCorsHeaders(res: ServerResponse): void {\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');\n res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');\n}\n\nfunction editorWorkerCorsMiddleware(\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: unknown) => void,\n): void {\n if (!req.url?.includes(EDITOR_WORKER_PATH)) {\n next();\n return;\n }\n\n applyEditorWorkerCorsHeaders(res);\n\n if (req.method === 'OPTIONS') {\n res.statusCode = 204;\n res.end();\n return;\n }\n\n next();\n}\n\n/** CORS for editor worker bundles under cross-origin Module Federation. */\nexport function editorWorkerCorsPlugin(): Plugin {\n return {\n name: 'editor-worker-cors',\n enforce: 'pre',\n configureServer(server) {\n server.middlewares.use(editorWorkerCorsMiddleware);\n },\n configurePreviewServer(server) {\n server.middlewares.use(editorWorkerCorsMiddleware);\n },\n };\n}\n",
|
|
3674
|
-
"../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationHosts.ts": "/** Host and CDN remote both on localhost; different ports make them cross-origin, like MF behind a separate CDN. */\nexport const MF_STAND_HOST = 'localhost';\nexport const MF_STAND_HOST_PORT =
|
|
3692
|
+
"../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationHosts.ts": "/** Host and CDN remote both on localhost; different ports make them cross-origin, like MF behind a separate CDN. */\nexport const MF_STAND_HOST = 'localhost';\nconst MF_STAND_DEFAULT_HOST_PORT = 3000;\n\n/**\n * Host port comes from PLUGIN_DEV_PORT, like the other stands: `concurrently` drops a trailing\n * `--port`, so the environment is the only channel that reaches both the host and the remote.\n */\nfunction resolveModuleFederationHostPort(): number {\n const port = Number(process.env.PLUGIN_DEV_PORT);\n return Number.isInteger(port) && port > 0 ? port : MF_STAND_DEFAULT_HOST_PORT;\n}\n\nexport const MF_STAND_HOST_PORT = resolveModuleFederationHostPort();\n/** The remote (CDN) always sits on the next port, so one number describes the whole stand. */\nexport const MF_STAND_REMOTE_PORT = MF_STAND_HOST_PORT + 1;\n\nexport function moduleFederationCdnPublicPath(port = MF_STAND_REMOTE_PORT): string {\n return `http://${MF_STAND_HOST}:${port}/`;\n}\n\nexport function moduleFederationRemoteEntryUrl(port = MF_STAND_REMOTE_PORT): string {\n return `${moduleFederationCdnPublicPath(port)}remoteEntry.js`;\n}\n\nexport function moduleFederationHostPageUrl(port = MF_STAND_HOST_PORT): string {\n return `http://${MF_STAND_HOST}:${port}/`;\n}\n\n/** Remotes host: a Vite remoteEntry is ESM, so it needs type module rather than a classic script. */\nexport function moduleFederationHostRemotes(remoteEntryUrl = moduleFederationRemoteEntryUrl()) {\n return {\n editor: {\n type: 'module' as const,\n name: 'editor',\n entry: remoteEntryUrl,\n entryGlobalName: 'editor',\n shareScope: 'default',\n },\n };\n}\n\n/** Delays the host dev server until the remote serves remoteEntry.js; the port is not known to npm scripts. */\nexport async function waitForModuleFederationRemote(\n remoteEntryUrl = moduleFederationRemoteEntryUrl(),\n timeoutMs = 120_000,\n): Promise<void> {\n const startedAt = Date.now();\n let lastError = '';\n while (Date.now() - startedAt < timeoutMs) {\n try {\n const response = await fetch(remoteEntryUrl, { signal: AbortSignal.timeout(2_000) });\n if (response.ok) {\n return;\n }\n lastError = `HTTP ${response.status}`;\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n throw new Error(`Module Federation remote is not reachable at ${remoteEntryUrl} (${lastError || 'no response'})`);\n}\n",
|
|
3675
3693
|
"../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationOptimizeDeps.ts": "import path from 'node:path';\n\n/** Entrypoints for the remote dev server dep scan, excluding the host index and editor/Editor. */\nexport function getModuleFederationRemoteOptimizeDepsEntries(projectRoot: string): string[] {\n return [\n path.join(projectRoot, 'remote-index.html'),\n path.join(projectRoot, 'src/remote/EditorApp.tsx'),\n path.join(projectRoot, 'src/remote/devShell.tsx'),\n ];\n}\n\n/** Entrypoints for the host dev server dep scan. */\nexport function getModuleFederationHostOptimizeDepsEntries(projectRoot: string): string[] {\n return [\n path.join(projectRoot, 'index.html'),\n path.join(projectRoot, 'src/index.tsx'),\n ];\n}\n",
|
|
3676
3694
|
"../../project-templates/stand/advanced/module-federation/vite/config/lib/moduleFederationShared.ts": "/** Shared deps for @module-federation/vite; versions match the stand package.json. */\nexport const MODULE_FEDERATION_REACT_VERSION = '19.2.7';\n\nexport const MODULE_FEDERATION_REMOTE_SHARED = {\n react: {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n import: false,\n },\n 'react-dom': {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n import: false,\n },\n} as const;\n\n/** The host must load React before the MF runtime; otherwise ReactCurrentDispatcher breaks. */\nexport const MODULE_FEDERATION_HOST_SHARED = {\n react: {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n eager: true,\n },\n 'react-dom': {\n singleton: true,\n requiredVersion: MODULE_FEDERATION_REACT_VERSION,\n eager: true,\n },\n} as const;\n",
|
|
3677
3695
|
"../../project-templates/stand/advanced/module-federation/vite/index.html.eta": "<%~ include('stand-vite-index-shell', it) %>\n",
|
|
@@ -3682,9 +3700,9 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3682
3700
|
"../../project-templates/stand/advanced/module-federation/vite/src/dev/getAuthToken.ts.eta": "<%~ include('stand-get-auth-token', it) %>\n",
|
|
3683
3701
|
"../../project-templates/stand/advanced/module-federation/vite/src/dev/oauthCredentials.ts": "export const oauthCredentials = {\n clientId: 'YOUR_CLIENT_ID',\n clientSecret: 'YOUR_CLIENT_SECRET',\n};\n\nexport function hasOAuthCredentials() {\n return oauthCredentials.clientId !== 'YOUR_CLIENT_ID'\n && oauthCredentials.clientSecret !== 'YOUR_CLIENT_SECRET';\n}\n",
|
|
3684
3702
|
"../../project-templates/stand/advanced/module-federation/vite/src/dev/storageProvider.ts.eta": "<%~ include('stand-storage-provider', it) %>\n",
|
|
3685
|
-
"../../project-templates/stand/advanced/module-federation/vite/src/index.tsx.eta": "import { lazy, Suspense } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nconst EditorRemote = lazy(() => import('editor/Editor'));\n\nfunction HostApp() {\n return (\n <div style={{
|
|
3686
|
-
"../../project-templates/stand/advanced/module-federation/vite/src/remote/EditorApp.tsx.eta": "import { useEffect, useRef, useState } from 'react';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nexport default function EditorRemoteApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'module-federation',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: {\n ...editorConfig,\n codeMode: 'true',\n codeModeDirection: 'bottom',\n },\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{
|
|
3687
|
-
"../../project-templates/stand/advanced/module-federation/vite/src/remote/devShell.tsx": "import { createRoot } from 'react-dom/client';\n\n/** Dev-only remote shell; the MF host runs on
|
|
3703
|
+
"../../project-templates/stand/advanced/module-federation/vite/src/index.tsx.eta": "import { lazy, Suspense } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nconst EditorRemote = lazy(() => import('editor/Editor'));\n\nfunction HostApp() {\n return (\n <div style={{ boxSizing: 'border-box', display: 'flex', flexDirection: 'column', height: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0, width: '100%', margin: '0 auto', maxWidth: '1280px' }}>\n<% if (it.standShowModuleFederationBanner) { %>\n <div style={{ marginBottom: '12px', color: '#7c2d12', fontSize: '14px' }}>\n Module Federation stand — host at <code>{window.location.origin}/</code>, remote/CDN on the next port (set both with PLUGIN_DEV_PORT).\n </div>\n<% } %>\n <Suspense fallback={<div style={{ padding: '16px', fontSize: '14px' }}>Loading editor remote…</div>}>\n <EditorRemote />\n </Suspense>\n </div>\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (!rootElement) {\n throw new Error(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<HostApp />);\n",
|
|
3704
|
+
"../../project-templates/stand/advanced/module-federation/vite/src/remote/EditorApp.tsx.eta": "import { useEffect, useRef, useState } from 'react';\nimport * as <%= it.standProductApiName %> from '<%~ it.packageName %>';\nimport baseEmailHtml from '../dev/email.html?raw';\nimport { editorConfig } from '../dev/editorConfig';\nimport { getAuthToken } from '../dev/getAuthToken';\nimport { createLocalFolderStorageProvider } from '../dev/storageProvider';\n\n<%~ include('editor-init-smoke', it) %>\n<%~ include('stand-demo-email-id', it) %>\ntype EditorInstance = Awaited<ReturnType<typeof <%= it.standProductApiName %>.init>>;\n\nexport default function EditorRemoteApp() {\n const instanceRef = useRef<EditorInstance | null>(null);\n const [initError, setInitError] = useState<string | null>(null);\n\n useEffect(() => {\n async function run() {\n if (instanceRef.current) {\n return;\n }\n\n const mountElement = document.getElementById('editor-root');\n const smokeMeta = {\n hostKind: 'stand-host',\n variant: 'module-federation',\n mountLabel: '#editor-root',\n } as const;\n\n try {\n const instance = await <%= it.standProductApiName %>.init({\n getAuthToken,\n storageProvider: createLocalFolderStorageProvider(),\n element: '#editor-root',\n content: {\n email: {\n id: createDemoEmailId(),\n title: <%~ JSON.stringify(it.devHostDemoTitle) %>,\n code: baseEmailHtml,\n },\n },\n config: {\n ...editorConfig,\n codeMode: 'true',\n codeModeDirection: 'bottom',\n },\n });\n instanceRef.current = instance;\n reportEditorReady(smokeMeta, mountElement);\n } catch (error) {\n const message = reportEditorInitError(smokeMeta, error, mountElement);\n setInitError(message);\n }\n }\n\n run();\n }, []);\n\n return (\n <div style={{ display: 'flex', flex: 1, flexDirection: 'column', minHeight: 0 }}>\n {initError ? (\n <div style={{ marginBottom: '12px', color: '#b42318', fontSize: '14px' }}>\n Editor failed to initialize: {initError}\n </div>\n ) : null}\n <div id=\"editor-root\" style={{ flex: 1, minHeight: 0 }} />\n </div>\n );\n}\n",
|
|
3705
|
+
"../../project-templates/stand/advanced/module-federation/vite/src/remote/devShell.tsx": "import { createRoot } from 'react-dom/client';\n\n/** Dev-only remote shell; the MF host runs on the port just below this one. */\nfunction RemoteDevShell() {\n return (\n <div style={{ padding: '16px', fontFamily: 'system-ui, sans-serif', fontSize: '14px', color: '#44506b' }}>\n Editor MF remote ({window.location.host}). Open the host on the previous port.\n </div>\n );\n}\n\nconst rootElement = document.getElementById('root');\n\nif (rootElement) {\n createRoot(rootElement).render(<RemoteDevShell />);\n}\n",
|
|
3688
3706
|
"../../project-templates/stand/advanced/module-federation/vite/src/types/mf.d.ts": "declare module 'editor/Editor' {\n import type { ComponentType } from 'react';\n\n const EditorRemoteApp: ComponentType;\n export default EditorRemoteApp;\n}\n",
|
|
3689
3707
|
"../../project-templates/stand/advanced/shadow-dom/vite/README.md.eta": "<%~ include('stand-readme', it) %>\n",
|
|
3690
3708
|
"../../project-templates/stand/advanced/shadow-dom/vite/config/dev-host.ts.eta": "<%~ include('stand-dev-host-vite', it) %>\n",
|
|
@@ -3752,13 +3770,13 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3752
3770
|
"../../project-templates/stand/angular/esbuild/esbuild/plugins.cjs.eta": "const fs = require('node:fs');\nconst path = require('node:path');\n\n/** Vite-style `?raw` imports for stand dev email HTML (webpack used asset/source rule). */\nconst rawImportPlugin = {\n name: 'stand-raw-import',\n setup(build) {\n build.onResolve({ filter: /\\?raw$/ }, (args) => {\n const sourcePath = args.path.replace(/\\?raw$/, '');\n return {\n path: path.resolve(args.resolveDir, sourcePath),\n namespace: 'stand-raw-import',\n };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'stand-raw-import' }, async (args) => {\n const contents = await fs.promises.readFile(args.path, 'utf8');\n return {\n contents: `export default ${JSON.stringify(contents)};`,\n loader: 'js',\n };\n });\n },\n};\n\nmodule.exports = [rawImportPlugin];\n",
|
|
3753
3771
|
"../../project-templates/stand/angular/esbuild/esbuild/publicPath-shim.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst publicPath = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nconst root = window as unknown as Record<string, ProductNamespace | undefined>;\n\nroot[namespace] = {\n ...(root[namespace] ?? {}),\n publicPath,\n};\n\nexport {};\n",
|
|
3754
3772
|
"../../project-templates/stand/angular/esbuild/package.json.eta": "<%~ include('stand-package-json', it) %>\n",
|
|
3755
|
-
"../../project-templates/stand/angular/esbuild/proxy.conf.json.eta": "{\n \"/api\": {\n \"target\": <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n \"secure\": false,\n \"changeOrigin\": true,\n \"headers\": {\n \"origin\": <%~ JSON.stringify(it.standOpenApiOrigin) %>\n }\n }\n}\n",
|
|
3773
|
+
"../../project-templates/stand/angular/esbuild/proxy.conf.json.eta": "{\n \"/api\": {\n \"target\": <%~ JSON.stringify(it.standOpenApiBaseUrl) %>,\n \"secure\": false,\n \"changeOrigin\": true,\n \"pathRewrite\": { \"^/api\": \"\" },\n \"headers\": {\n \"origin\": <%~ JSON.stringify(it.standOpenApiOrigin) %>\n }\n }\n}\n",
|
|
3756
3774
|
"../../project-templates/stand/angular/esbuild/scripts/chunkRepro.cjs.eta": "#!/usr/bin/env node\n/**\n * Cross-origin chunk repro: HTML on :4200, JS chunks and <base href> on :4201.\n * Lazy chunk import.meta.url points at the CDN host; product assets stay on the page\n * origin (panel/<app>/).\n * Compile graph: thin facade only (~0.4 MB); static/esm is copied into panel/, not bundled.\n *\n * Usage: npm run build:rebundle && npm run serve:chunk-repro\n */\nconst http = require('node:http');\nconst https = require('node:https');\nconst fs = require('node:fs');\nconst path = require('node:path');\nconst { URL } = require('node:url');\n\nconst API_PROXY_ENABLED = <%= it.standClosedLoop ? 'false' : 'true' %>;\nconst API_TARGET = <%~ JSON.stringify(it.standOpenApiBaseUrl) %>;\nconst API_ORIGIN = <%~ JSON.stringify(it.standOpenApiOrigin) %>;\nconst SITE_PORT = 4200;\nconst CDN_PORT = 4201;\n// <base href> points at the CDN, so every relative path (publicPath from the shim,\n// iframe src, worker url) resolves against that origin instead of the page origin.\n// STAND_CDN_BASE_HREF=0 keeps the page base href for comparison.\nconst CDN_BASE_HREF = process.env.STAND_CDN_BASE_HREF !== '0';\nconst DIST_RELATIVE = <%~ JSON.stringify(it.standAngularChunkReproDistRelative) %>;\n\nconst MIME = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n};\n\nconst STATIC_HEADERS = {\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n};\n\n// The page origin and the API port differ under this repro, so proxied answers need CORS.\nconst CORS_HEADERS = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Max-Age': '600',\n};\n\nfunction contentType(filePath) {\n return MIME[path.extname(filePath).toLowerCase()] || 'application/octet-stream';\n}\n\nfunction resolveFile(distDir, requestPath) {\n const safe = path.normalize(requestPath).replace(/^(\\.\\.[/\\\\])+/, '');\n const candidate = path.join(distDir, safe);\n if (!candidate.startsWith(distDir)) return null;\n if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n return null;\n}\n\nfunction patchIndexHtml(html, cdnOrigin) {\n const patched = html.replace(\n /(<script\\b[^>]*\\ssrc=\")(?!https?:|\\/\\/)([^\"]+)\"/gi,\n (_, prefix, src) => `${prefix}${cdnOrigin}/${src.replace(/^\\//, '')}\"`,\n );\n\n if (!CDN_BASE_HREF) {\n return patched;\n }\n\n return patched.replace(/(<base\\b[^>]*\\shref=\")[^\"]*\"/i, (_, prefix) => `${prefix}${cdnOrigin}/\"`);\n}\n\nfunction readRequestBody(req) {\n return new Promise((resolve, reject) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n}\n\nfunction buildProxyRequestHeaders(req, targetUrl, bodyLength) {\n const headers = { ...req.headers, host: targetUrl.host };\n if (headers.origin) {\n headers.origin = API_ORIGIN;\n }\n delete headers.connection;\n delete headers['transfer-encoding'];\n if (bodyLength > 0) {\n headers['content-length'] = String(bodyLength);\n } else {\n delete headers['content-length'];\n }\n return headers;\n}\n\nfunction drainResponse(proxyRes) {\n return new Promise((resolve) => {\n proxyRes.on('end', resolve);\n proxyRes.resume();\n });\n}\n\nfunction proxyApiRequest(req, res, targetUrl, body, redirectCount, method) {\n const MAX_REDIRECTS = 5;\n if (redirectCount > MAX_REDIRECTS) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Too many redirects');\n return;\n }\n\n const requestMethod = method || req.method || 'GET';\n const transport = targetUrl.protocol === 'https:' ? https : http;\n const headers = buildProxyRequestHeaders(req, targetUrl, body.length);\n\n const proxyReq = transport.request(\n targetUrl,\n { method: requestMethod, headers },\n (proxyRes) => {\n const status = proxyRes.statusCode || 502;\n const location = proxyRes.headers.location;\n if (status >= 300 && status < 400 && location) {\n drainResponse(proxyRes).then(() => {\n const nextUrl = new URL(location, targetUrl);\n const useGet = status === 303;\n proxyApiRequest(\n req,\n res,\n nextUrl,\n useGet ? Buffer.alloc(0) : body,\n redirectCount + 1,\n useGet ? 'GET' : requestMethod,\n );\n });\n return;\n }\n\n const outHeaders = { ...proxyRes.headers, ...CORS_HEADERS };\n delete outHeaders.location;\n res.writeHead(status, outHeaders);\n proxyRes.pipe(res);\n },\n );\n\n proxyReq.on('error', (error) => {\n console.error('[chunkRepro] API proxy error:', error.message);\n if (!res.headersSent) {\n res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('Bad Gateway');\n }\n });\n\n if (body.length > 0) {\n proxyReq.write(body);\n }\n proxyReq.end();\n}\n\nasync function proxyApi(req, res) {\n const body = await readRequestBody(req);\n const targetUrl = new URL(req.url || '/', API_TARGET);\n proxyApiRequest(req, res, targetUrl, body, 0);\n}\n\nfunction createStaticServer(distDir, port, options = {}) {\n const { patchIndex = false, cdnOrigin = '' } = options;\n\n return http.createServer((req, res) => {\n const url = new URL(req.url || '/', `http://127.0.0.1:${port}`);\n const pathname = decodeURIComponent(url.pathname);\n\n // Both servers proxy /api: with <base href> on the CDN even a root-relative\n // fetch('/api') takes its origin from the base, so it lands on the CDN port.\n if (API_PROXY_ENABLED && pathname.startsWith('/api')) {\n if ((req.method || '').toUpperCase() === 'OPTIONS') {\n res.writeHead(204, CORS_HEADERS);\n res.end();\n return;\n }\n proxyApi(req, res);\n return;\n }\n\n let filePath = resolveFile(distDir, pathname === '/' ? '/index.html' : pathname);\n\n if (!filePath) {\n res.writeHead(404, STATIC_HEADERS);\n res.end('Not found');\n return;\n }\n\n if (patchIndex && filePath.endsWith('index.html')) {\n const raw = fs.readFileSync(filePath, 'utf8');\n res.writeHead(200, { ...STATIC_HEADERS, 'Content-Type': 'text/html; charset=utf-8' });\n res.end(patchIndexHtml(raw, cdnOrigin));\n return;\n }\n\n res.writeHead(200, { ...STATIC_HEADERS, 'Content-Type': contentType(filePath) });\n fs.createReadStream(filePath).pipe(res);\n }).listen(port, () => {\n console.log(`[chunkRepro] ${patchIndex ? 'site' : 'cdn'} → http://localhost:${port}/`);\n if (API_PROXY_ENABLED) {\n console.log(`[chunkRepro] /api → ${API_TARGET}`);\n }\n });\n}\n\nconst distDir = path.resolve(process.cwd(), DIST_RELATIVE);\nif (!fs.existsSync(path.join(distDir, 'index.html'))) {\n console.error(`[chunkRepro] Missing ${DIST_RELATIVE}/index.html — run \\`npm run build:rebundle\\` first.`);\n process.exit(1);\n}\n\nconst cdnOrigin = `http://localhost:${CDN_PORT}`;\ncreateStaticServer(distDir, CDN_PORT);\ncreateStaticServer(distDir, SITE_PORT, { patchIndex: true, cdnOrigin });\n\nconsole.log(\n CDN_BASE_HREF\n ? `[chunkRepro] <base href> → ${cdnOrigin}/ (set STAND_CDN_BASE_HREF=0 to disable)`\n : '[chunkRepro] <base href> left on the page origin',\n);\nconsole.log('[chunkRepro] Open http://localhost:4200/ — check Network + console [publicPath-diag]');\n",
|
|
3757
3775
|
"../../project-templates/stand/angular/esbuild/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
|
|
3758
3776
|
"../../project-templates/stand/angular/esbuild/scripts/formidable.d.ts": "declare module 'formidable';\n",
|
|
3759
3777
|
"../../project-templates/stand/angular/esbuild/scripts/publicPathDiagnostics.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nexport type PublicPathDiagSnapshot = {\n label: string;\n pageOrigin: string;\n pageHref: string;\n baseURI: string;\n windowNamespacePublicPath: string | undefined;\n expectedShimPrefix: string;\n bareNamespaceReadable: boolean;\n bareNamespacePublicPath: string | undefined;\n resolvedFromBaseURI: string;\n resolvedFromPageOrigin: string;\n basesDiverge: boolean;\n};\n\n/**\n * resolveAgainst expands publicPath against the given base; empty string when the base is invalid.\n * A relative publicPath resolves to different addresses against <base href> and the page origin;\n * that divergence is what breaks asset loading when base href points at another origin.\n */\nfunction resolveAgainst(publicPath: string | undefined, base: string): string {\n if (!publicPath || !base) {\n return '';\n }\n try {\n return new URL(publicPath, base).href;\n } catch {\n return '';\n }\n}\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst expectedShimPrefix = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nfunction readBareNamespacePublicPath(): { readable: boolean; publicPath: string | undefined } {\n try {\n // eslint-disable-next-line no-new-func\n const read = new Function(\n `try { return typeof <%= it.standWindowNamespace %> !== 'undefined' ? <%= it.standWindowNamespace %>.publicPath : undefined; } catch (e) { return undefined; }`,\n ) as () => string | undefined;\n return { readable: true, publicPath: read() };\n } catch {\n return { readable: false, publicPath: undefined };\n }\n}\n\nexport function snapshotPublicPathDiagnostics(label: string): PublicPathDiagSnapshot {\n const root = window as unknown as Record<string, ProductNamespace | undefined>;\n const bare = readBareNamespacePublicPath();\n const pageOrigin = window.location.origin;\n const baseURI = typeof document !== 'undefined' ? document.baseURI : '';\n const publicPath = root[namespace]?.publicPath;\n const resolvedFromBaseURI = resolveAgainst(publicPath, baseURI);\n const resolvedFromPageOrigin = resolveAgainst(publicPath, pageOrigin);\n\n const snapshot: PublicPathDiagSnapshot = {\n label,\n pageOrigin,\n pageHref: window.location.href,\n baseURI,\n windowNamespacePublicPath: publicPath,\n expectedShimPrefix,\n bareNamespaceReadable: bare.readable,\n bareNamespacePublicPath: bare.publicPath,\n resolvedFromBaseURI,\n resolvedFromPageOrigin,\n basesDiverge: Boolean(resolvedFromBaseURI) && resolvedFromBaseURI !== resolvedFromPageOrigin,\n };\n\n const bag = window as unknown as { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n bag.__standPublicPathDiagnostics = [...(bag.__standPublicPathDiagnostics ?? []), snapshot];\n console.info('[publicPath-diag]', label, snapshot);\n return snapshot;\n}\n",
|
|
3760
3778
|
"../../project-templates/stand/angular/esbuild/scripts/standDevMiddleware.ts.eta": "import type { IncomingMessage, ServerResponse } from 'node:http';\n\nimport devStorageMiddleware from './devStorageMiddleware';\n\nconst HOST_EDITOR_ASSET_HEADERS = Object.freeze({\n 'Cross-Origin-Resource-Policy': 'cross-origin',\n 'Access-Control-Allow-Origin': '*',\n});\n\ntype ConnectMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n) => void;\n\nfunction createHostEditorHeaderMiddleware(): ConnectMiddleware {\n return (_req, res, next) => {\n for (const [key, value] of Object.entries(HOST_EDITOR_ASSET_HEADERS)) {\n res.setHeader(key, value);\n }\n next();\n };\n}\n\nconst middlewares: ConnectMiddleware[] = [\n createHostEditorHeaderMiddleware(),\n devStorageMiddleware(),\n];\n\nexport default middlewares;\n",
|
|
3761
|
-
"../../project-templates/stand/angular/esbuild/src/app/app.component.css": ".page {\n font-family: system-ui, sans-serif;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n min-height:
|
|
3779
|
+
"../../project-templates/stand/angular/esbuild/src/app/app.component.css": ".page {\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n font-family: system-ui, sans-serif;\n height: 100vh;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n flex-shrink: 0;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n flex: 1;\n min-height: 0;\n}\n",
|
|
3762
3780
|
"../../project-templates/stand/angular/esbuild/src/app/app.component.html.eta": "<main class=\"page\">\n @if (initError()) {\n <p class=\"error\">Editor failed: {{ initError() }}</p>\n }\n @if (publicPathDiag()) {\n <pre class=\"diag\">{{ publicPathDiag() }}</pre>\n }\n <div id=\"editor-root\" class=\"editor-mount\"></div>\n</main>\n",
|
|
3763
3781
|
"../../project-templates/stand/angular/esbuild/src/app/app.component.ts.eta": "import { Component, AfterViewInit, signal } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport type { PublicPathDiagSnapshot } from '../../scripts/publicPathDiagnostics';\n\ntype DiagBag = { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [CommonModule],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css',\n})\nexport class AppComponent implements AfterViewInit {\n readonly initError = signal<string | null>(null);\n readonly publicPathDiag = signal<string | null>(null);\n\n ngAfterViewInit(): void {\n import('./editor-host')\n .then(({ initOAuthEditor }) => initOAuthEditor())\n .then(() => {\n const bag = window as unknown as DiagBag;\n const last = bag.__standPublicPathDiagnostics?.at(-1);\n if (last) {\n this.publicPathDiag.set(JSON.stringify(last, null, 2));\n }\n })\n .catch((error) => {\n this.initError.set(error instanceof Error ? error.message : String(error));\n });\n }\n}\n",
|
|
3764
3782
|
"../../project-templates/stand/angular/esbuild/src/app/app.config.ts.eta": "import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\n\nexport const appConfig: ApplicationConfig = {\n providers: [provideZoneChangeDetection({ eventCoalescing: true })],\n};\n",
|
|
@@ -3784,7 +3802,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3784
3802
|
"../../project-templates/stand/angular/webpack/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
|
|
3785
3803
|
"../../project-templates/stand/angular/webpack/scripts/publicPath-shim.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst publicPath = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nconst root = window as unknown as Record<string, ProductNamespace | undefined>;\n\nroot[namespace] = {\n ...(root[namespace] ?? {}),\n publicPath,\n};\n\nexport {};\n",
|
|
3786
3804
|
"../../project-templates/stand/angular/webpack/scripts/publicPathDiagnostics.ts.eta": "type ProductNamespace = {\n publicPath?: string;\n};\n\nexport type PublicPathDiagSnapshot = {\n label: string;\n pageOrigin: string;\n pageHref: string;\n baseURI: string;\n windowNamespacePublicPath: string | undefined;\n expectedShimPrefix: string;\n bareNamespaceReadable: boolean;\n bareNamespacePublicPath: string | undefined;\n};\n\nconst namespace = <%~ JSON.stringify(it.standWindowNamespace) %>;\nconst expectedShimPrefix = <%~ JSON.stringify(it.standAngularProductPublicPath + '/') %>;\n\nfunction readBareNamespacePublicPath(): { readable: boolean; publicPath: string | undefined } {\n try {\n // eslint-disable-next-line no-new-func\n const read = new Function(\n `try { return typeof <%= it.standWindowNamespace %> !== 'undefined' ? <%= it.standWindowNamespace %>.publicPath : undefined; } catch (e) { return undefined; }`,\n ) as () => string | undefined;\n return { readable: true, publicPath: read() };\n } catch {\n return { readable: false, publicPath: undefined };\n }\n}\n\nexport function snapshotPublicPathDiagnostics(label: string): PublicPathDiagSnapshot {\n const root = window as unknown as Record<string, ProductNamespace | undefined>;\n const bare = readBareNamespacePublicPath();\n\n const snapshot: PublicPathDiagSnapshot = {\n label,\n pageOrigin: window.location.origin,\n pageHref: window.location.href,\n baseURI: typeof document !== 'undefined' ? document.baseURI : '',\n windowNamespacePublicPath: root[namespace]?.publicPath,\n expectedShimPrefix,\n bareNamespaceReadable: bare.readable,\n bareNamespacePublicPath: bare.publicPath,\n };\n\n const bag = window as unknown as { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n bag.__standPublicPathDiagnostics = [...(bag.__standPublicPathDiagnostics ?? []), snapshot];\n console.info('[publicPath-diag]', label, snapshot);\n return snapshot;\n}\n",
|
|
3787
|
-
"../../project-templates/stand/angular/webpack/src/app/app.component.css": ".page {\n font-family: system-ui, sans-serif;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n min-height:
|
|
3805
|
+
"../../project-templates/stand/angular/webpack/src/app/app.component.css": ".page {\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n font-family: system-ui, sans-serif;\n height: 100vh;\n margin: 0 auto;\n max-width: 1200px;\n padding: 16px;\n}\n\n.error {\n color: #b42318;\n margin: 0 0 12px;\n}\n\n.diag {\n background: #f4f4f5;\n border: 1px solid #d4d4d8;\n flex-shrink: 0;\n font-size: 12px;\n margin: 0 0 12px;\n max-height: 200px;\n overflow: auto;\n padding: 8px;\n}\n\n.editor-mount {\n flex: 1;\n min-height: 0;\n}\n",
|
|
3788
3806
|
"../../project-templates/stand/angular/webpack/src/app/app.component.html.eta": "<main class=\"page\">\n @if (initError()) {\n <p class=\"error\">Editor failed: {{ initError() }}</p>\n }\n @if (publicPathDiag()) {\n <pre class=\"diag\">{{ publicPathDiag() }}</pre>\n }\n <div id=\"editor-root\" class=\"editor-mount\"></div>\n</main>\n",
|
|
3789
3807
|
"../../project-templates/stand/angular/webpack/src/app/app.component.ts.eta": "import { Component, AfterViewInit, signal } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport type { PublicPathDiagSnapshot } from '../../scripts/publicPathDiagnostics';\n\ntype DiagBag = { __standPublicPathDiagnostics?: PublicPathDiagSnapshot[] };\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [CommonModule],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css',\n})\nexport class AppComponent implements AfterViewInit {\n readonly initError = signal<string | null>(null);\n readonly publicPathDiag = signal<string | null>(null);\n\n ngAfterViewInit(): void {\n import('./editor-host')\n .then(({ initOAuthEditor }) => initOAuthEditor())\n .then(() => {\n const bag = window as unknown as DiagBag;\n const last = bag.__standPublicPathDiagnostics?.at(-1);\n if (last) {\n this.publicPathDiag.set(JSON.stringify(last, null, 2));\n }\n })\n .catch((error) => {\n this.initError.set(error instanceof Error ? error.message : String(error));\n });\n }\n}\n",
|
|
3790
3808
|
"../../project-templates/stand/angular/webpack/src/app/app.config.ts.eta": "import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\n\nexport const appConfig: ApplicationConfig = {\n providers: [provideZoneChangeDetection({ eventCoalescing: true })],\n};\n",
|
|
@@ -3997,6 +4015,7 @@ function buildPluginPackageJsonData(options) {
|
|
|
3997
4015
|
const extensionsSandboxVersion = localTarballs?.extensionsSandboxPackageName || packageConfig.extensionsSandboxVersion;
|
|
3998
4016
|
const extensionsReactVersion = localTarballs?.extensionsReactPackageName || packageConfig.extensionsReactVersion;
|
|
3999
4017
|
const uiKitVersion = localTarballs?.uiKitPackageName || packageConfig.uiKitVersion;
|
|
4018
|
+
const startProductionScript = localTarballs ? "tsx ./scripts/production-runner.ts --bundler-runtime-strict" : "tsx ./scripts/production-runner.ts";
|
|
4000
4019
|
const releaseHostCommand = bundler === "vite" ? `vite --config ./${releaseConfig}` : `${WEBPACK_CLI_COMMAND} serve --config ./${releaseConfig} --mode development`;
|
|
4001
4020
|
const mainPkgKey = resolveLocalPublishedPackageKey(localPublishedNames, "packageName", packageConfig.packageName);
|
|
4002
4021
|
const extApiKey = resolveLocalPublishedPackageKey(localPublishedNames, "extensionsApiPackageName", packageConfig.extensionsApiPackageName);
|
|
@@ -4044,9 +4063,12 @@ function buildPluginPackageJsonData(options) {
|
|
|
4044
4063
|
scripts: bundler === "vite" ? {
|
|
4045
4064
|
start: "tsx ./scripts/dev-runner.ts",
|
|
4046
4065
|
"start:release": startReleaseScript,
|
|
4066
|
+
"start:production": startProductionScript,
|
|
4047
4067
|
"dev:app": "tsx ./scripts/dev-runner.ts",
|
|
4048
4068
|
"dev:host": `vite --config ./${generatedPaths.devConfig}`,
|
|
4049
4069
|
"dev:release-host": releaseHostCommand,
|
|
4070
|
+
"build:release-host": `vite build --config ./${releaseConfig}`,
|
|
4071
|
+
"preview:release-host": `vite preview --config ./${releaseConfig}`,
|
|
4050
4072
|
"dev:sandbox": `vite build --config ./${generatedPaths.sandboxBuildConfig} --watch --mode development`,
|
|
4051
4073
|
"dev:sandbox:once": `vite build --config ./${generatedPaths.sandboxBuildConfig} --mode development`,
|
|
4052
4074
|
build: "tsx ./scripts/build-runner.ts",
|
|
@@ -4056,9 +4078,12 @@ function buildPluginPackageJsonData(options) {
|
|
|
4056
4078
|
} : {
|
|
4057
4079
|
start: "tsx ./scripts/dev-runner.ts",
|
|
4058
4080
|
"start:release": startReleaseScript,
|
|
4081
|
+
"start:production": startProductionScript,
|
|
4059
4082
|
"dev:app": "tsx ./scripts/dev-runner.ts",
|
|
4060
4083
|
"dev:host": `${WEBPACK_CLI_COMMAND} serve --config ./${generatedPaths.devConfig} --mode development`,
|
|
4061
4084
|
"dev:release-host": releaseHostCommand,
|
|
4085
|
+
"build:release-host": `${WEBPACK_CLI_COMMAND} --config ./${releaseConfig} --mode production`,
|
|
4086
|
+
"preview:release-host": `${WEBPACK_CLI_COMMAND} serve --config ./${releaseConfig} --mode production`,
|
|
4062
4087
|
"dev:sandbox": `${WEBPACK_CLI_COMMAND} --config ./${generatedPaths.sandboxBuildConfig} --mode development --watch`,
|
|
4063
4088
|
"dev:sandbox:once": `${WEBPACK_CLI_COMMAND} --config ./${generatedPaths.sandboxBuildConfig} --mode development`,
|
|
4064
4089
|
build: "tsx ./scripts/build-runner.ts",
|
|
@@ -4214,6 +4239,8 @@ function buildPluginEtaData(templateOptions) {
|
|
|
4214
4239
|
const isTemplating = preset === "templating";
|
|
4215
4240
|
const productApiName = String(packageConfig?.appName || "app").replace(/[^a-zA-Z0-9_$]/g, "") || "app";
|
|
4216
4241
|
const releaseUsesUmd = pluginFormat === "umd";
|
|
4242
|
+
const releaseHostCompatGlobals = importsMode !== "esm";
|
|
4243
|
+
const devHostCompatGlobals = isLegacyWebpack;
|
|
4217
4244
|
const targetLabel = formatPluginTargetTemplateLabel(t, target, advancedTarget);
|
|
4218
4245
|
const pluginKeyLiteral = toLiteral(pluginKey);
|
|
4219
4246
|
const importsModeLiteral = toLiteral(importsMode);
|
|
@@ -4262,6 +4289,8 @@ function buildPluginEtaData(templateOptions) {
|
|
|
4262
4289
|
pluginFormatVite,
|
|
4263
4290
|
productApiName,
|
|
4264
4291
|
releaseUsesUmd,
|
|
4292
|
+
releaseHostCompatGlobals,
|
|
4293
|
+
devHostCompatGlobals,
|
|
4265
4294
|
bundler,
|
|
4266
4295
|
importsMode,
|
|
4267
4296
|
pluginFormat,
|
|
@@ -4398,6 +4427,7 @@ function getPostCreateRunCommands(startMode, options, packageManager = "npm") {
|
|
|
4398
4427
|
if (isAngularEsbuildStand(options)) return [[packageManager, ["run", "build"]], [packageManager, ["run", "serve:chunk-repro"]]];
|
|
4399
4428
|
return [[packageManager, ["run", "build:rebundle"]], [packageManager, ["run", "serve:chunk-repro"]]];
|
|
4400
4429
|
}
|
|
4430
|
+
if (startMode === "production" && options.kind !== "demo-stand") return [[packageManager, ["run", "start:production"]]];
|
|
4401
4431
|
if (options.kind === "demo-stand") {
|
|
4402
4432
|
if (isModuleFederationStand(options)) return [[packageManager, ["run", "start"]]];
|
|
4403
4433
|
const serveScript = getStandProductionServeScript(options);
|
|
@@ -4517,6 +4547,10 @@ async function promptForPostCreateActions(options, messages) {
|
|
|
4517
4547
|
title: isStand ? messages.promptStandStartModeRelease : messages.promptStartModeRelease,
|
|
4518
4548
|
value: "release"
|
|
4519
4549
|
},
|
|
4550
|
+
...isStand ? [] : [{
|
|
4551
|
+
title: messages.promptStartModeProduction,
|
|
4552
|
+
value: "production"
|
|
4553
|
+
}],
|
|
4520
4554
|
...isAngularReproStand ? [{
|
|
4521
4555
|
title: messages.promptStandStartModeRepro,
|
|
4522
4556
|
value: "repro"
|
|
@@ -4552,34 +4586,35 @@ function printNextSteps(result, options, actions, messages, credentialsReady = f
|
|
|
4552
4586
|
title: messages.nextStepFillCredentials,
|
|
4553
4587
|
command: getCredentialsMessage(options, messages)
|
|
4554
4588
|
});
|
|
4555
|
-
if (options.kind === "plugin")
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4589
|
+
if (options.kind === "plugin") {
|
|
4590
|
+
if (!actions.installDependencies) steps.push({
|
|
4591
|
+
title: messages.nextStepInstall,
|
|
4592
|
+
command: installCommand
|
|
4593
|
+
}, {
|
|
4594
|
+
title: messages.nextStepStartDebug,
|
|
4595
|
+
command: startDebugCommand
|
|
4596
|
+
}, {
|
|
4597
|
+
title: messages.nextStepStartRelease,
|
|
4598
|
+
command: startReleaseCommand
|
|
4599
|
+
});
|
|
4600
|
+
else if (actions.startMode === "none") steps.push({
|
|
4601
|
+
title: messages.nextStepAlreadyInstalled,
|
|
4602
|
+
command: null
|
|
4603
|
+
}, {
|
|
4604
|
+
title: messages.nextStepStartDebug,
|
|
4605
|
+
command: startDebugCommand
|
|
4606
|
+
}, {
|
|
4607
|
+
title: messages.nextStepStartRelease,
|
|
4608
|
+
command: startReleaseCommand
|
|
4609
|
+
});
|
|
4610
|
+
else steps.push({
|
|
4611
|
+
title: messages.nextStepAlreadyInstalled,
|
|
4612
|
+
command: null
|
|
4613
|
+
}, {
|
|
4614
|
+
title: actions.startMode === "release" ? messages.nextStepServerStartingRelease : messages.nextStepServerStartingDebug,
|
|
4615
|
+
command: null
|
|
4616
|
+
});
|
|
4617
|
+
} else if (!actions.installDependencies) steps.push({
|
|
4583
4618
|
title: messages.nextStepInstall,
|
|
4584
4619
|
command: installCommand
|
|
4585
4620
|
}, {
|