@knapsack/renderer-react 4.70.0--canary.4433.133de0f.0 → 4.70.0--canary.4513.12c8d13.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
- // ../../../../node_modules/.pnpm/tsup@8.2.4_@microsoft+api-extractor@7.43.8_@types+node@20.16.5__@swc+core@1.3.57_@swc+helpers_wmt3ybl3mzdoq2p43nq3x3nq7u/node_modules/tsup/assets/esm_shims.js
10
+ // ../../../../node_modules/.pnpm/tsup@8.2.4_@microsoft+api-extractor@7.43.8_@types+node@20.16.6__@swc+core@1.3.57_@swc+helpers_iqa4vqpgdlzwuubzthdmdz7nfe/node_modules/tsup/assets/esm_shims.js
11
11
  import { fileURLToPath } from "url";
12
12
  import path from "path";
13
13
  var getFilename = /* @__PURE__ */ __name(() => fileURLToPath(import.meta.url), "getFilename");
@@ -16,17 +16,20 @@ var __dirname = /* @__PURE__ */ getDirname();
16
16
 
17
17
  // src/renderer-react.ts
18
18
  import sleep from "sleep-promise";
19
- import { KnapsackRendererWebpackBase } from "@knapsack/renderer-webpack-base";
19
+ import {
20
+ RendererWebpackBase
21
+ } from "@knapsack/renderer-webpack-base";
20
22
  import { pascalCase, isFirstLetterCapital } from "@knapsack/utils";
21
- import { knapsackEvents, log as log2, KnapsackRendererBase } from "@knapsack/app";
23
+ import { knapsackEvents, log as log2 } from "@knapsack/app";
24
+ import {
25
+ babelCodeForBrowser,
26
+ createSlotOptionsHtmlTags
27
+ } from "@knapsack/app/renderers";
22
28
  import {
23
- isSlottedText,
24
- isSlottedTemplateReference,
25
- isSlottedTemplateDemo,
26
29
  rendererIds
27
30
  } from "@knapsack/types";
