useblocks-cli 1.1.81 → 1.1.85-dev.1
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 +98 -72
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ The list below covers the main options available to end users through `--help`.
|
|
|
8
8
|
|
|
9
9
|
### `--dev` / `--dev-packages`
|
|
10
10
|
|
|
11
|
-
**The flag you will use most often in day-to-day development:**
|
|
11
|
+
**The flag you will use most often in day-to-day development:** in the generated project, ecosystem packages get the `dev` dist-tag instead of `latest`. Use it when you need fresh prerelease builds.
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
14
|
npx useblocks-cli my-plugin --kind plugin --preset advanced --bundler vite --target npm-package --dev --output-dir ./my-plugin
|
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.1";
|
|
426
|
+
var DEFAULT_UI_KIT_VERSION = "1.1.85-dev.1";
|
|
427
|
+
var DEFAULT_CLI_VERSION = "1.1.85-dev.1";
|
|
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";
|
|
@@ -1463,13 +1465,13 @@ var ROOT_PKG = {
|
|
|
1463
1465
|
engines: { "node": ">=24.0.0" },
|
|
1464
1466
|
packageManager: "pnpm@11.4.0",
|
|
1465
1467
|
dependencies: {
|
|
1468
|
+
"@ant-design/icons": "^6.1.0",
|
|
1469
|
+
"@babel/runtime": "^7.26.0",
|
|
1466
1470
|
"@easylogic/colorpicker": "1.10.7",
|
|
1467
|
-
"@emailmaker/filemanager": "workspace:*",
|
|
1468
|
-
"@emailmaker/ui-kit": "workspace:*",
|
|
1469
1471
|
"@emailmaker/extensions-api": "workspace:*",
|
|
1470
1472
|
"@emailmaker/extensions-react": "workspace:*",
|
|
1471
|
-
"@
|
|
1472
|
-
"@
|
|
1473
|
+
"@emailmaker/filemanager": "workspace:*",
|
|
1474
|
+
"@emailmaker/ui-kit": "workspace:*",
|
|
1473
1475
|
"@internal/core-loader": "workspace:*",
|
|
1474
1476
|
"app-core": "workspace:*",
|
|
1475
1477
|
"browserExtensionSanitizer": "workspace:*",
|
|
@@ -1510,7 +1512,7 @@ var ROOT_PKG = {
|
|
|
1510
1512
|
"@types/js-cookie": "^3.0.6",
|
|
1511
1513
|
"@wordpress/i18n": "^4.58.0",
|
|
1512
1514
|
"@wordpress/react-i18n": "^3.15.0",
|
|
1513
|
-
"antd": "
|
|
1515
|
+
"antd": "6.3.5",
|
|
1514
1516
|
"autoprefixer": "10.4.5",
|
|
1515
1517
|
"axios": "^1.7.9",
|
|
1516
1518
|
"browser-image-compression": "^2.0.2",
|
|
@@ -1521,8 +1523,9 @@ var ROOT_PKG = {
|
|
|
1521
1523
|
"darkreader": "4.9.125",
|
|
1522
1524
|
"date-fns": "^2.27.0",
|
|
1523
1525
|
"dayjs": "^1.11.8",
|
|
1524
|
-
"deepmerge-ts": "^5.1.0",
|
|
1525
1526
|
"deepmerge": "^4.3.1",
|
|
1527
|
+
"deepmerge-ts": "^5.1.0",
|
|
1528
|
+
"documentCore": "workspace:*",
|
|
1526
1529
|
"effection": "^3.0.3",
|
|
1527
1530
|
"emmet": "^2.3.6",
|
|
1528
1531
|
"emmet-monaco-es": "file:local_modules/emmet-monaco-es",
|
|
@@ -1547,12 +1550,13 @@ var ROOT_PKG = {
|
|
|
1547
1550
|
"path-browserify": "^1.0.1",
|
|
1548
1551
|
"pixie": "file:local_modules/pixie",
|
|
1549
1552
|
"postal-mime": "^3.0.0",
|
|
1553
|
+
"source": "workspace:*",
|
|
1550
1554
|
"process": "^0.11.10",
|
|
1551
1555
|
"prop-types": "^15.8.1",
|
|
1556
|
+
"rc-input-number": "^9.5.0",
|
|
1552
1557
|
"react": "19.2.7",
|
|
1553
1558
|
"react-dom": "19.2.7",
|
|
1554
1559
|
"react-infinite-scroll-component": "^7.2.1",
|
|
1555
|
-
"rc-input-number": "^9.5.0",
|
|
1556
1560
|
"react-masonry-css": "^1.0.16",
|
|
1557
1561
|
"react-redux": "^7.2.3",
|
|
1558
1562
|
"react-refresh": "^0.18.0",
|
|
@@ -1560,15 +1564,15 @@ var ROOT_PKG = {
|
|
|
1560
1564
|
"react-split": "^2.0.13",
|
|
1561
1565
|
"react-sticky-box": "^1.0.1",
|
|
1562
1566
|
"react-transition-group": "^4.4.5",
|
|
1563
|
-
"regenerator-runtime": "^0.14.1",
|
|
1564
1567
|
"recharts": "^2.15.4",
|
|
1568
|
+
"regenerator-runtime": "^0.14.1",
|
|
1565
1569
|
"sass": "^1.44.0",
|
|
1566
1570
|
"save": "^2.9.0",
|
|
1567
1571
|
"selderee": "^0.11.0",
|
|
1568
1572
|
"sortablejs": "^1.15.2",
|
|
1569
1573
|
"stream-browserify": "^3.0.0",
|
|
1574
|
+
"textChange": "workspace:*",
|
|
1570
1575
|
"util": "^0.12.5",
|
|
1571
|
-
"uuid": "^13.0.0",
|
|
1572
1576
|
"vscode-html-languageservice": "^5.0.2",
|
|
1573
1577
|
"webfontloader": "^1.6.28",
|
|
1574
1578
|
"xss": "^1.0.14",
|
|
@@ -1581,6 +1585,7 @@ var ROOT_PKG = {
|
|
|
1581
1585
|
"build:global": "tsx build-tools/pipeline.ts --envMode=global",
|
|
1582
1586
|
"preview": "vite preview --config build-tools/config/presets/build.main.ts --mode production",
|
|
1583
1587
|
"build:cli": "tsx build-tools/cli/scripts/build.ts",
|
|
1588
|
+
"cli:local": "node build/cli/bin/createPlugin.js --local-test --local-build-dir ./build",
|
|
1584
1589
|
"emailmaker-cli": "node build/cli/bin/createPlugin.js --local-test --local-build-dir ./build",
|
|
1585
1590
|
"verify:cli": "tsx build-tools/cli/scripts/e2e/verify-global-cli.ts --cli-dir=build/cli",
|
|
1586
1591
|
"verify:cli:source": "tsx build-tools/cli/scripts/e2e/verify-global-cli.ts --source-tools",
|
|
@@ -1601,6 +1606,8 @@ var ROOT_PKG = {
|
|
|
1601
1606
|
"publish:npm": "node build-tools/scripts/publish/publish-from-manifest.mjs",
|
|
1602
1607
|
"publish:plan": "tsx build-tools/scripts/publish/publish-plan.ts",
|
|
1603
1608
|
"build:translations": "tsx build-tools/translations/extract.ts",
|
|
1609
|
+
"delivery:groups": "tsx build-tools/scripts/build/update-delivery-groups.ts",
|
|
1610
|
+
"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
1611
|
"build:bundler-plugins": "tsx build-tools/scripts/build/bundler-plugins.ts --build-dir build --mode dev",
|
|
1605
1612
|
"send:translations": "tsx build-tools/scripts/i18n/send-translations.ts",
|
|
1606
1613
|
"start:proxy": "env-cmd -f .env.dev tsx build-tools/proxy/client/server.ts --mountPath=/proxy",
|
|
@@ -1635,6 +1642,7 @@ var ROOT_PKG = {
|
|
|
1635
1642
|
"lint:types": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsc --noEmit && tsc -p build-tools/tsconfig.tooling.json",
|
|
1636
1643
|
"test:typecheck": "npm run lint:types && tsc -p iframe/tsconfig.json --noEmit && tsc -p packages/po/tsconfig.json --noEmit",
|
|
1637
1644
|
"type-check:tooling": "tsc -p build-tools/tsconfig.tooling.json",
|
|
1645
|
+
"diag:measure": "tsx build-tools/scripts/diagnostics/measure.ts",
|
|
1638
1646
|
"lint:new": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
|
|
1639
1647
|
"test:plugin-matrix": "tsx build-tools/scripts/dev/run-plugin-matrix.ts",
|
|
1640
1648
|
"lint:ci": "tsx build-tools/scripts/build/ensure-file-manager.ts && tsx build-tools/scripts/lint/diffAwareLint.ts",
|
|
@@ -1644,7 +1652,8 @@ var ROOT_PKG = {
|
|
|
1644
1652
|
"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
1653
|
"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
1654
|
"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"
|
|
1655
|
+
"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",
|
|
1656
|
+
"saas-check": "tsx build-tools/scripts/saas-check/run.ts"
|
|
1648
1657
|
},
|
|
1649
1658
|
browserslist: {
|
|
1650
1659
|
"production": [
|
|
@@ -1698,6 +1707,7 @@ var ROOT_PKG = {
|
|
|
1698
1707
|
"jest-junit": "^16.0.0",
|
|
1699
1708
|
"jsdom": "^16.7.0",
|
|
1700
1709
|
"less": "^4.1.3",
|
|
1710
|
+
"line-awesome": "^1.3.0",
|
|
1701
1711
|
"napi-postinstall": "^0.3.4",
|
|
1702
1712
|
"oxlint": "1.77.0",
|
|
1703
1713
|
"oxlint-tsgolint": "7.0.2001",
|
|
@@ -1707,7 +1717,7 @@ var ROOT_PKG = {
|
|
|
1707
1717
|
"postcss-preset-env": "^9.5.0",
|
|
1708
1718
|
"prettier": "^3.4.2",
|
|
1709
1719
|
"react-error-overlay": "6.0.9",
|
|
1710
|
-
"rolldown": "~1.
|
|
1720
|
+
"rolldown": "~1.2.6",
|
|
1711
1721
|
"rolldown-plugin-dts": "^0.28.0",
|
|
1712
1722
|
"rollup": "^4.61.1",
|
|
1713
1723
|
"sass-cast": "^0.5.6",
|
|
@@ -1726,7 +1736,7 @@ var ROOT_PKG = {
|
|
|
1726
1736
|
"tsdown": "^0.21.0-beta.2",
|
|
1727
1737
|
"tsx": "^4.21.0",
|
|
1728
1738
|
"typescript": "^7.0.2",
|
|
1729
|
-
"vite": "^8.
|
|
1739
|
+
"vite": "^8.3.0",
|
|
1730
1740
|
"vite-plugin-commonjs": "^0.10.4",
|
|
1731
1741
|
"vite-plugin-css-injected-by-js": "^4.0.1",
|
|
1732
1742
|
"vite-plugin-monaco-editor": "^1.1.0",
|
|
@@ -1737,7 +1747,7 @@ var ROOT_PKG = {
|
|
|
1737
1747
|
"yargs": "^17.5.1"
|
|
1738
1748
|
},
|
|
1739
1749
|
overrides: {
|
|
1740
|
-
"rolldown": "~1.
|
|
1750
|
+
"rolldown": "~1.2.6",
|
|
1741
1751
|
"monaco-html-linter": { "monaco-editor": "0.34.0" },
|
|
1742
1752
|
"@vitest/expect": "4.1.4",
|
|
1743
1753
|
"@vitest/runner": "4.1.4",
|
|
@@ -1809,6 +1819,7 @@ var LEGACY_REACT_DEPENDENCIES = {
|
|
|
1809
1819
|
react: extractPinned(getRootDependencyVersion("react")),
|
|
1810
1820
|
"react-dom": extractPinned(getRootDependencyVersion("react-dom")),
|
|
1811
1821
|
antd: extractPinned(getRootDependencyVersion("antd")),
|
|
1822
|
+
"@ant-design/icons": extractPinned(getRootDependencyVersion("@ant-design/icons")),
|
|
1812
1823
|
"@types/react": extractPinned(getRootDependencyVersion("@types/react")),
|
|
1813
1824
|
"@types/react-dom": extractPinned(getRootDependencyVersion("@types/react-dom"))
|
|
1814
1825
|
};
|
|
@@ -1993,14 +2004,21 @@ e({
|
|
|
1993
2004
|
name: "antd",
|
|
1994
2005
|
exportName: "Antd",
|
|
1995
2006
|
hasDefault: false,
|
|
1996
|
-
isCjs:
|
|
2007
|
+
isCjs: false,
|
|
2008
|
+
isLocalWorkspace: false
|
|
2009
|
+
}), e({
|
|
2010
|
+
name: "@ant-design/icons/es/components/AntdIcon",
|
|
2011
|
+
exportName: "AntDesignIconBase",
|
|
2012
|
+
hasDefault: true,
|
|
2013
|
+
isCjs: false,
|
|
1997
2014
|
isLocalWorkspace: false
|
|
1998
2015
|
}), e({
|
|
1999
2016
|
name: "@ant-design/icons",
|
|
2000
2017
|
exportName: "AntDesignIcons",
|
|
2001
2018
|
hasDefault: true,
|
|
2002
2019
|
isCjs: false,
|
|
2003
|
-
isLocalWorkspace: false
|
|
2020
|
+
isLocalWorkspace: false,
|
|
2021
|
+
delivery: "compat-lazy"
|
|
2004
2022
|
}), e({
|
|
2005
2023
|
name: "@ant-design/cssinjs",
|
|
2006
2024
|
exportName: "AntDesignCssinjs",
|
|
@@ -2020,12 +2038,6 @@ e({
|
|
|
2020
2038
|
hasDefault: true,
|
|
2021
2039
|
isCjs: true,
|
|
2022
2040
|
isLocalWorkspace: false
|
|
2023
|
-
}), e({
|
|
2024
|
-
name: "uuid",
|
|
2025
|
-
exportName: "Uuid",
|
|
2026
|
-
hasDefault: false,
|
|
2027
|
-
isCjs: false,
|
|
2028
|
-
isLocalWorkspace: false
|
|
2029
2041
|
}), e({
|
|
2030
2042
|
name: "di",
|
|
2031
2043
|
exportName: "Di",
|
|
@@ -3535,6 +3547,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3535
3547
|
"../../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
3548
|
"../../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
3549
|
"../../project-templates/plugin/shared-base/scripts/hostDevServerHeaders.ts.eta": "<%~ include('stand-host-dev-server-webpack', it) %>\n",
|
|
3550
|
+
"../../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
3551
|
"../../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
3552
|
"../../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
3553
|
"../../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 +3570,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3557
3570
|
"../../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
3571
|
"../../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
3572
|
"../../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\
|
|
3573
|
+
"../../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 <div id=\"editor-root\" />\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
3574
|
"../../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
3575
|
"../../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
3576
|
"../../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 +3580,34 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3567
3580
|
"../../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
3581
|
"../../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
3582
|
"../../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\
|
|
3583
|
+
"../../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",
|
|
3584
|
+
"../../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 <div id=\"editor-root\" />\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",
|
|
3585
|
+
"../../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 <div id=\"editor-root\" />\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",
|
|
3573
3586
|
"../../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",
|
|
3574
3587
|
"../../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(
|
|
3588
|
+
"../../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('../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
3589
|
"../../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
3590
|
"../../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
3591
|
"../../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",
|
|
3592
|
+
"../../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 } from '@ant-design/icons';\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\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
3593
|
"../../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
3594
|
"../../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
3595
|
"../../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
3596
|
"../../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
3597
|
"../../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
3598
|
"../../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",
|
|
3599
|
+
"../../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
3600
|
"../../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
3601
|
"../../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\
|
|
3602
|
+
"../../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
3603
|
"../../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
3604
|
"../../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",
|
|
3605
|
+
"../../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",
|
|
3606
|
+
"../../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
3607
|
"../../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
3608
|
"../../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
3609
|
"../../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",
|
|
3610
|
+
"../../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
3611
|
"../../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
3612
|
"../../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
3613
|
"../../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,14 +3624,14 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3611
3624
|
"../../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
3625
|
"../../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
3626
|
"../../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",
|
|
3627
|
+
"../../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",
|
|
3628
|
+
"../../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",
|
|
3629
|
+
"../../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
3630
|
"../../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
3631
|
"../../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
3632
|
"../../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
3633
|
"../../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
|
|
3634
|
+
"../../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",
|
|
3622
3635
|
"../../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 <>\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(<%~ JSON.stringify(it.commonRootElementNotFound) %>);\n}\n\ncreateRoot(rootElement).render(<EditorApp />);\n",
|
|
3623
3636
|
"../../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
3637
|
"../../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={{ minHeight: '100vh', background: '#f5f7fb', padding: '24px' }}>\n <div style={{ 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={{ minHeight: '100vh' }} />\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",
|
|
@@ -3640,7 +3653,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3640
3653
|
"../../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
3654
|
"../../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
3655
|
"../../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",
|
|
3656
|
+
"../../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
3657
|
"../../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
3658
|
"../../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
3659
|
"../../project-templates/shared/stand-vite-base/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
|
|
@@ -3752,7 +3765,7 @@ var rawTemplateModules = /* #__PURE__ */ Object.assign({
|
|
|
3752
3765
|
"../../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
3766
|
"../../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
3767
|
"../../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",
|
|
3768
|
+
"../../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
3769
|
"../../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
3770
|
"../../project-templates/stand/angular/esbuild/scripts/devStorageMiddleware.ts.eta": "<%~ include('stand-dev-storage-middleware', it) %>\n",
|
|
3758
3771
|
"../../project-templates/stand/angular/esbuild/scripts/formidable.d.ts": "declare module 'formidable';\n",
|
|
@@ -3997,6 +4010,7 @@ function buildPluginPackageJsonData(options) {
|
|
|
3997
4010
|
const extensionsSandboxVersion = localTarballs?.extensionsSandboxPackageName || packageConfig.extensionsSandboxVersion;
|
|
3998
4011
|
const extensionsReactVersion = localTarballs?.extensionsReactPackageName || packageConfig.extensionsReactVersion;
|
|
3999
4012
|
const uiKitVersion = localTarballs?.uiKitPackageName || packageConfig.uiKitVersion;
|
|
4013
|
+
const startProductionScript = localTarballs ? "tsx ./scripts/production-runner.ts --bundler-runtime-strict" : "tsx ./scripts/production-runner.ts";
|
|
4000
4014
|
const releaseHostCommand = bundler === "vite" ? `vite --config ./${releaseConfig}` : `${WEBPACK_CLI_COMMAND} serve --config ./${releaseConfig} --mode development`;
|
|
4001
4015
|
const mainPkgKey = resolveLocalPublishedPackageKey(localPublishedNames, "packageName", packageConfig.packageName);
|
|
4002
4016
|
const extApiKey = resolveLocalPublishedPackageKey(localPublishedNames, "extensionsApiPackageName", packageConfig.extensionsApiPackageName);
|
|
@@ -4044,9 +4058,12 @@ function buildPluginPackageJsonData(options) {
|
|
|
4044
4058
|
scripts: bundler === "vite" ? {
|
|
4045
4059
|
start: "tsx ./scripts/dev-runner.ts",
|
|
4046
4060
|
"start:release": startReleaseScript,
|
|
4061
|
+
"start:production": startProductionScript,
|
|
4047
4062
|
"dev:app": "tsx ./scripts/dev-runner.ts",
|
|
4048
4063
|
"dev:host": `vite --config ./${generatedPaths.devConfig}`,
|
|
4049
4064
|
"dev:release-host": releaseHostCommand,
|
|
4065
|
+
"build:release-host": `vite build --config ./${releaseConfig}`,
|
|
4066
|
+
"preview:release-host": `vite preview --config ./${releaseConfig}`,
|
|
4050
4067
|
"dev:sandbox": `vite build --config ./${generatedPaths.sandboxBuildConfig} --watch --mode development`,
|
|
4051
4068
|
"dev:sandbox:once": `vite build --config ./${generatedPaths.sandboxBuildConfig} --mode development`,
|
|
4052
4069
|
build: "tsx ./scripts/build-runner.ts",
|
|
@@ -4056,9 +4073,12 @@ function buildPluginPackageJsonData(options) {
|
|
|
4056
4073
|
} : {
|
|
4057
4074
|
start: "tsx ./scripts/dev-runner.ts",
|
|
4058
4075
|
"start:release": startReleaseScript,
|
|
4076
|
+
"start:production": startProductionScript,
|
|
4059
4077
|
"dev:app": "tsx ./scripts/dev-runner.ts",
|
|
4060
4078
|
"dev:host": `${WEBPACK_CLI_COMMAND} serve --config ./${generatedPaths.devConfig} --mode development`,
|
|
4061
4079
|
"dev:release-host": releaseHostCommand,
|
|
4080
|
+
"build:release-host": `${WEBPACK_CLI_COMMAND} --config ./${releaseConfig} --mode production`,
|
|
4081
|
+
"preview:release-host": `${WEBPACK_CLI_COMMAND} serve --config ./${releaseConfig} --mode production`,
|
|
4062
4082
|
"dev:sandbox": `${WEBPACK_CLI_COMMAND} --config ./${generatedPaths.sandboxBuildConfig} --mode development --watch`,
|
|
4063
4083
|
"dev:sandbox:once": `${WEBPACK_CLI_COMMAND} --config ./${generatedPaths.sandboxBuildConfig} --mode development`,
|
|
4064
4084
|
build: "tsx ./scripts/build-runner.ts",
|
|
@@ -4398,6 +4418,7 @@ function getPostCreateRunCommands(startMode, options, packageManager = "npm") {
|
|
|
4398
4418
|
if (isAngularEsbuildStand(options)) return [[packageManager, ["run", "build"]], [packageManager, ["run", "serve:chunk-repro"]]];
|
|
4399
4419
|
return [[packageManager, ["run", "build:rebundle"]], [packageManager, ["run", "serve:chunk-repro"]]];
|
|
4400
4420
|
}
|
|
4421
|
+
if (startMode === "production" && options.kind !== "demo-stand") return [[packageManager, ["run", "start:production"]]];
|
|
4401
4422
|
if (options.kind === "demo-stand") {
|
|
4402
4423
|
if (isModuleFederationStand(options)) return [[packageManager, ["run", "start"]]];
|
|
4403
4424
|
const serveScript = getStandProductionServeScript(options);
|
|
@@ -4517,6 +4538,10 @@ async function promptForPostCreateActions(options, messages) {
|
|
|
4517
4538
|
title: isStand ? messages.promptStandStartModeRelease : messages.promptStartModeRelease,
|
|
4518
4539
|
value: "release"
|
|
4519
4540
|
},
|
|
4541
|
+
...isStand ? [] : [{
|
|
4542
|
+
title: messages.promptStartModeProduction,
|
|
4543
|
+
value: "production"
|
|
4544
|
+
}],
|
|
4520
4545
|
...isAngularReproStand ? [{
|
|
4521
4546
|
title: messages.promptStandStartModeRepro,
|
|
4522
4547
|
value: "repro"
|
|
@@ -4552,34 +4577,35 @@ function printNextSteps(result, options, actions, messages, credentialsReady = f
|
|
|
4552
4577
|
title: messages.nextStepFillCredentials,
|
|
4553
4578
|
command: getCredentialsMessage(options, messages)
|
|
4554
4579
|
});
|
|
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
|
-
|
|
4580
|
+
if (options.kind === "plugin") {
|
|
4581
|
+
if (!actions.installDependencies) steps.push({
|
|
4582
|
+
title: messages.nextStepInstall,
|
|
4583
|
+
command: installCommand
|
|
4584
|
+
}, {
|
|
4585
|
+
title: messages.nextStepStartDebug,
|
|
4586
|
+
command: startDebugCommand
|
|
4587
|
+
}, {
|
|
4588
|
+
title: messages.nextStepStartRelease,
|
|
4589
|
+
command: startReleaseCommand
|
|
4590
|
+
});
|
|
4591
|
+
else if (actions.startMode === "none") steps.push({
|
|
4592
|
+
title: messages.nextStepAlreadyInstalled,
|
|
4593
|
+
command: null
|
|
4594
|
+
}, {
|
|
4595
|
+
title: messages.nextStepStartDebug,
|
|
4596
|
+
command: startDebugCommand
|
|
4597
|
+
}, {
|
|
4598
|
+
title: messages.nextStepStartRelease,
|
|
4599
|
+
command: startReleaseCommand
|
|
4600
|
+
});
|
|
4601
|
+
else steps.push({
|
|
4602
|
+
title: messages.nextStepAlreadyInstalled,
|
|
4603
|
+
command: null
|
|
4604
|
+
}, {
|
|
4605
|
+
title: actions.startMode === "release" ? messages.nextStepServerStartingRelease : messages.nextStepServerStartingDebug,
|
|
4606
|
+
command: null
|
|
4607
|
+
});
|
|
4608
|
+
} else if (!actions.installDependencies) steps.push({
|
|
4583
4609
|
title: messages.nextStepInstall,
|
|
4584
4610
|
command: installCommand
|
|
4585
4611
|
}, {
|
package/package.json
CHANGED