28
31
  import {
29
- exists,
32
+ exists as fileExists,
30
33
  findUpPkgJson,
31
34
  getJsExportNames as getJsExportNames2,
32
35
  readFile as readFile2,
@@ -61,13 +64,14 @@ function renderUsageTemplate({
61
64
  `;
62
65
  }
63
66
  __name(renderUsageTemplate, "renderUsageTemplate");
67
+ var demoAppName = "DemoApp";
64
68
  function renderDemoAppTemplate({
65
- imports,
69
+ imports = "",
66
70
  children
67
71
  }) {
68
72
  return `${imports}
69
73
 
70
- function DemoApp() {
74
+ function ${demoAppName}() {
71
75
  return (
72
76
  ${children}
73
77
  )
@@ -126,12 +130,14 @@ async function getUsage(data) {
126
130
  __name(getUsage, "getUsage");
127
131
  async function getDemoAppUsage({
128
132
  children,
129
- imports
133
+ imports,
134
+ format
130
135
  }) {
131
136
  const code = renderDemoAppTemplate({
132
137
  children,
133
138
  imports
134
139
  });
140
+ if (!format) return code;
135
141
  return formatCode({
136
142
  contents: code,
137
143
  path: "x.tsx"
@@ -721,11 +727,13 @@ var createReactPattern = createCreator({
721
727
  }, "getTasks")
722
728
  });
723
729
 
730
+ // src/types.ts
731
+ var rendererMetaScriptTagId = "ks-react-meta";
732
+
724
733
  // src/renderer-react.ts
725
734
  var { pkg } = findUpPkgJson(__dirname);
726
735
  log2.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
727
- var { createSlotOptionsHtmlTags } = KnapsackRendererBase;
728
- var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendererWebpackBase {
736
+ var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpackBase {
729
737
  static {
730
738
  __name(this, "KnapsackReactRenderer");
731
739
  }
@@ -734,7 +742,6 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
734
742
  */
735
743
  assets;
736
744
  babelConfig;
737
- creators;
738
745
  demoWrapperPath;
739
746
  disableReactStrictMode;
740
747
  constructor({
@@ -747,7 +754,11 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
747
754
  id,
748
755
  extension: ".jsx",
749
756
  language: "jsx",
750
- webpackConfig
757
+ webpackConfig,
758
+ extraScripts: [
759
+ // this is the code in `./client/init.mts`
760
+ "@knapsack/renderer-react/client"
761
+ ]
751
762
  });
752
763
  this.language = "jsx";
753
764
  this.assets = [];
@@ -755,15 +766,15 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
755
766
  this.disableReactStrictMode = disableReactStrictMode;
756
767
  this.creators = [createReactPattern];
757
768
  }
758
- async init(opt) {
769
+ init = /* @__PURE__ */ __name(async (opt) => {
759
770
  await super.init(opt);
760
771
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
761
- if (!await exists(this.demoWrapperPath)) {
772
+ if (!await fileExists(this.demoWrapperPath)) {
762
773
  throw new Error(
763
774
  `Could not find demo wrapper at: "${this.demoWrapperPath}"`
764
775
  );
765
776
  }
766
- }
777
+ }, "init");
767
778
  getMeta = /* @__PURE__ */ __name(() => ({
768
779
  id: this.id,
769
780
  title: "React",
@@ -793,18 +804,16 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
793
804
  }
794
805
  }
795
806
  }), "getMeta");
796
- changeCase(str) {
797
- return pascalCase(str);
798
- }
799
- createWebpackConfig() {
807
+ changeCase = /* @__PURE__ */ __name((str) => pascalCase(str), "changeCase");
808
+ createWebpackConfig = /* @__PURE__ */ __name(() => {
800
809
  const config = super.createWebpackConfig();
801
810
  config.externals = {
802
811
  react: "React",
803
812
  "react-dom": "ReactDOM"
804
813
  };
805
814
  return config;
806
- }
807
- getJsImports() {
815
+ }, "createWebpackConfig");
816
+ getJsImports = /* @__PURE__ */ __name(() => {
808
817
  const imports = super.getJsImports();
809
818
  imports.push(
810
819
  {
@@ -825,174 +834,85 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
825
834
  }
826
835
  );
827
836
  return imports;
828
- }
837
+ }, "getJsImports");
829
838
  async prepClientRenderResults({
830
839
  usage,
831
840
  demoApp,
832
841
  imports: xImports,
833
842
  renderOptions: { pattern, template, demo }
834
843
  }) {
835
- const extraImportNames = this.getJsImports().flatMap(
836
- (imp) => imp.type === "extra" ? [imp.importInfo.name] : []
844
+ const extraImports = this.getJsImports().filter(
845
+ (imp) => imp.type === "extra"
837
846
  );
838
- const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: xImports });
847
+ const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
839
848
  if (!isDeclaredVarsUnique) {
840
849
  log2.error(`${nameCollisions.join(", ")} are declared multiple times`, {
841
850
  imports
842
851
  });
843
852
  }
844
- const importNames = [
845
- ...imports.map(({ importInfo: { name } }) => name),
846
- ...extraImportNames
847
- ];
848
- const patternsUsed = imports.flatMap((imp) => {
849
- if (imp.type === "pattern-template") {
850
- return [
851
- {
852
- patternId: imp.patternId,
853
- templateId: imp.templateId
853
+ const meta = {
854
+ demo,
855
+ disableReactStrictMode: this.disableReactStrictMode,
856
+ neededImports: imports,
857
+ demoWrapperProps: {
858
+ pattern,
859
+ template,
860
+ demo,
861
+ patternsUsed: imports.flatMap((imp) => {
862
+ if (imp.type === "pattern-template") {
863
+ return [
864
+ {
865
+ patternId: imp.patternId,
866
+ templateId: imp.templateId
867
+ }
868
+ ];
854
869
  }
855
- ];
856
- }
857
- if (imp.type === "pattern-template-demo") {
858
- return [
859
- {
860
- patternId: imp.patternId,
861
- templateId: imp.templateId,
862
- demoId: imp.demoId
870
+ if (imp.type === "pattern-template-demo") {
871
+ return [
872
+ {
873
+ patternId: imp.patternId,
874
+ templateId: imp.templateId,
875
+ demoId: imp.demoId
876
+ }
877
+ ];
863
878
  }
864
- ];
879
+ return [];
880
+ })
865
881
  }
866
- return [];
867
- });
868
- const demoWrapperProps = {
869
- patternsUsed,
870
- pattern,
871
- template,
872
- demo
873
882
  };
874
- const demoWrapperCode = await getUsage({
875
- templateName: "DemoWrapper",
876
- props: demoWrapperProps,
877
- children: `<DemoApp />`
878
- // extraProps,
879
- });
880
- async function renderReact({
881
- patterns,
882
- theExtraImportNames,
883
- ksGlobal
884
- }) {
885
- if (!ksGlobal) {
886
- throw new Error('"window.knapsack" is null');
887
- }
888
- const components = await ksGlobal.getAllImports({
889
- patterns,
890
- extras: theExtraImportNames.map((name) => ({ name }))
891
- });
892
- return components;
893
- }
894
- __name(renderReact, "renderReact");
895
883
  let code = `
896
-
897
- ${renderReact.toString()}
898
- ${renderReact.name}({
899
- ksGlobal: window.knapsack,
900
- patterns: ${JSON.stringify(patternsUsed)},
901
- theExtraImportNames: ${JSON.stringify(extraImportNames)},
902
- }).then((components) => {
903
- const { ${importNames.join(", ")} } = components;
904
- const root = document.getElementById('render-root');
905
-
906
- ${demoApp}
907
-
908
- const reactDomVersion = parseInt(ReactDOM.version.split('.')[0], 10);
909
-
910
- const ReactRendererResult = () => {
911
- if (reactDomVersion < 17 || ${this.disableReactStrictMode}){
912
- return (
913
- <ErrorCatcher>
914
- ${demoWrapperCode}
915
- </ErrorCatcher>
916
- )
884
+ window.knapsack = window.knapsack || {};
885
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
886
+ ${demoApp}
887
+ return ${demoAppName}
917
888
  }
918
-
919
- return (
920
- <React.StrictMode>
921
- <ErrorCatcher>
922
- ${demoWrapperCode}
923
- </ErrorCatcher>
924
- </React.StrictMode>
925
- )
926
- };
927
-
928
-
929
- if (reactDomVersion > 17){
930
- ReactDOM.createRoot(root).render(
931
- <ReactRendererResult />
932
- )
933
- } else {
934
- ReactDOM.render(
935
- <ReactRendererResult />,
936
- root
937
- );
938
- }
939
- }).catch((err) => {
940
- console.error(err);
941
- const root = document.getElementById('render-root');
942
- // Create a new <div> element to contain the error message
943
- const errorMsgDiv = document.createElement('div');
944
- // Insert the new <div> element before the existing element
945
- root.parentNode.insertBefore(errorMsgDiv, root);
946
- // add error message so users can see it
947
- errorMsgDiv.innerHTML = '<h1>Component Error</h1><p>' + err.message + '</p>';
948
- });
949
889
  `;
950
- let codeHadError = false;
951
890
  let errorHtmlMsg = "";
952
891
  try {
953
- code = await this.babelCodeForBrowser({
954
- code
955
- });
892
+ code = await babelCodeForBrowser({ code });
956
893
  } catch (e) {
957
- codeHadError = true;
958
894
  console.log(code);
959
895
  console.log("---original code before babel error ^---");
960
896
  console.trace(e.message);
961
897
  code = `console.error(${JSON.stringify(e.message)});`;
962
898
  errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
963
899
  }
964
- if (!codeHadError) {
965
- try {
966
- code = await formatCode2({
967
- contents: code,
968
- path: "x.tsx"
969
- // doing this to set format language
970
- });
971
- } catch (e) {
972
- codeHadError = true;
973
- console.log(code);
974
- console.log("---original code before prettier error ^---");
975
- console.trace(e.message);
976
- code = `console.error(${JSON.stringify(e.message)});`;
977
- errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
978
- }
979
- }
980
900
  const html = `
901
+ <script type="application/json" id="${rendererMetaScriptTagId}">${JSON.stringify(
902
+ meta
903
+ )}</script>
904
+ <script type="application/javascript">${code}</script>
905
+ <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
981
906
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
982
-
983
907
  ${this.createHtmlTagsForAssetPaths({
984
908
  assets: this.getWebpackAssetPaths(),
985
909
  // we need the scripts to finish adding methods to the global knapsack object synchronously before the client-side code runs that is in the <script> tag below
986
910
  scriptTagsAreAsync: false
987
911
  })}
988
-
989
- <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
990
- <script type="application/javascript">${code}</script>
991
- ${errorHtmlMsg}
992
-
912
+ ${errorHtmlMsg}
993
913
  `;
994
914
  return {
995
- ok: !codeHadError,
915
+ ok: !errorHtmlMsg,
996
916
  html: await formatCode2({
997
917
  contents: html,
998
918
  path: "x.html"
@@ -1002,18 +922,22 @@ ${errorHtmlMsg}
1002
922
  templateLanguage: this.language
1003
923
  };
1004
924
  }
1005
- async render(opt) {
1006
- if (_KnapsackReactRenderer.isTemplateDemo(opt.demo)) {
925
+ render = /* @__PURE__ */ __name(async (opt) => {
926
+ if (opt.demo?.type === "template") {
1007
927
  const waits = [5, 10, 20, 50, 100, 1e3, 1e3];
1008
928
  let templateDemoPath;
1009
929
  let attempt = 0;
1010
930
  while (true) {
1011
931
  try {
1012
- templateDemoPath = opt.patternManifest.getTemplateDemoAbsolutePath({
1013
- patternId: opt.pattern.id,
1014
- templateId: opt.template.id,
1015
- demoId: opt.demo.id
1016
- });
932
+ const { absolutePath, exists } = await this.resolvePath(
933
+ opt.demo.templateInfo.path
934
+ );
935
+ if (!exists) {
936
+ throw new Error(
937
+ `Template demo file does not exist: ${absolutePath}`
938
+ );
939
+ }
940
+ templateDemoPath = absolutePath;
1017
941
  break;
1018
942
  } catch (e) {
1019
943
  const waitTime = waits[attempt];
@@ -1039,7 +963,7 @@ ${errorHtmlMsg}
1039
963
  });
1040
964
  return results;
1041
965
  }
1042
- if (_KnapsackReactRenderer.isDataDemo(opt.demo)) {
966
+ if (opt.demo?.type === "data") {
1043
967
  const { usage, imports } = await this.getUsageAndImports(opt);
1044
968
  const { code: importCode } = this.createJsImportCodeBlock({
1045
969
  imports
@@ -1047,7 +971,8 @@ ${errorHtmlMsg}
1047
971
  const [demoAppUsage, demoApp] = await Promise.all([
1048
972
  getDemoAppUsage({
1049
973
  children: usage,
1050
- imports: importCode
974
+ imports: importCode,
975
+ format: true
1051
976
  }),
1052
977
  getDemoAppUsage({
1053
978
  children: usage
@@ -1060,10 +985,14 @@ ${errorHtmlMsg}
1060
985
  renderOptions: opt
1061
986
  });
1062
987
  }
1063
- }
1064
- async getUsageAndImports(opt) {
1065
- const { pattern, template, patternManifest, demo } = opt;
1066
- if (demo?.type && _KnapsackReactRenderer.isDataDemo(demo)) {
988
+ }, "render");
989
+ getUsageAndImports = /* @__PURE__ */ __name(async ({
990
+ pattern,
991
+ template,
992
+ patternManifest,
993
+ demo
994
+ }) => {
995
+ if (demo?.type && demo.type === "data") {
1067
996
  const {
1068
997
  data: { props, slots, slotsOptionsComputed }
1069
998
  } = demo;
@@ -1087,16 +1016,16 @@ ${errorHtmlMsg}
1087
1016
  const slotItems = slots[slotName];
1088
1017
  const slotItemsUsages = await Promise.all(
1089
1018
  slotItems.filter((slotItem) => {
1090
- if (!isSlottedText(slotItem)) {
1019
+ if (slotItem.type !== "text") {
1091
1020
  if (!slotItem.patternId) return false;
1092
1021
  if (!slotItem.templateId) return false;
1093
- if (isSlottedTemplateDemo(slotItem) && !slotItem.demoId) {
1022
+ if (slotItem.type === "template-demo" && !slotItem.demoId) {
1094
1023
  return false;
1095
1024
  }
1096
1025
  }
1097
1026
  return true;
1098
1027
  }).map(async (slotItem) => {
1099
- if (isSlottedText(slotItem)) {
1028
+ if (slotItem.type === "text") {
1100
1029
  if (slotItems.length === 1 && slotName !== "children") {
1101
1030
  return `\`${slotItem.text}\``;
1102
1031
  }
@@ -1108,7 +1037,7 @@ ${errorHtmlMsg}
1108
1037
  const slotTemplate = slotPattern.templates.find(
1109
1038
  (t) => t.id === slotItem.templateId
1110
1039
  );
1111
- if (isSlottedTemplateReference(slotItem)) {
1040
+ if (slotItem.type === "template-reference") {
1112
1041
  const { usage: usage2, imports } = await this.getUsageAndImports({
1113
1042
  pattern: slotPattern,
1114
1043
  template: slotTemplate,
@@ -1117,7 +1046,7 @@ ${errorHtmlMsg}
1117
1046
  importInfos.push(...imports);
1118
1047
  return usage2;
1119
1048
  }
1120
- if (isSlottedTemplateDemo(slotItem)) {
1049
+ if (slotItem.type === "template-demo") {
1121
1050
  const { usage: usage2, imports } = await this.getUsageAndImports({
1122
1051
  pattern: slotPattern,
1123
1052
  template: slotTemplate,
@@ -1188,7 +1117,7 @@ ${errorHtmlMsg}
1188
1117
  imports: importInfos
1189
1118
  };
1190
1119
  }
1191
- if (demo?.type && _KnapsackReactRenderer.isTemplateDemo(demo)) {
1120
+ if (demo?.type && demo.type === "template") {
1192
1121
  const importInfo = this.getJsImport({
1193
1122
  patternId: pattern.id,
1194
1123
  templateId: template.id,
@@ -1232,11 +1161,7 @@ ${errorHtmlMsg}
1232
1161
  demo
1233
1162
  )}`
1234
1163
  );
1235
- }
1236
- async getUsage(opt) {
1237
- const { usage } = await this.getUsageAndImports(opt);
1238
- return usage;
1239
- }
1164
+ }, "getUsageAndImports");
1240
1165
  inferSpec = /* @__PURE__ */ __name(async ({
1241
1166
  template,
1242
1167
  templatePath
@@ -1255,12 +1180,12 @@ ${errorHtmlMsg}
1255
1180
  }
1256
1181
  return spec;
1257
1182
  }, "inferSpec");
1258
- async watch(opt) {
1259
- await super.watch(opt);
1183
+ watch = /* @__PURE__ */ __name(async (opt) => {
1184
+ super.watch(opt);
1260
1185
  knapsackEvents.onPatternTemplateChanged(() => {
1261
1186
  clearInferSpecCache();
1262
1187
  });
1263
- }
1188
+ }, "watch");
1264
1189
  getTemplateMeta = /* @__PURE__ */ __name(async ({
1265
1190
  pattern,
1266
1191
  template
@@ -1303,7 +1228,10 @@ ${errorHtmlMsg}
1303
1228
  }
1304
1229
  return files;
1305
1230
  }, "getTemplateMeta");
1306
- alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({ files, metaDir }) => {
1231
+ alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({
1232
+ files,
1233
+ metaDir
1234
+ }) => {
1307
1235
  const imports = [];
1308
1236
  const ext = ".spec.d.ts";
1309
1237
  files.forEach((file) => {
@@ -1330,9 +1258,9 @@ ${errorHtmlMsg}
1330
1258
  }
1331
1259
  ];
1332
1260
  }, "alterTemplateMetaFiles");
1333
- async getTemplateSuggestions({
1261
+ getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1334
1262
  newPath
1335
- }) {
1263
+ }) => {
1336
1264
  const { data: dataDir } = this.patterns.userConfig;
1337
1265
  const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1338
1266
  const usedSuggestions = [
@@ -1383,7 +1311,7 @@ ${errorHtmlMsg}
1383
1311
  return {
1384
1312
  suggestions
1385
1313
  };
1386
- }
1314
+ }, "getTemplateSuggestions");
1387
1315
  };
1388
1316
  export {
1389
1317
  KnapsackReactRenderer