@stripe/extensibility-dev-tools 0.23.5

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.
Files changed (253) hide show
  1. package/LICENSE.md +19 -0
  2. package/dist/bin/build-custom-object-definitions.cjs +2111 -0
  3. package/dist/bin/build-custom-object-definitions.d.ts +11 -0
  4. package/dist/bin/build-custom-object-definitions.d.ts.map +1 -0
  5. package/dist/bin/build-custom-object-definitions.js +2088 -0
  6. package/dist/bin/create-upload-image.cjs +2136 -0
  7. package/dist/bin/create-upload-image.d.ts +17 -0
  8. package/dist/bin/create-upload-image.d.ts.map +1 -0
  9. package/dist/bin/create-upload-image.js +2113 -0
  10. package/dist/bin/dev-tools-rpc.cjs +3874 -0
  11. package/dist/bin/dev-tools-rpc.d.ts +3 -0
  12. package/dist/bin/dev-tools-rpc.d.ts.map +1 -0
  13. package/dist/bin/dev-tools-rpc.js +3864 -0
  14. package/dist/bin/gen-schemas.cjs +20739 -0
  15. package/dist/bin/gen-schemas.d.ts +8 -0
  16. package/dist/bin/gen-schemas.d.ts.map +1 -0
  17. package/dist/bin/gen-schemas.js +20715 -0
  18. package/dist/bin/gen-workspace.cjs +3847 -0
  19. package/dist/bin/gen-workspace.d.ts +8 -0
  20. package/dist/bin/gen-workspace.d.ts.map +1 -0
  21. package/dist/bin/gen-workspace.js +3841 -0
  22. package/dist/bin/manifest.cjs +686 -0
  23. package/dist/bin/manifest.d.ts +10 -0
  24. package/dist/bin/manifest.d.ts.map +1 -0
  25. package/dist/bin/manifest.js +663 -0
  26. package/dist/bin/rpc/dispatch.d.ts +10 -0
  27. package/dist/bin/rpc/dispatch.d.ts.map +1 -0
  28. package/dist/bin/rpc/handlers.d.ts +4 -0
  29. package/dist/bin/rpc/handlers.d.ts.map +1 -0
  30. package/dist/bin/rpc/types.d.ts +29 -0
  31. package/dist/bin/rpc/types.d.ts.map +1 -0
  32. package/dist/bin/template-info.cjs +1511 -0
  33. package/dist/bin/template-info.d.ts +9 -0
  34. package/dist/bin/template-info.d.ts.map +1 -0
  35. package/dist/bin/template-info.js +1488 -0
  36. package/dist/custom-objects/build-definitions.d.ts +98 -0
  37. package/dist/custom-objects/build-definitions.d.ts.map +1 -0
  38. package/dist/custom-objects/generated/proto/custom_objects/pub/api/app_api/object_definitions_app_service.pb.d.ts +191 -0
  39. package/dist/custom-objects/generated/proto/custom_objects/pub/api/app_api/object_definitions_app_service.pb.d.ts.map +1 -0
  40. package/dist/custom-objects/generated/proto/custom_objects/pub/api/common/schema.pb.d.ts +131 -0
  41. package/dist/custom-objects/generated/proto/custom_objects/pub/api/common/schema.pb.d.ts.map +1 -0
  42. package/dist/custom-objects/generated/proto/google/protobuf/descriptor.pb.d.ts +1482 -0
  43. package/dist/custom-objects/generated/proto/google/protobuf/descriptor.pb.d.ts.map +1 -0
  44. package/dist/custom-objects/generated/proto/google/protobuf/timestamp.pb.d.ts +167 -0
  45. package/dist/custom-objects/generated/proto/google/protobuf/timestamp.pb.d.ts.map +1 -0
  46. package/dist/custom-objects/generated/proto/proto/annotations.pb.d.ts +64 -0
  47. package/dist/custom-objects/generated/proto/proto/annotations.pb.d.ts.map +1 -0
  48. package/dist/custom-objects/generated/proto/proto/extensions.pb.d.ts +657 -0
  49. package/dist/custom-objects/generated/proto/proto/extensions.pb.d.ts.map +1 -0
  50. package/dist/custom-objects/generated/proto/vendor/metadata/pub/api/api_metadata.pb.d.ts +105 -0
  51. package/dist/custom-objects/generated/proto/vendor/metadata/pub/api/api_metadata.pb.d.ts.map +1 -0
  52. package/dist/custom-objects/generated/proto/vendor/net/idempotency/idempotency_model.pb.d.ts +79 -0
  53. package/dist/custom-objects/generated/proto/vendor/net/idempotency/idempotency_model.pb.d.ts.map +1 -0
  54. package/dist/custom-objects/generated/proto/vendor/publicapi/api_group_enum.pb.d.ts +129 -0
  55. package/dist/custom-objects/generated/proto/vendor/publicapi/api_group_enum.pb.d.ts.map +1 -0
  56. package/dist/custom-objects/generated/proto/vendor/publicapi/api_visibility.pb.d.ts +76 -0
  57. package/dist/custom-objects/generated/proto/vendor/publicapi/api_visibility.pb.d.ts.map +1 -0
  58. package/dist/custom-objects/generated/proto/vendor/publicapi/customize_dispatch_middleware_enum.pb.d.ts +78 -0
  59. package/dist/custom-objects/generated/proto/vendor/publicapi/customize_dispatch_middleware_enum.pb.d.ts.map +1 -0
  60. package/dist/custom-objects/generated/proto/vendor/publicapi/docs_namespace_group_enum.pb.d.ts +146 -0
  61. package/dist/custom-objects/generated/proto/vendor/publicapi/docs_namespace_group_enum.pb.d.ts.map +1 -0
  62. package/dist/custom-objects/generated/proto/vendor/publicapi/documented_enum.pb.d.ts +76 -0
  63. package/dist/custom-objects/generated/proto/vendor/publicapi/documented_enum.pb.d.ts.map +1 -0
  64. package/dist/custom-objects/generated/proto/vendor/publicapi/event_scope_enum.pb.d.ts +92 -0
  65. package/dist/custom-objects/generated/proto/vendor/publicapi/event_scope_enum.pb.d.ts.map +1 -0
  66. package/dist/custom-objects/generated/proto/vendor/publicapi/extension_interface.pb.d.ts +124 -0
  67. package/dist/custom-objects/generated/proto/vendor/publicapi/extension_interface.pb.d.ts.map +1 -0
  68. package/dist/custom-objects/generated/proto/vendor/publicapi/feature_enum.pb.d.ts +1070 -0
  69. package/dist/custom-objects/generated/proto/vendor/publicapi/feature_enum.pb.d.ts.map +1 -0
  70. package/dist/custom-objects/generated/proto/vendor/publicapi/field_validation_rules.pb.d.ts +279 -0
  71. package/dist/custom-objects/generated/proto/vendor/publicapi/field_validation_rules.pb.d.ts.map +1 -0
  72. package/dist/custom-objects/generated/proto/vendor/publicapi/flavor_enum.pb.d.ts +78 -0
  73. package/dist/custom-objects/generated/proto/vendor/publicapi/flavor_enum.pb.d.ts.map +1 -0
  74. package/dist/custom-objects/generated/proto/vendor/publicapi/http_error_status.pb.d.ts +102 -0
  75. package/dist/custom-objects/generated/proto/vendor/publicapi/http_error_status.pb.d.ts.map +1 -0
  76. package/dist/custom-objects/generated/proto/vendor/publicapi/method_kind_enum.pb.d.ts +86 -0
  77. package/dist/custom-objects/generated/proto/vendor/publicapi/method_kind_enum.pb.d.ts.map +1 -0
  78. package/dist/custom-objects/generated/proto/vendor/publicapi/method_priority.pb.d.ts +80 -0
  79. package/dist/custom-objects/generated/proto/vendor/publicapi/method_priority.pb.d.ts.map +1 -0
  80. package/dist/custom-objects/generated/proto/vendor/publicapi/permission_check_enum.pb.d.ts +74 -0
  81. package/dist/custom-objects/generated/proto/vendor/publicapi/permission_check_enum.pb.d.ts.map +1 -0
  82. package/dist/custom-objects/generated/proto/vendor/publicapi/redaction_enum.pb.d.ts +76 -0
  83. package/dist/custom-objects/generated/proto/vendor/publicapi/redaction_enum.pb.d.ts.map +1 -0
  84. package/dist/custom-objects/generated/proto/vendor/publicapi/region_routers.pb.d.ts +103 -0
  85. package/dist/custom-objects/generated/proto/vendor/publicapi/region_routers.pb.d.ts.map +1 -0
  86. package/dist/custom-objects/generated/proto/vendor/publicapi/rollout_configs.pb.d.ts +153 -0
  87. package/dist/custom-objects/generated/proto/vendor/publicapi/rollout_configs.pb.d.ts.map +1 -0
  88. package/dist/custom-objects/generated/proto/vendor/publicapi/v2ext.pb.d.ts +1111 -0
  89. package/dist/custom-objects/generated/proto/vendor/publicapi/v2ext.pb.d.ts.map +1 -0
  90. package/dist/custom-objects/generated/proto/vendor/vext/annotations.pb.d.ts +602 -0
  91. package/dist/custom-objects/generated/proto/vendor/vext/annotations.pb.d.ts.map +1 -0
  92. package/dist/custom-objects/generated/proto/vendor/vext/extensions.pb.d.ts +144 -0
  93. package/dist/custom-objects/generated/proto/vendor/vext/extensions.pb.d.ts.map +1 -0
  94. package/dist/custom-objects/generated/proto/vendor/vext/privacy_unified_annotations.pb.d.ts +851 -0
  95. package/dist/custom-objects/generated/proto/vendor/vext/privacy_unified_annotations.pb.d.ts.map +1 -0
  96. package/dist/custom-objects/generated/proto/vendor/vext/xml_annotations.pb.d.ts +125 -0
  97. package/dist/custom-objects/generated/proto/vendor/vext/xml_annotations.pb.d.ts.map +1 -0
  98. package/dist/custom-objects/to-proto-json.d.ts +17 -0
  99. package/dist/custom-objects/to-proto-json.d.ts.map +1 -0
  100. package/dist/dependencies/index.cjs +601 -0
  101. package/dist/dependencies/index.d.ts +320 -0
  102. package/dist/dependencies/index.d.ts.map +1 -0
  103. package/dist/dependencies/index.js +560 -0
  104. package/dist/extensibility-dev-tools-alpha.d.ts +199 -0
  105. package/dist/extensibility-dev-tools-beta.d.ts +199 -0
  106. package/dist/extensibility-dev-tools-dependencies-alpha.d.ts +51 -0
  107. package/dist/extensibility-dev-tools-dependencies-beta.d.ts +51 -0
  108. package/dist/extensibility-dev-tools-dependencies-internal.d.ts +372 -0
  109. package/dist/extensibility-dev-tools-dependencies-public.d.ts +51 -0
  110. package/dist/extensibility-dev-tools-internal.d.ts +1722 -0
  111. package/dist/extensibility-dev-tools-jsonschema-tools-alpha.d.ts +57 -0
  112. package/dist/extensibility-dev-tools-jsonschema-tools-beta.d.ts +57 -0
  113. package/dist/extensibility-dev-tools-jsonschema-tools-internal.d.ts +123 -0
  114. package/dist/extensibility-dev-tools-jsonschema-tools-public.d.ts +57 -0
  115. package/dist/extensibility-dev-tools-manifest-alpha.d.ts +31 -0
  116. package/dist/extensibility-dev-tools-manifest-beta.d.ts +31 -0
  117. package/dist/extensibility-dev-tools-manifest-internal.d.ts +461 -0
  118. package/dist/extensibility-dev-tools-manifest-public.d.ts +31 -0
  119. package/dist/extensibility-dev-tools-public.d.ts +199 -0
  120. package/dist/extensibility-dev-tools-schemas-alpha.d.ts +9 -0
  121. package/dist/extensibility-dev-tools-schemas-beta.d.ts +9 -0
  122. package/dist/extensibility-dev-tools-schemas-internal.d.ts +41 -0
  123. package/dist/extensibility-dev-tools-schemas-public.d.ts +9 -0
  124. package/dist/extensibility-dev-tools-templates-alpha.d.ts +67 -0
  125. package/dist/extensibility-dev-tools-templates-beta.d.ts +67 -0
  126. package/dist/extensibility-dev-tools-templates-internal.d.ts +554 -0
  127. package/dist/extensibility-dev-tools-templates-public.d.ts +67 -0
  128. package/dist/extensibility-dev-tools-workspace-alpha.d.ts +51 -0
  129. package/dist/extensibility-dev-tools-workspace-beta.d.ts +51 -0
  130. package/dist/extensibility-dev-tools-workspace-internal.d.ts +410 -0
  131. package/dist/extensibility-dev-tools-workspace-public.d.ts +51 -0
  132. package/dist/index.cjs +3810 -0
  133. package/dist/index.d.ts +18 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +3758 -0
  136. package/dist/jsonschema-tools.cjs +20451 -0
  137. package/dist/jsonschema-tools.d.ts +98 -0
  138. package/dist/jsonschema-tools.d.ts.map +1 -0
  139. package/dist/jsonschema-tools.js +20404 -0
  140. package/dist/manifest/index.cjs +610 -0
  141. package/dist/manifest/index.d.ts +8 -0
  142. package/dist/manifest/index.d.ts.map +1 -0
  143. package/dist/manifest/index.js +571 -0
  144. package/dist/manifest/manifest-v1.d.ts +102 -0
  145. package/dist/manifest/manifest-v1.d.ts.map +1 -0
  146. package/dist/manifest/manifest-v2.d.ts +253 -0
  147. package/dist/manifest/manifest-v2.d.ts.map +1 -0
  148. package/dist/manifest/stripe-app-manifest.d.ts +114 -0
  149. package/dist/manifest/stripe-app-manifest.d.ts.map +1 -0
  150. package/dist/schemas/index.cjs +20692 -0
  151. package/dist/schemas/index.d.ts +37 -0
  152. package/dist/schemas/index.d.ts.map +1 -0
  153. package/dist/schemas/index.js +20656 -0
  154. package/dist/templates/diff-viewer/diff-generator.d.ts +22 -0
  155. package/dist/templates/diff-viewer/diff-generator.d.ts.map +1 -0
  156. package/dist/templates/diff-viewer/diff-prompt.d.ts +13 -0
  157. package/dist/templates/diff-viewer/diff-prompt.d.ts.map +1 -0
  158. package/dist/templates/diff-viewer/index.d.ts +7 -0
  159. package/dist/templates/diff-viewer/index.d.ts.map +1 -0
  160. package/dist/templates/diff-viewer/terminal-renderer.d.ts +29 -0
  161. package/dist/templates/diff-viewer/terminal-renderer.d.ts.map +1 -0
  162. package/dist/templates/diff-viewer/types.d.ts +58 -0
  163. package/dist/templates/diff-viewer/types.d.ts.map +1 -0
  164. package/dist/templates/extensions/base.d.ts +23 -0
  165. package/dist/templates/extensions/base.d.ts.map +1 -0
  166. package/dist/templates/extensions/billing.bill.discount_calculation.d.ts +6 -0
  167. package/dist/templates/extensions/billing.bill.discount_calculation.d.ts.map +1 -0
  168. package/dist/templates/extensions/billing.customer_balance_application.d.ts +6 -0
  169. package/dist/templates/extensions/billing.customer_balance_application.d.ts.map +1 -0
  170. package/dist/templates/extensions/billing.invoice_collection_setting.d.ts +6 -0
  171. package/dist/templates/extensions/billing.invoice_collection_setting.d.ts.map +1 -0
  172. package/dist/templates/extensions/billing.prorations.d.ts +6 -0
  173. package/dist/templates/extensions/billing.prorations.d.ts.map +1 -0
  174. package/dist/templates/extensions/billing.recurring_billing_item_handling.d.ts +6 -0
  175. package/dist/templates/extensions/billing.recurring_billing_item_handling.d.ts.map +1 -0
  176. package/dist/templates/extensions/core.workflows.custom_action.d.ts +6 -0
  177. package/dist/templates/extensions/core.workflows.custom_action.d.ts.map +1 -0
  178. package/dist/templates/extensions/extend.objects.custom_objects.d.ts +6 -0
  179. package/dist/templates/extensions/extend.objects.custom_objects.d.ts.map +1 -0
  180. package/dist/templates/extensions/extend.workflows.custom_action.d.ts +6 -0
  181. package/dist/templates/extensions/extend.workflows.custom_action.d.ts.map +1 -0
  182. package/dist/templates/extensions/index.d.ts +13 -0
  183. package/dist/templates/extensions/index.d.ts.map +1 -0
  184. package/dist/templates/extensions/registry.d.ts +10 -0
  185. package/dist/templates/extensions/registry.d.ts.map +1 -0
  186. package/dist/templates/extensions/types.d.ts +104 -0
  187. package/dist/templates/extensions/types.d.ts.map +1 -0
  188. package/dist/templates/file-writer.d.ts +140 -0
  189. package/dist/templates/file-writer.d.ts.map +1 -0
  190. package/dist/templates/fs/_impl.d.ts +29 -0
  191. package/dist/templates/fs/_impl.d.ts.map +1 -0
  192. package/dist/templates/fs/filesystem.d.ts +8 -0
  193. package/dist/templates/fs/filesystem.d.ts.map +1 -0
  194. package/dist/templates/fs/in-memory.d.ts +9 -0
  195. package/dist/templates/fs/in-memory.d.ts.map +1 -0
  196. package/dist/templates/fs/index.d.ts +25 -0
  197. package/dist/templates/fs/index.d.ts.map +1 -0
  198. package/dist/templates/fs-utils.d.ts +17 -0
  199. package/dist/templates/fs-utils.d.ts.map +1 -0
  200. package/dist/templates/index.cjs +2248 -0
  201. package/dist/templates/index.d.ts +32 -0
  202. package/dist/templates/index.d.ts.map +1 -0
  203. package/dist/templates/index.js +2203 -0
  204. package/dist/templates/root/index.d.ts +60 -0
  205. package/dist/templates/root/index.d.ts.map +1 -0
  206. package/dist/templates/simple-templates.d.ts +8 -0
  207. package/dist/templates/simple-templates.d.ts.map +1 -0
  208. package/dist/templates/template-manager.d.ts +8 -0
  209. package/dist/templates/template-manager.d.ts.map +1 -0
  210. package/dist/templates/types.d.ts +9 -0
  211. package/dist/templates/types.d.ts.map +1 -0
  212. package/dist/tsconfig.build.tsbuildinfo +1 -0
  213. package/dist/workspace/index.cjs +3756 -0
  214. package/dist/workspace/index.d.ts +336 -0
  215. package/dist/workspace/index.d.ts.map +1 -0
  216. package/dist/workspace/index.js +3731 -0
  217. package/package.json +137 -0
  218. package/templates/extensions/billing.bill.discount_calculation/index.test.ts +15 -0
  219. package/templates/extensions/billing.bill.discount_calculation/index.ts +20 -0
  220. package/templates/extensions/billing.customer_balance_application/index.test.ts +15 -0
  221. package/templates/extensions/billing.customer_balance_application/index.ts +18 -0
  222. package/templates/extensions/billing.invoice_collection_setting/index.test.ts +15 -0
  223. package/templates/extensions/billing.invoice_collection_setting/index.ts +16 -0
  224. package/templates/extensions/billing.prorations/index.test.ts +15 -0
  225. package/templates/extensions/billing.prorations/index.ts +18 -0
  226. package/templates/extensions/billing.recurring_billing_item_handling/index.test.ts +15 -0
  227. package/templates/extensions/billing.recurring_billing_item_handling/index.ts +42 -0
  228. package/templates/extensions/common/.prettierignore +3 -0
  229. package/templates/extensions/common/eslint.config.mts.mustache +95 -0
  230. package/templates/extensions/common/package.json.mustache +26 -0
  231. package/templates/extensions/common/tsconfig.build.json.mustache +15 -0
  232. package/templates/extensions/common/tsconfig.json.mustache +16 -0
  233. package/templates/extensions/core.workflows.custom_action/custom_input.schema.json +6 -0
  234. package/templates/extensions/core.workflows.custom_action/index.test.ts +15 -0
  235. package/templates/extensions/core.workflows.custom_action/index.ts +31 -0
  236. package/templates/extensions/extend.workflows.custom_action/custom_input.schema.json +6 -0
  237. package/templates/extensions/extend.workflows.custom_action/index.test.ts +15 -0
  238. package/templates/extensions/extend.workflows.custom_action/index.ts +31 -0
  239. package/templates/root/.husky/pre-commit +1 -0
  240. package/templates/root/.prettierignore +5 -0
  241. package/templates/root/.prettierrc +7 -0
  242. package/templates/root/_gitignore +28 -0
  243. package/templates/root/custom-objects/package.json +20 -0
  244. package/templates/root/custom-objects/tsconfig.json +9 -0
  245. package/templates/root/eslint.config.mts +95 -0
  246. package/templates/root/package.json.mustache +32 -0
  247. package/templates/root/pnpm-workspace.yaml +7 -0
  248. package/templates/root/stripe-app.yaml.mustache +6 -0
  249. package/templates/root/tools/test.mts +38 -0
  250. package/templates/root/tsconfig.base.json +23 -0
  251. package/templates/root/tsconfig.json +15 -0
  252. package/templates/root/ui/package.json +17 -0
  253. package/templates/root/vitest.config.mts +47 -0
package/dist/index.js ADDED
@@ -0,0 +1,3758 @@
1
+ // src/templates/template-manager.ts
2
+ import { _TemplateManager } from "@stripe/extensibility-tool-utils";
3
+
4
+ // src/templates/fs/in-memory.ts
5
+ import { _createInMemoryTemplateFS } from "@stripe/extensibility-tool-utils";
6
+
7
+ // templates-virtual:./_impl.js
8
+ var TEMPLATE_FS_IMAGE = [
9
+ {
10
+ path: "extensions/billing.bill.discount_calculation/index.test.ts",
11
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
12
+
13
+ import MyDiscountCalculation from './index.js';
14
+
15
+ describe('MyDiscountCalculation', () => {
16
+ let instance: MyDiscountCalculation;
17
+
18
+ beforeEach(() => {
19
+ instance = new MyDiscountCalculation();
20
+ });
21
+
22
+ it('should be constructable', () => {
23
+ expect(instance).toBeInstanceOf(MyDiscountCalculation);
24
+ });
25
+ });
26
+ `
27
+ },
28
+ {
29
+ path: "extensions/billing.bill.discount_calculation/index.ts",
30
+ content: `import type { Billing } from '@stripe/extensibility-sdk/extensions';
31
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
32
+
33
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
34
+ interface MyDiscountCalculationConfig extends Record<string, unknown> {}
35
+
36
+ export default class MyDiscountCalculation implements Billing.Bill
37
+ .DiscountCalculation<MyDiscountCalculationConfig> {
38
+ computeDiscounts(
39
+ request: Billing.Bill.DiscountCalculation.DiscountableItem,
40
+ _config: MyDiscountCalculationConfig,
41
+ _context: Context
42
+ ) {
43
+ // TODO: implement your discount logic here
44
+
45
+ return {
46
+ discount: { amount: request.grossAmount },
47
+ };
48
+ }
49
+ }
50
+ `
51
+ },
52
+ {
53
+ path: "extensions/billing.customer_balance_application/index.test.ts",
54
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
55
+
56
+ import MyCustomerBalanceApplication from './index.js';
57
+
58
+ describe('MyCustomerBalanceApplication', () => {
59
+ let instance: MyCustomerBalanceApplication;
60
+
61
+ beforeEach(() => {
62
+ instance = new MyCustomerBalanceApplication();
63
+ });
64
+
65
+ it('should be constructable', () => {
66
+ expect(instance).toBeInstanceOf(MyCustomerBalanceApplication);
67
+ });
68
+ });
69
+ `
70
+ },
71
+ {
72
+ path: "extensions/billing.customer_balance_application/index.ts",
73
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
74
+
75
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
76
+ interface MyCustomerBalanceApplicationConfig extends Record<string, unknown> {}
77
+
78
+ export default class MyCustomerBalanceApplication implements Billing.CustomerBalanceApplication<MyCustomerBalanceApplicationConfig> {
79
+ computeAppliedCustomerBalance(
80
+ request: Billing.CustomerBalanceApplication.CustomerBalanceApplicationInput,
81
+ _config: MyCustomerBalanceApplicationConfig,
82
+ _context: Context
83
+ ) {
84
+ // TODO: implement your customer balance logic here
85
+
86
+ return {
87
+ appliedCustomerBalance: request.customerBalance,
88
+ };
89
+ }
90
+ }
91
+ `
92
+ },
93
+ {
94
+ path: "extensions/billing.invoice_collection_setting/index.test.ts",
95
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
96
+
97
+ import MyInvoiceCollectionSetting from './index.js';
98
+
99
+ describe('MyInvoiceCollectionSetting', () => {
100
+ let instance: MyInvoiceCollectionSetting;
101
+
102
+ beforeEach(() => {
103
+ instance = new MyInvoiceCollectionSetting();
104
+ });
105
+
106
+ it('should be constructable', () => {
107
+ expect(instance).toBeInstanceOf(MyInvoiceCollectionSetting);
108
+ });
109
+ });
110
+ `
111
+ },
112
+ {
113
+ path: "extensions/billing.invoice_collection_setting/index.ts",
114
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
115
+
116
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
117
+ interface MyInvoiceCollectionSettingConfig extends Record<string, unknown> {}
118
+
119
+ export default class MyInvoiceCollectionSetting implements Billing.InvoiceCollectionSetting<MyInvoiceCollectionSettingConfig> {
120
+ collectionOverride(
121
+ _request: Billing.InvoiceCollectionSetting.InvoiceCollectionRequest,
122
+ _config: MyInvoiceCollectionSettingConfig,
123
+ _context: Context
124
+ ) {
125
+ // TODO: implement your collection setting logic here
126
+
127
+ return {};
128
+ }
129
+ }
130
+ `
131
+ },
132
+ {
133
+ path: "extensions/billing.prorations/index.test.ts",
134
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
135
+
136
+ import MyProrations from './index.js';
137
+
138
+ describe('MyProrations', () => {
139
+ let instance: MyProrations;
140
+
141
+ beforeEach(() => {
142
+ instance = new MyProrations();
143
+ });
144
+
145
+ it('should be constructable', () => {
146
+ expect(instance).toBeInstanceOf(MyProrations);
147
+ });
148
+ });
149
+ `
150
+ },
151
+ {
152
+ path: "extensions/billing.prorations/index.ts",
153
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
154
+
155
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
156
+ interface MyProrationsConfig extends Record<string, unknown> {}
157
+
158
+ export default class MyProrations implements Billing.Prorations<MyProrationsConfig> {
159
+ prorateItems(
160
+ _request: Billing.Prorations.ProrateItemsInput,
161
+ _config: MyProrationsConfig,
162
+ _context: Context
163
+ ) {
164
+ // TODO: implement your proration logic here
165
+
166
+ return {
167
+ items: [],
168
+ };
169
+ }
170
+ }
171
+ `
172
+ },
173
+ {
174
+ path: "extensions/billing.recurring_billing_item_handling/index.test.ts",
175
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
176
+
177
+ import MyRecurringBillingItemHandling from './index.js';
178
+
179
+ describe('MyRecurringBillingItemHandling', () => {
180
+ let instance: MyRecurringBillingItemHandling;
181
+
182
+ beforeEach(() => {
183
+ instance = new MyRecurringBillingItemHandling();
184
+ });
185
+
186
+ it('should be constructable', () => {
187
+ expect(instance).toBeInstanceOf(MyRecurringBillingItemHandling);
188
+ });
189
+ });
190
+ `
191
+ },
192
+ {
193
+ path: "extensions/billing.recurring_billing_item_handling/index.ts",
194
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
195
+
196
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
197
+ interface MyRecurringBillingItemHandlingConfig extends Record<string, unknown> {}
198
+
199
+ export default class MyRecurringBillingItemHandling implements Billing.RecurringBillingItemHandling<MyRecurringBillingItemHandlingConfig> {
200
+ beforeItemCreation(
201
+ _request: Billing.RecurringBillingItemHandling.BeforeItemCreationInput,
202
+ _config: MyRecurringBillingItemHandlingConfig,
203
+ _context: Context
204
+ ) {
205
+ // TODO: implement your before-item-creation logic here
206
+
207
+ return {
208
+ items: [],
209
+ };
210
+ }
211
+
212
+ filterItems(
213
+ _request: Billing.RecurringBillingItemHandling.FilterItemsInput,
214
+ _config: MyRecurringBillingItemHandlingConfig,
215
+ _context: Context
216
+ ) {
217
+ // TODO: implement your filter-items logic here
218
+
219
+ return {
220
+ items: [],
221
+ };
222
+ }
223
+
224
+ groupItems(
225
+ _request: Billing.RecurringBillingItemHandling.GroupItemsInput,
226
+ _config: MyRecurringBillingItemHandlingConfig,
227
+ _context: Context
228
+ ) {
229
+ // TODO: implement your group-items logic here
230
+
231
+ return {
232
+ groups: [],
233
+ };
234
+ }
235
+ }
236
+ `
237
+ },
238
+ {
239
+ path: "extensions/common/.prettierignore",
240
+ content: `dist
241
+ generated
242
+ node_modules
243
+ `
244
+ },
245
+ {
246
+ path: "extensions/common/eslint.config.mts.mustache",
247
+ content: `import eslint from '@eslint/js';
248
+ import { defineConfig } from 'eslint/config';
249
+ import tseslint from 'typescript-eslint';
250
+ import eslintConfigPrettier from 'eslint-config-prettier/flat';
251
+
252
+ import globals from 'globals';
253
+
254
+ import stripeAppsConfig from '@stripe/extensibility-eslint-plugin';
255
+ import extensionTypeConfig from '@stripe/extensibility-eslint-plugin/{{extensionInterfaceId}}';
256
+
257
+ export default defineConfig([
258
+ eslint.configs.recommended,
259
+ ...tseslint.configs.recommended,
260
+ ...stripeAppsConfig,
261
+ ...extensionTypeConfig,
262
+
263
+ // Global ignores
264
+ {
265
+ ignores: ['dist', 'generated', 'node_modules'],
266
+ },
267
+
268
+ // TypeScript source files (with type-checking)
269
+ {
270
+ name: 'sources',
271
+ files: ['src/**/*.ts'],
272
+ ignores: ['**/*.test.ts', '**/__tests__/**'],
273
+ languageOptions: {
274
+ globals: {
275
+ ...globals.node,
276
+ },
277
+ parserOptions: {
278
+ projectService: true,
279
+ tsconfigRootDir: import.meta.dirname,
280
+ },
281
+ },
282
+ },
283
+
284
+ // Test files (type-checking, relaxed rules)
285
+ {
286
+ name: 'tests',
287
+ files: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts'],
288
+ languageOptions: {
289
+ globals: {
290
+ ...globals.node,
291
+ },
292
+ parserOptions: {
293
+ projectService: true,
294
+ tsconfigRootDir: import.meta.dirname,
295
+ },
296
+ },
297
+ rules: {
298
+ '@typescript-eslint/no-explicit-any': 'off',
299
+ '@typescript-eslint/no-unused-vars': 'off',
300
+ 'no-console': 'off',
301
+ },
302
+ },
303
+
304
+ // Config files
305
+ {
306
+ name: 'ts-configs',
307
+ files: ['*.config.m?ts', 'eslint.config.mts'],
308
+ languageOptions: {
309
+ globals: {
310
+ ...globals.node,
311
+ },
312
+ parserOptions: {
313
+ projectService: false,
314
+ },
315
+ },
316
+ rules: {
317
+ '@typescript-eslint/no-unused-vars': 'off',
318
+ },
319
+ },
320
+
321
+ // JavaScript/MJS files (scripts, configs)
322
+ {
323
+ name: 'js-configs',
324
+ files: ['**/*.js', '**/*.mjs'],
325
+ languageOptions: {
326
+ globals: {
327
+ ...globals.node,
328
+ },
329
+ parserOptions: {
330
+ projectService: false,
331
+ },
332
+ },
333
+ rules: {
334
+ '@typescript-eslint/no-require-imports': 'off',
335
+ '@typescript-eslint/no-unused-vars': 'off',
336
+ 'no-unused-vars': 'off',
337
+ },
338
+ },
339
+
340
+ eslintConfigPrettier,
341
+ ]);
342
+ `
343
+ },
344
+ {
345
+ path: "extensions/common/package.json.mustache",
346
+ content: `{
347
+ "name": "{{id}}",
348
+ "version": "{{version}}",
349
+ "description": "{{name}}",
350
+ "private": true,
351
+ "license": "~~proprietary~~",
352
+ "type": "module",
353
+ "scripts": {
354
+ "build": "tsc -p tsconfig.build.json && pnpm build:schemas",
355
+ "build:schemas": "gen-schemas --root ../.. --extension-id \\"$npm_package_name\\" --out-dir generated --schema-name config",
356
+ "lint": "pnpm lint:types && pnpm lint:eslint && pnpm lint:format",
357
+ "lint:types": "tsc -p tsconfig.build.json --noEmit && tsc -p tsconfig.json --noEmit",
358
+ "lint:eslint": "eslint .",
359
+ "lint:format": "prettier --check .",
360
+ "fix:lint": "eslint --fix .",
361
+ "fix:format": "prettier --write .",
362
+ "test": "vitest --root ../.. run --project \\"$npm_package_name\\"",
363
+ "test:watch": "pnpm test --watch",
364
+ "dev": "concurrently -n build,lint,test -c blue,yellow,green 'tsc -p tsconfig.json -w --noEmit' 'chokidar \\"src/**/*.{ts,json}\\" -c \\"eslint .\\"' 'pnpm test --watch --no-clear-screen'",
365
+ "stripe:regen": "gen-workspace --root ../.. --package-dir . --template-id {{extensionInterfaceId}}"
366
+ },
367
+ "lint-staged": {
368
+ "*.{ts,mts,mjs,js}": ["eslint --fix", "prettier --write"],
369
+ "*.{json,md,yaml}": "prettier --write"
370
+ }
371
+ }
372
+ `
373
+ },
374
+ {
375
+ path: "extensions/common/tsconfig.build.json.mustache",
376
+ content: `{
377
+ "extends": "../../tsconfig.base.json",
378
+ "compilerOptions": {
379
+ "lib": null,
380
+ "noLib": true,
381
+ "outDir": "./dist",
382
+ "rootDir": "./src"
383
+ },
384
+ "include": [
385
+ "src/**/*.ts",
386
+ "node_modules/@stripe/extensibility-sdk/tslibs/5.9.3/lib.es2022.{{executionProfile}}.d.ts",
387
+ "node_modules/@stripe/extensibility-sdk/tslibs/lib.{{executionProfile}}.globals.d.ts"
388
+ ],
389
+ "exclude": ["src/**/*.test.ts", "src/**/__tests__"]
390
+ }
391
+ `
392
+ },
393
+ {
394
+ path: "extensions/common/tsconfig.json.mustache",
395
+ content: `{
396
+ "extends": "../../tsconfig.json",
397
+ "compilerOptions": {
398
+ "rootDir": ".",
399
+ "plugins": [
400
+ {
401
+ "name": "@stripe/extensibility-language-server/plugin"
402
+ }
403
+ ]
404
+ },
405
+ "include": [
406
+ "src/**/*.ts",
407
+ "node_modules/@stripe/extensibility-sdk/tslibs/lib.{{executionProfile}}.globals.d.ts"
408
+ ],
409
+ "exclude": ["dist"]
410
+ }
411
+ `
412
+ },
413
+ {
414
+ path: "extensions/core.workflows.custom_action/custom_input.schema.json",
415
+ content: `{
416
+ "$schema": "http://json-schema.org/draft-07/schema#",
417
+ "type": "object",
418
+ "properties": {},
419
+ "additionalProperties": false
420
+ }
421
+ `
422
+ },
423
+ {
424
+ path: "extensions/core.workflows.custom_action/index.test.ts",
425
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
426
+
427
+ import MyCustomAction from './index.js';
428
+
429
+ describe('MyCustomAction', () => {
430
+ let instance: MyCustomAction;
431
+
432
+ beforeEach(() => {
433
+ instance = new MyCustomAction();
434
+ });
435
+
436
+ it('should be constructable', () => {
437
+ expect(instance).toBeInstanceOf(MyCustomAction);
438
+ });
439
+ });
440
+ `
441
+ },
442
+ {
443
+ path: "extensions/core.workflows.custom_action/index.ts",
444
+ content: `import type { Core } from '@stripe/extensibility-sdk/extensions';
445
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
446
+
447
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
448
+ interface MyCustomActionConfig extends Record<string, unknown> {}
449
+
450
+ export default class MyCustomAction implements Core.Workflows
451
+ .CustomAction<MyCustomActionConfig> {
452
+ execute(
453
+ _request: Core.Workflows.CustomAction.ExecuteCustomActionRequest,
454
+ _config: MyCustomActionConfig,
455
+ _context: Context
456
+ ) {
457
+ // TODO: implement your action logic here
458
+
459
+ return {};
460
+ }
461
+
462
+ getFormState(
463
+ _request: Core.Workflows.CustomAction.GetFormStateRequest,
464
+ _config: MyCustomActionConfig,
465
+ _context: Context
466
+ ) {
467
+ // TODO: implement your logic here
468
+
469
+ return {
470
+ values: {},
471
+ config: {},
472
+ };
473
+ }
474
+ }
475
+ `
476
+ },
477
+ {
478
+ path: "extensions/extend.workflows.custom_action/custom_input.schema.json",
479
+ content: `{
480
+ "$schema": "http://json-schema.org/draft-07/schema#",
481
+ "type": "object",
482
+ "properties": {},
483
+ "additionalProperties": false
484
+ }
485
+ `
486
+ },
487
+ {
488
+ path: "extensions/extend.workflows.custom_action/index.test.ts",
489
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
490
+
491
+ import MyCustomAction from './index.js';
492
+
493
+ describe('MyCustomAction', () => {
494
+ let instance: MyCustomAction;
495
+
496
+ beforeEach(() => {
497
+ instance = new MyCustomAction();
498
+ });
499
+
500
+ it('should be constructable', () => {
501
+ expect(instance).toBeInstanceOf(MyCustomAction);
502
+ });
503
+ });
504
+ `
505
+ },
506
+ {
507
+ path: "extensions/extend.workflows.custom_action/index.ts",
508
+ content: `import type { Extend } from '@stripe/extensibility-sdk/extensions';
509
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
510
+
511
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
512
+ interface MyCustomActionConfig extends Record<string, unknown> {}
513
+
514
+ export default class MyCustomAction implements Extend.Workflows
515
+ .CustomAction<MyCustomActionConfig> {
516
+ execute(
517
+ _request: Extend.Workflows.CustomAction.ExecuteCustomActionRequest,
518
+ _config: MyCustomActionConfig,
519
+ _context: Context
520
+ ) {
521
+ // TODO: implement your action logic here
522
+
523
+ return {};
524
+ }
525
+
526
+ getFormState(
527
+ _request: Extend.Workflows.CustomAction.GetFormStateRequest,
528
+ _config: MyCustomActionConfig,
529
+ _context: Context
530
+ ) {
531
+ // TODO: implement your logic here
532
+
533
+ return {
534
+ values: {},
535
+ config: {},
536
+ };
537
+ }
538
+ }
539
+ `
540
+ },
541
+ {
542
+ path: "root/.husky/pre-commit",
543
+ content: `pnpm lint-staged
544
+ `
545
+ },
546
+ {
547
+ path: "root/.prettierignore",
548
+ content: `dist
549
+ generated
550
+ node_modules
551
+ pnpm-lock.yaml
552
+ .build
553
+ `
554
+ },
555
+ {
556
+ path: "root/.prettierrc",
557
+ content: `{
558
+ "semi": true,
559
+ "singleQuote": true,
560
+ "tabWidth": 2,
561
+ "trailingComma": "es5",
562
+ "printWidth": 90
563
+ }
564
+ `
565
+ },
566
+ {
567
+ path: "root/_gitignore",
568
+ content: `# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
569
+
570
+ *~
571
+
572
+ # dependencies
573
+ node_modules
574
+ dist
575
+
576
+ # testing
577
+ /coverage
578
+
579
+ # production
580
+ /.build
581
+
582
+ # misc
583
+ .DS_Store
584
+ .env.local
585
+ .env.development.local
586
+ .env.test.local
587
+ .env.production.local
588
+
589
+ npm-debug.log*
590
+ yarn-debug.log*
591
+ yarn-error.log*
592
+ install-deps.log
593
+
594
+ # generated schemas
595
+ generated
596
+ `
597
+ },
598
+ {
599
+ path: "root/custom-objects/package.json",
600
+ content: `{
601
+ "name": "custom-objects",
602
+ "type": "module",
603
+ "version": "0.0.1",
604
+ "license": "UNLICENSED",
605
+ "private": true,
606
+ "scripts": {
607
+ "build": "test -d src && custom-objects-build --input src --output dist || true",
608
+ "lint:types": "test ! -d src || tsc --noEmit",
609
+ "test": "vitest run"
610
+ },
611
+ "dependencies": {
612
+ "@stripe/extensibility-custom-objects": "0.7.4",
613
+ "@stripe/extensibility-sdk": "0.22.4"
614
+ },
615
+ "devDependencies": {
616
+ "@stripe/extensibility-custom-objects-tools": "0.40.0",
617
+ "@stripe/extensibility-test-helpers": "0.2.7"
618
+ }
619
+ }
620
+ `
621
+ },
622
+ {
623
+ path: "root/custom-objects/tsconfig.json",
624
+ content: `{
625
+ "extends": "../tsconfig.base.json",
626
+ "compilerOptions": {
627
+ "module": "ESNext",
628
+ "moduleResolution": "bundler",
629
+ "types": ["vitest/globals"]
630
+ },
631
+ "exclude": ["dist"]
632
+ }
633
+ `
634
+ },
635
+ {
636
+ path: "root/eslint.config.mts",
637
+ content: `import { readFileSync } from 'node:fs';
638
+ import { dirname, resolve } from 'node:path';
639
+ import { fileURLToPath } from 'node:url';
640
+ import eslint from '@eslint/js';
641
+ import { defineConfig } from 'eslint/config';
642
+ import tseslint from 'typescript-eslint';
643
+ import workspaces from 'eslint-plugin-workspaces';
644
+ import eslintConfigPrettier from 'eslint-config-prettier/flat';
645
+
646
+ import globals from 'globals';
647
+
648
+ import stripeAppsConfig from '@stripe/extensibility-eslint-plugin';
649
+
650
+ // Read additional ignore globs from package.json (written by the generate plugin
651
+ // to exclude generated SDK directories from linting).
652
+ let stripeGlobsToIgnore: string[] = [];
653
+ try {
654
+ const configDir = dirname(fileURLToPath(import.meta.url));
655
+ const packageJsonPath = resolve(configDir, './package.json');
656
+ const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
657
+ const globs = pkg?.stripe?.eslintIgnoreGlobs;
658
+ if (Array.isArray(globs)) {
659
+ stripeGlobsToIgnore = globs.filter(
660
+ (g: unknown): g is string => typeof g === 'string'
661
+ );
662
+ }
663
+ } catch {
664
+ // package.json not found or unparseable \u2014 ignore
665
+ }
666
+
667
+ export default defineConfig([
668
+ eslint.configs.recommended,
669
+ ...tseslint.configs.recommended,
670
+ ...stripeAppsConfig,
671
+
672
+ // Global ignores
673
+ {
674
+ ignores: [
675
+ '.build',
676
+ '**/dist',
677
+ '**/generated',
678
+ '**/node_modules',
679
+ 'extensions/**',
680
+ 'custom-objects',
681
+ 'ui',
682
+ ...stripeGlobsToIgnore,
683
+ ],
684
+ },
685
+
686
+ // Common rules for all files
687
+ {
688
+ plugins: { workspaces },
689
+ rules: {
690
+ ...workspaces.configs.recommended.rules,
691
+ },
692
+ },
693
+
694
+ // Config files (vitest.config.ts, eslint.config.ts, etc.)
695
+ {
696
+ name: 'ts-configs',
697
+ files: ['extensions/*/*.config.m?ts', '*.config.m?ts', 'eslint.config.mts'],
698
+ languageOptions: {
699
+ globals: {
700
+ ...globals.node,
701
+ },
702
+ parserOptions: {
703
+ projectService: false,
704
+ },
705
+ },
706
+ rules: {
707
+ '@typescript-eslint/no-unused-vars': 'off',
708
+ },
709
+ },
710
+
711
+ // JavaScript/MJS files (scripts, configs)
712
+ {
713
+ name: 'js-configs',
714
+ files: ['**/*.js', '**/*.mjs'],
715
+ languageOptions: {
716
+ globals: {
717
+ ...globals.node,
718
+ },
719
+ parserOptions: {
720
+ projectService: false,
721
+ },
722
+ },
723
+ rules: {
724
+ '@typescript-eslint/no-require-imports': 'off',
725
+ '@typescript-eslint/no-unused-vars': 'off',
726
+ 'no-unused-vars': 'off',
727
+ },
728
+ },
729
+
730
+ eslintConfigPrettier,
731
+ ]);
732
+ `
733
+ },
734
+ {
735
+ path: "root/package.json.mustache",
736
+ content: `{
737
+ "name": "{{ appId }}",
738
+ "version": "{{ version }}",
739
+ "description": "{{ appName }}",
740
+ "private": true,
741
+ "license": "~~proprietary~~",
742
+ "engines": {
743
+ "node": ">=20.0.0"
744
+ },
745
+ "packageManager": "pnpm@10.30.3",
746
+ "scripts": {
747
+ "build": "pnpm -r --if-present build",
748
+ "lint": "pnpm lint:types && pnpm lint:eslint && pnpm lint:format",
749
+ "lint:types": "pnpm -r --if-present lint:types",
750
+ "lint:eslint": "eslint . --ignore-pattern 'extensions/**' && pnpm -r --filter './extensions/*' --if-present lint:eslint",
751
+ "lint:format": "prettier --check .",
752
+ "fix:lint": "eslint --fix . --ignore-pattern 'extensions/**' && pnpm -r --filter './extensions/*' --if-present fix:lint",
753
+ "fix:format": "prettier --write .",
754
+ "test": "tsx tools/test.mts",
755
+ "test:watch": "vitest watch",
756
+ "check": "pnpm build && pnpm lint && pnpm test",
757
+ "prepare": "husky",
758
+ "preimage": "pnpm install --lockfile-only && pnpm build && pnpm lint:types && pnpm lint:eslint && pnpm test",
759
+ "image": "rm -rf .build && create-upload-image .build",
760
+ "postimage": "cp pnpm-lock.yaml .build/",
761
+ "stripe:regen": "gen-workspace --package-dir ."
762
+ },
763
+ "lint-staged": {
764
+ "*.{ts,mts,mjs,js}": ["eslint --fix", "prettier --write"],
765
+ "*.{json,md,yaml}": "prettier --write"
766
+ }
767
+ }
768
+ `
769
+ },
770
+ {
771
+ path: "root/pnpm-workspace.yaml",
772
+ content: `packages:
773
+ - extensions/*
774
+ - custom-objects
775
+ - ui
776
+
777
+ overrides:
778
+ vite: ^6.0.0
779
+ `
780
+ },
781
+ {
782
+ path: "root/stripe-app.yaml.mustache",
783
+ content: `$schema: https://stripe.com/stripe-app/v2.0.0/schema
784
+ id: '{{ appId }}'
785
+ name: '{{ appName }}'
786
+ version: 0.0.1
787
+ declarations:
788
+ distribution_type: private
789
+ `
790
+ },
791
+ {
792
+ path: "root/tools/test.mts",
793
+ content: `#!/usr/bin/env tsx
794
+ /**
795
+ * Runs tests across the workspace:
796
+ * - vitest for script extensions and custom objects (extensions/*)
797
+ * - jest for UI extensions (ui/)
798
+ */
799
+ import { existsSync, readdirSync } from 'node:fs';
800
+ import { execSync } from 'node:child_process';
801
+
802
+ const hasExtensions =
803
+ existsSync('extensions') &&
804
+ readdirSync('extensions').some((name) => existsSync(\`extensions/\${name}/package.json\`));
805
+
806
+ const hasUI = existsSync('ui/package.json');
807
+
808
+ let exitCode = 0;
809
+
810
+ function run(cmd: string): void {
811
+ try {
812
+ execSync(cmd, { stdio: 'inherit' });
813
+ } catch (e: unknown) {
814
+ exitCode = (e as NodeJS.ErrnoException & { status?: number }).status ?? 1;
815
+ }
816
+ }
817
+
818
+ if (hasExtensions) {
819
+ run('vitest run');
820
+ }
821
+
822
+ if (hasUI) {
823
+ try {
824
+ execSync('pnpm --filter "./ui" test', { stdio: 'inherit' });
825
+ } catch {
826
+ // UI test failures are non-fatal
827
+ }
828
+ }
829
+
830
+ process.exit(exitCode);
831
+ `
832
+ },
833
+ {
834
+ path: "root/tsconfig.base.json",
835
+ content: `{
836
+ "compilerOptions": {
837
+ "target": "ES2022",
838
+ "module": "NodeNext",
839
+ "moduleResolution": "NodeNext",
840
+ "lib": ["ES2022"],
841
+ "declaration": true,
842
+ "declarationMap": true,
843
+ "esModuleInterop": true,
844
+ "exactOptionalPropertyTypes": false,
845
+ "forceConsistentCasingInFileNames": true,
846
+ "isolatedModules": true,
847
+ "noFallthroughCasesInSwitch": true,
848
+ "noImplicitReturns": true,
849
+ "removeComments": false,
850
+ "resolveJsonModule": true,
851
+ "skipLibCheck": true,
852
+ "sourceMap": true,
853
+ "strict": true,
854
+ "types": [],
855
+ "verbatimModuleSyntax": true
856
+ }
857
+ }
858
+ `
859
+ },
860
+ {
861
+ path: "root/tsconfig.json",
862
+ content: `{
863
+ "extends": "./tsconfig.base.json",
864
+ "compilerOptions": {
865
+ "noEmit": true,
866
+ "plugins": [
867
+ {
868
+ "name": "@stripe/extensibility-language-server/plugin"
869
+ }
870
+ ],
871
+ "preserveWatchOutput": true,
872
+ "types": ["vitest/globals", "node"]
873
+ },
874
+ "include": ["**/*.ts"],
875
+ "exclude": ["**/node_modules", "**/dist"]
876
+ }
877
+ `
878
+ },
879
+ {
880
+ path: "root/ui/package.json",
881
+ content: `{
882
+ "name": "ui",
883
+ "version": "0.0.1",
884
+ "license": "UNLICENSED",
885
+ "private": true,
886
+ "scripts": {
887
+ "test": "jest --passWithNoTests"
888
+ },
889
+ "dependencies": {
890
+ "@stripe/ui-extension-sdk": "^9.1.0"
891
+ },
892
+ "devDependencies": {
893
+ "@stripe/ui-extension-tools": "^0.0.1",
894
+ "@types/jest": "^27.5.2",
895
+ "@types/react": "^17.0.2"
896
+ }
897
+ }
898
+ `
899
+ },
900
+ {
901
+ path: "root/vitest.config.mts",
902
+ content: `import { defineConfig } from 'vitest/config';
903
+ import { existsSync, readdirSync } from 'fs';
904
+ import { dirname, resolve } from 'path';
905
+ import { fileURLToPath } from 'url';
906
+
907
+ const rootDir = dirname(fileURLToPath(import.meta.url));
908
+ const extensionsDir = resolve(rootDir, 'extensions');
909
+
910
+ const extensionProjects = existsSync(extensionsDir)
911
+ ? readdirSync(extensionsDir)
912
+ .filter((name) => existsSync(resolve(extensionsDir, name, 'package.json')))
913
+ .map((name) => resolve(extensionsDir, name))
914
+ : [];
915
+
916
+ const coProjects = existsSync(resolve(rootDir, 'custom-objects/package.json'))
917
+ ? [resolve(rootDir, 'custom-objects')]
918
+ : [];
919
+
920
+ const projects = [...extensionProjects, ...coProjects];
921
+
922
+ if (projects.length === 0) {
923
+ console.debug(\`No vitest projects detected. This means either:
924
+ - You have no extension projects defined, in which case this warning is expected.
925
+ - There is an internal error detecting vitest projects relative to the project root
926
+ \${rootDir}.
927
+ \`);
928
+ }
929
+
930
+ export default projects.length > 0
931
+ ? defineConfig({
932
+ test: {
933
+ projects,
934
+ passWithNoTests: true,
935
+
936
+ // Only run tests from src, not compiled dist
937
+ exclude: ['**/node_modules', '**/dist'],
938
+ // Place snapshots alongside test files instead of in __snapshots__
939
+ snapshotFormat: {
940
+ escapeString: false,
941
+ printBasicPrototype: false,
942
+ },
943
+ resolveSnapshotPath: (testPath, snapExtension) => {
944
+ return testPath.replace(/\\.test\\.ts$/, \`.test\${snapExtension}\`);
945
+ },
946
+ },
947
+ })
948
+ : defineConfig({ test: { passWithNoTests: true, include: [] } });
949
+ `
950
+ }
951
+ ];
952
+ var _fs = _createInMemoryTemplateFS(TEMPLATE_FS_IMAGE);
953
+
954
+ // src/templates/simple-templates.ts
955
+ import {
956
+ _createSimpleTemplate,
957
+ _SingleTemplateManager,
958
+ _createSimpleSingleFileTemplate
959
+ } from "@stripe/extensibility-tool-utils";
960
+
961
+ // src/templates/file-writer.ts
962
+ import path from "path";
963
+ import { mkdir, writeFile, readFile } from "fs/promises";
964
+ import { createInterface } from "readline";
965
+ import { _createLogger } from "@stripe/extensibility-tool-utils";
966
+
967
+ // src/templates/fs-utils.ts
968
+ import { stat } from "fs/promises";
969
+ async function pathExists(filePath, predicate) {
970
+ try {
971
+ const stats = await stat(filePath);
972
+ return predicate(stats);
973
+ } catch (error) {
974
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
975
+ return false;
976
+ }
977
+ throw error;
978
+ }
979
+ }
980
+ async function fileExists(filePath) {
981
+ return pathExists(filePath, (stats) => stats.isFile());
982
+ }
983
+ async function directoryExists(dirPath) {
984
+ return pathExists(dirPath, (stats) => stats.isDirectory());
985
+ }
986
+
987
+ // src/templates/file-writer.ts
988
+ var logger = _createLogger({ name: "file-writer" });
989
+ async function _promptOverwrite(filePath) {
990
+ const prompt = `${filePath} exists. Overwrite [yNaq]? `;
991
+ if (!process.stdin.isTTY) {
992
+ const rl = createInterface({
993
+ input: process.stdin,
994
+ output: process.stdout
995
+ });
996
+ return new Promise((resolve) => {
997
+ rl.question(prompt, (answer) => {
998
+ rl.close();
999
+ const normalized = answer.toLowerCase().trim();
1000
+ switch (normalized) {
1001
+ case "y":
1002
+ case "yes":
1003
+ resolve("overwrite");
1004
+ break;
1005
+ case "n":
1006
+ case "no":
1007
+ case "":
1008
+ resolve("skip");
1009
+ break;
1010
+ case "a":
1011
+ case "all":
1012
+ resolve("overwrite-all");
1013
+ break;
1014
+ case "q":
1015
+ case "quit":
1016
+ resolve("abort");
1017
+ break;
1018
+ default:
1019
+ logger.warn("Invalid input '%s', treating as 'no'", answer);
1020
+ resolve("skip");
1021
+ }
1022
+ });
1023
+ });
1024
+ }
1025
+ process.stdout.write(prompt);
1026
+ return new Promise((resolve) => {
1027
+ const stdin = process.stdin;
1028
+ const wasRaw = stdin.isRaw;
1029
+ stdin.setRawMode(true);
1030
+ stdin.resume();
1031
+ const onData = (buffer) => {
1032
+ stdin.setRawMode(wasRaw || false);
1033
+ stdin.pause();
1034
+ stdin.removeListener("data", onData);
1035
+ const key = buffer.toString();
1036
+ const code = buffer[0];
1037
+ if (code === 3) {
1038
+ process.stdout.write("\nCancelled.\n");
1039
+ setTimeout(() => process.exit(0), 100);
1040
+ return;
1041
+ }
1042
+ if (code === 13 || code === 10) {
1043
+ process.stdout.write("n\n");
1044
+ resolve("skip");
1045
+ return;
1046
+ }
1047
+ const normalized = key.toLowerCase();
1048
+ let decision;
1049
+ switch (normalized) {
1050
+ case "y":
1051
+ process.stdout.write("y\n");
1052
+ decision = "overwrite";
1053
+ break;
1054
+ case "n":
1055
+ process.stdout.write("n\n");
1056
+ decision = "skip";
1057
+ break;
1058
+ case "a":
1059
+ process.stdout.write("a\n");
1060
+ decision = "overwrite-all";
1061
+ break;
1062
+ case "q":
1063
+ process.stdout.write("q\n");
1064
+ decision = "abort";
1065
+ break;
1066
+ default:
1067
+ process.stdout.write(`${key}
1068
+ `);
1069
+ logger.warn("Invalid input '%s', treating as 'no'", key);
1070
+ decision = "skip";
1071
+ }
1072
+ resolve(decision);
1073
+ };
1074
+ stdin.on("data", onData);
1075
+ });
1076
+ }
1077
+ async function _writeGeneratedFiles(files, options = {}) {
1078
+ const { cwd = process.cwd(), onFileWritten, onFileSkipped, onFileIdentical } = options;
1079
+ let write = options.write ?? "abort-if-existing";
1080
+ const existing = [];
1081
+ for (const file of files) {
1082
+ const fullPath = path.join(cwd, file.path);
1083
+ if (await fileExists(fullPath)) {
1084
+ existing.push(file.path);
1085
+ }
1086
+ }
1087
+ if (existing.length > 0 && write === "abort-if-existing") {
1088
+ if (onFileSkipped) {
1089
+ for (const file of files) {
1090
+ if (existing.includes(file.path)) {
1091
+ onFileSkipped(file);
1092
+ }
1093
+ }
1094
+ }
1095
+ return {
1096
+ written: [],
1097
+ existing,
1098
+ skipped: true,
1099
+ aborted: false
1100
+ };
1101
+ }
1102
+ const written = [];
1103
+ for (const file of files) {
1104
+ const fullPath = path.join(cwd, file.path);
1105
+ const fileDir = path.dirname(fullPath);
1106
+ const isExisting = existing.includes(file.path);
1107
+ if (isExisting) {
1108
+ const existingContent = await readFile(fullPath, "utf-8");
1109
+ if (existingContent === file.content) {
1110
+ if (onFileIdentical) {
1111
+ onFileIdentical(file);
1112
+ }
1113
+ continue;
1114
+ }
1115
+ }
1116
+ if (isExisting && (write === "if-missing" || file.precious)) {
1117
+ if (onFileSkipped) {
1118
+ onFileSkipped(file);
1119
+ }
1120
+ continue;
1121
+ }
1122
+ if (isExisting && typeof write === "function") {
1123
+ const decision = await write(file.path, cwd, file.content);
1124
+ switch (decision) {
1125
+ case "skip":
1126
+ if (onFileSkipped) {
1127
+ onFileSkipped(file);
1128
+ }
1129
+ continue;
1130
+ case "overwrite":
1131
+ break;
1132
+ case "overwrite-all":
1133
+ write = "overwrite-all";
1134
+ break;
1135
+ case "abort":
1136
+ return {
1137
+ written,
1138
+ existing,
1139
+ skipped: false,
1140
+ aborted: true
1141
+ };
1142
+ }
1143
+ }
1144
+ if (!await directoryExists(fileDir)) {
1145
+ await mkdir(fileDir, { recursive: true });
1146
+ }
1147
+ await writeFile(fullPath, file.content, "utf-8");
1148
+ if (onFileWritten) {
1149
+ onFileWritten(file, isExisting);
1150
+ }
1151
+ written.push(file.path);
1152
+ }
1153
+ return {
1154
+ written,
1155
+ existing,
1156
+ // Always populated; write='abort-if-existing' returns early above
1157
+ skipped: false,
1158
+ aborted: false
1159
+ };
1160
+ }
1161
+
1162
+ // src/templates/diff-viewer/diff-prompt.ts
1163
+ import path2 from "path";
1164
+
1165
+ // src/templates/diff-viewer/diff-generator.ts
1166
+ import { createPatch } from "diff";
1167
+ import { readFile as readFile2 } from "fs/promises";
1168
+ async function generateDiff(filePath, oldContent, newContent, contextLines = 3) {
1169
+ if (isBinary(oldContent) || isBinary(newContent)) {
1170
+ return {
1171
+ lines: [{ type: "header", text: "Binary file changed" }],
1172
+ oldFileName: filePath,
1173
+ newFileName: filePath,
1174
+ isBinary: true
1175
+ };
1176
+ }
1177
+ const patch = createPatch(filePath, oldContent, newContent, "existing", "new", {
1178
+ context: contextLines
1179
+ });
1180
+ const lines = parsePatch(patch);
1181
+ return {
1182
+ lines,
1183
+ oldFileName: filePath,
1184
+ newFileName: filePath,
1185
+ isBinary: false
1186
+ };
1187
+ }
1188
+ function parsePatch(patch) {
1189
+ const lines = [];
1190
+ const patchLines = patch.split("\n");
1191
+ let oldLine = 0;
1192
+ let newLine = 0;
1193
+ for (const line of patchLines) {
1194
+ if (line.startsWith("@@")) {
1195
+ const match = line.match(/@@ -(\d+),?\d* \+(\d+),?\d* @@/);
1196
+ if (match !== null) {
1197
+ oldLine = parseInt(match[1], 10);
1198
+ newLine = parseInt(match[2], 10);
1199
+ lines.push({ type: "header", text: line });
1200
+ }
1201
+ } else if (line.startsWith("+")) {
1202
+ lines.push({ type: "add", text: line, newLine: newLine++ });
1203
+ } else if (line.startsWith("-")) {
1204
+ lines.push({ type: "remove", text: line, oldLine: oldLine++ });
1205
+ } else if (line.startsWith(" ")) {
1206
+ lines.push({
1207
+ type: "context",
1208
+ text: line,
1209
+ oldLine: oldLine++,
1210
+ newLine: newLine++
1211
+ });
1212
+ } else if (line.startsWith("\\")) {
1213
+ lines.push({ type: "context", text: line });
1214
+ }
1215
+ }
1216
+ return lines;
1217
+ }
1218
+ function isBinary(content) {
1219
+ return content.includes("\0");
1220
+ }
1221
+ async function readExistingFile(resolvedPath) {
1222
+ try {
1223
+ return await readFile2(resolvedPath, "utf-8");
1224
+ } catch (err) {
1225
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
1226
+ return "";
1227
+ }
1228
+ throw err;
1229
+ }
1230
+ }
1231
+
1232
+ // src/templates/diff-viewer/terminal-renderer.ts
1233
+ import { execSync } from "child_process";
1234
+ import stringWidth from "string-width";
1235
+ var ANSI = {
1236
+ // Colors
1237
+ RED: "\x1B[31m",
1238
+ GREEN: "\x1B[32m",
1239
+ CYAN: "\x1B[36m",
1240
+ GRAY: "\x1B[90m",
1241
+ RESET: "\x1B[0m",
1242
+ // Text styles
1243
+ BOLD: "\x1B[1m",
1244
+ DIM: "\x1B[2m"
1245
+ };
1246
+ var BOX_HORIZONTAL = "\u2500";
1247
+ function render(state, filePath, clearPrevious = false) {
1248
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
1249
+ const maxContentHeight = maxTotalHeight - 3;
1250
+ const contentHeight = state.diffLines.length;
1251
+ const windowHeight = Math.min(contentHeight, maxContentHeight);
1252
+ const visibleLines = state.diffLines.slice(
1253
+ state.scrollOffset,
1254
+ state.scrollOffset + windowHeight
1255
+ );
1256
+ const totalLines = state.diffLines.length;
1257
+ const startLine = state.scrollOffset + 1;
1258
+ const endLine = state.scrollOffset + visibleLines.length;
1259
+ if (clearPrevious && state.renderedHeight > 0) {
1260
+ clearPreviousRender(state.renderedHeight - 1);
1261
+ }
1262
+ let output = "";
1263
+ output += renderTopBar(filePath, state.terminalWidth) + "\n";
1264
+ for (const line of visibleLines) {
1265
+ output += colorize(line, state.terminalWidth) + "\n";
1266
+ }
1267
+ output += renderBottomBar(startLine, endLine, totalLines, state, state.terminalWidth) + "\n";
1268
+ output += "\n";
1269
+ output += `overwrite ${filePath} [yNaqd]? `;
1270
+ state.renderedHeight = 1 + visibleLines.length + 1 + 1 + 1;
1271
+ process.stdout.write(output);
1272
+ }
1273
+ function clearPreviousRender(lines) {
1274
+ process.stdout.write(`\x1B[${lines}A`);
1275
+ process.stdout.write("\r");
1276
+ process.stdout.write("\x1B[0J");
1277
+ }
1278
+ function renderTopBar(filePath, width) {
1279
+ const prefix = BOX_HORIZONTAL.repeat(3) + " ";
1280
+ const suffix = " " + BOX_HORIZONTAL.repeat(3);
1281
+ const availableWidth = width - stringWidth(prefix) - stringWidth(suffix);
1282
+ let displayName = filePath;
1283
+ if (stringWidth(displayName) + 1 > availableWidth) {
1284
+ while (stringWidth("..." + displayName) + 1 > availableWidth && displayName.length > 0) {
1285
+ displayName = displayName.slice(1);
1286
+ }
1287
+ displayName = "..." + displayName;
1288
+ }
1289
+ const paddingLength = Math.max(0, availableWidth - stringWidth(displayName) - 1);
1290
+ const padding = BOX_HORIZONTAL.repeat(paddingLength);
1291
+ return ANSI.CYAN + prefix + ANSI.BOLD + displayName + ANSI.RESET + " " + ANSI.CYAN + padding + suffix + ANSI.RESET;
1292
+ }
1293
+ function renderBottomBar(startLine, endLine, totalLines, _state, width) {
1294
+ const prefix = BOX_HORIZONTAL.repeat(3) + " ";
1295
+ const positionIndicator = `${startLine}-${endLine}/${totalLines}`;
1296
+ const content = positionIndicator;
1297
+ const suffix = " " + BOX_HORIZONTAL.repeat(3);
1298
+ const availableWidth = width - stringWidth(prefix) - stringWidth(suffix);
1299
+ const paddingLength = Math.max(0, availableWidth - stringWidth(content));
1300
+ const padding = BOX_HORIZONTAL.repeat(paddingLength);
1301
+ return ANSI.CYAN + prefix + ANSI.RESET + ANSI.DIM + content + ANSI.RESET + ANSI.CYAN + padding + suffix + ANSI.RESET;
1302
+ }
1303
+ function clearDiffWindow() {
1304
+ process.stdout.write("\n");
1305
+ }
1306
+ function colorize(line, terminalWidth) {
1307
+ const maxWidth = Math.max(10, terminalWidth - 3);
1308
+ const text = truncateLine(line.text, maxWidth);
1309
+ switch (line.type) {
1310
+ case "add":
1311
+ return ANSI.GREEN + text + ANSI.RESET;
1312
+ case "remove":
1313
+ return ANSI.RED + text + ANSI.RESET;
1314
+ case "header":
1315
+ return ANSI.CYAN + text + ANSI.RESET;
1316
+ case "context":
1317
+ return ANSI.GRAY + text + ANSI.RESET;
1318
+ default:
1319
+ return text;
1320
+ }
1321
+ }
1322
+ function truncateLine(text, maxWidth) {
1323
+ if (stringWidth(text) <= maxWidth) {
1324
+ return text;
1325
+ }
1326
+ let truncated = text;
1327
+ while (stringWidth(truncated + "...") > maxWidth && truncated.length > 0) {
1328
+ truncated = truncated.slice(0, -1);
1329
+ }
1330
+ return truncated + "...";
1331
+ }
1332
+ function getTerminalSize() {
1333
+ let columns = 80;
1334
+ let rows = 24;
1335
+ try {
1336
+ const sttyOutput = execSync("stty size </dev/tty", {
1337
+ encoding: "utf-8",
1338
+ stdio: ["ignore", "pipe", "ignore"],
1339
+ timeout: 200,
1340
+ shell: "/bin/bash"
1341
+ }).trim();
1342
+ const parts = sttyOutput.split(/\s+/);
1343
+ if (parts.length === 2) {
1344
+ const sttyRows = parseInt(parts[0], 10);
1345
+ const sttyCols = parseInt(parts[1], 10);
1346
+ if (!isNaN(sttyRows) && sttyRows > 0) {
1347
+ rows = sttyRows;
1348
+ }
1349
+ if (!isNaN(sttyCols) && sttyCols > 0) {
1350
+ columns = sttyCols;
1351
+ }
1352
+ }
1353
+ } catch {
1354
+ try {
1355
+ const tputCols = execSync("tput cols </dev/tty", {
1356
+ encoding: "utf-8",
1357
+ stdio: ["ignore", "pipe", "ignore"],
1358
+ timeout: 100,
1359
+ shell: "/bin/bash"
1360
+ }).trim();
1361
+ const cols = parseInt(tputCols, 10);
1362
+ if (!isNaN(cols) && cols > 0) {
1363
+ columns = cols;
1364
+ }
1365
+ } catch {
1366
+ }
1367
+ try {
1368
+ const tputRows = execSync("tput lines </dev/tty", {
1369
+ encoding: "utf-8",
1370
+ stdio: ["ignore", "pipe", "ignore"],
1371
+ timeout: 100,
1372
+ shell: "/bin/bash"
1373
+ }).trim();
1374
+ const lns = parseInt(tputRows, 10);
1375
+ if (!isNaN(lns) && lns > 0) {
1376
+ rows = lns;
1377
+ }
1378
+ } catch {
1379
+ }
1380
+ }
1381
+ return { rows, columns };
1382
+ }
1383
+
1384
+ // src/templates/diff-viewer/diff-prompt.ts
1385
+ import { _createLogger as _createLogger2 } from "@stripe/extensibility-tool-utils";
1386
+ var logger2 = _createLogger2({ name: "diff-prompt" });
1387
+ function isInteractiveTerminal() {
1388
+ if (process.env["CI"] === "true" || process.env["CI"] === "1") {
1389
+ return false;
1390
+ }
1391
+ const term = process.env["TERM"];
1392
+ if (!term || term === "dumb") {
1393
+ return false;
1394
+ }
1395
+ if (typeof process.stdin.setRawMode !== "function") {
1396
+ return false;
1397
+ }
1398
+ const termSize = getTerminalSize();
1399
+ if (termSize.rows === 24 && termSize.columns === 80) {
1400
+ }
1401
+ return true;
1402
+ }
1403
+ async function _advancedDiffPrompt(filePath, cwd, newContent) {
1404
+ const resolvedPath = path2.resolve(cwd, filePath);
1405
+ if (!isInteractiveTerminal()) {
1406
+ return await _promptOverwrite(filePath);
1407
+ }
1408
+ try {
1409
+ const existingContent = await readExistingFile(resolvedPath);
1410
+ const diffResult = await generateDiff(filePath, existingContent, newContent);
1411
+ const termSize = getTerminalSize();
1412
+ if (termSize.rows < 20) {
1413
+ return await _promptOverwrite(filePath);
1414
+ }
1415
+ if (diffResult.lines.length > 5e3) {
1416
+ logger2.info("Diff too large to display comfortably");
1417
+ return await _promptOverwrite(filePath);
1418
+ }
1419
+ const wasRaw = process.stdin.isRaw ?? false;
1420
+ try {
1421
+ process.stdin.setRawMode(true);
1422
+ } catch {
1423
+ return await _promptOverwrite(filePath);
1424
+ }
1425
+ process.stdin.resume();
1426
+ const maxTotalHeight = Math.floor(termSize.rows * 0.75);
1427
+ const maxContentHeight = maxTotalHeight - 3;
1428
+ const windowHeight = Math.min(diffResult.lines.length, maxContentHeight);
1429
+ const state = {
1430
+ scrollOffset: 0,
1431
+ maxScroll: Math.max(0, diffResult.lines.length - windowHeight),
1432
+ diffLines: diffResult.lines,
1433
+ terminalHeight: termSize.rows,
1434
+ terminalWidth: termSize.columns,
1435
+ wasRaw,
1436
+ renderedHeight: 0,
1437
+ fullFileMode: false
1438
+ };
1439
+ render(state, filePath, false);
1440
+ return new Promise((resolve) => {
1441
+ const onExit = () => {
1442
+ cleanup(state.wasRaw, onData, onExit);
1443
+ };
1444
+ const onData = (buffer) => {
1445
+ handleKeypress(buffer, state, filePath, newContent, existingContent).then((result) => {
1446
+ if (result !== "continue") {
1447
+ cleanup(state.wasRaw, onData, onExit);
1448
+ resolve(result);
1449
+ }
1450
+ }).catch((err) => {
1451
+ cleanup(state.wasRaw, onData, onExit);
1452
+ logger2.error({ err }, "Error handling keypress");
1453
+ resolve("abort");
1454
+ });
1455
+ };
1456
+ process.stdin.on("data", onData);
1457
+ process.on("exit", onExit);
1458
+ });
1459
+ } catch (err) {
1460
+ logger2.warn({ err }, "Error displaying diff, using basic prompt");
1461
+ return await _promptOverwrite(filePath);
1462
+ }
1463
+ }
1464
+ async function handleKeypress(buffer, state, filePath, newContent, existingContent) {
1465
+ const code = buffer[0];
1466
+ const key = buffer.toString();
1467
+ if (code === 3) {
1468
+ process.stdout.write("\nCancelled.\n");
1469
+ return "abort";
1470
+ }
1471
+ switch (key.toLowerCase()) {
1472
+ case "y":
1473
+ return "overwrite";
1474
+ case "n":
1475
+ case "\r":
1476
+ case "\n":
1477
+ return "skip";
1478
+ case "a":
1479
+ return "overwrite-all";
1480
+ case "q":
1481
+ return "abort";
1482
+ case "d":
1483
+ await toggleDiffContext(state, filePath, newContent, existingContent);
1484
+ return "continue";
1485
+ }
1486
+ if (buffer.length >= 3 && buffer[0] === 27 && buffer[1] === 91) {
1487
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
1488
+ const maxContentHeight = maxTotalHeight - 3;
1489
+ const windowHeight = Math.min(state.diffLines.length, maxContentHeight);
1490
+ let scrollDelta = 0;
1491
+ if (buffer[2] === 65) {
1492
+ scrollDelta = -1;
1493
+ } else if (buffer[2] === 66) {
1494
+ scrollDelta = 1;
1495
+ } else if (buffer[2] === 53) {
1496
+ scrollDelta = -windowHeight;
1497
+ } else if (buffer[2] === 54) {
1498
+ scrollDelta = windowHeight;
1499
+ }
1500
+ const newScrollOffset = Math.max(
1501
+ 0,
1502
+ Math.min(state.maxScroll, state.scrollOffset + scrollDelta)
1503
+ );
1504
+ if (newScrollOffset !== state.scrollOffset) {
1505
+ state.scrollOffset = newScrollOffset;
1506
+ render(state, filePath, true);
1507
+ }
1508
+ }
1509
+ return "continue";
1510
+ }
1511
+ function cleanup(wasRaw, onData, onExit) {
1512
+ if (process.stdin.setRawMode !== void 0) {
1513
+ process.stdin.setRawMode(wasRaw);
1514
+ }
1515
+ process.stdin.pause();
1516
+ if (onData) {
1517
+ process.stdin.off("data", onData);
1518
+ }
1519
+ if (onExit) {
1520
+ process.off("exit", onExit);
1521
+ }
1522
+ clearDiffWindow();
1523
+ }
1524
+ async function toggleDiffContext(state, filePath, newContent, existingContent) {
1525
+ state.fullFileMode = !state.fullFileMode;
1526
+ const contextLines = state.fullFileMode ? 1e4 : 3;
1527
+ const visibleStartIndex = state.scrollOffset;
1528
+ let referenceLineFinder = null;
1529
+ let skippedLines = 0;
1530
+ for (let i = visibleStartIndex; i < state.diffLines.length; i++) {
1531
+ const line = state.diffLines[i];
1532
+ if (line !== void 0) {
1533
+ if (line.type === "header") {
1534
+ skippedLines++;
1535
+ continue;
1536
+ }
1537
+ if (line.newLine !== void 0) {
1538
+ const targetNewLine = line.newLine;
1539
+ referenceLineFinder = (dl) => dl.newLine !== void 0 && dl.newLine >= targetNewLine - skippedLines;
1540
+ break;
1541
+ } else if (line.oldLine !== void 0) {
1542
+ const targetOldLine = line.oldLine;
1543
+ referenceLineFinder = (dl) => dl.oldLine !== void 0 && dl.oldLine >= targetOldLine - skippedLines;
1544
+ break;
1545
+ }
1546
+ }
1547
+ }
1548
+ const diffResult = await generateDiff(
1549
+ filePath,
1550
+ existingContent,
1551
+ newContent,
1552
+ contextLines
1553
+ );
1554
+ state.diffLines = diffResult.lines;
1555
+ let newScrollOffset = 0;
1556
+ if (referenceLineFinder !== null) {
1557
+ const referenceIndex = diffResult.lines.findIndex(referenceLineFinder);
1558
+ if (referenceIndex !== -1) {
1559
+ newScrollOffset = Math.max(0, referenceIndex);
1560
+ }
1561
+ }
1562
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
1563
+ const maxContentHeight = maxTotalHeight - 3;
1564
+ const windowHeight = Math.min(diffResult.lines.length, maxContentHeight);
1565
+ state.maxScroll = Math.max(0, diffResult.lines.length - windowHeight);
1566
+ state.scrollOffset = Math.min(newScrollOffset, state.maxScroll);
1567
+ render(state, filePath, true);
1568
+ }
1569
+
1570
+ // src/templates/extensions/types.ts
1571
+ var _ExtensionTemplateManager = class extends _TemplateManager {
1572
+ /**
1573
+ * Get summary info for all registered extension templates
1574
+ */
1575
+ getTemplateInfo() {
1576
+ return this.getTemplateEntries().map(([key, t]) => ({
1577
+ key,
1578
+ description: t.description,
1579
+ deprecated: t.deprecated ?? false,
1580
+ hidden: t.hidden ?? false,
1581
+ methods: t.methods
1582
+ }));
1583
+ }
1584
+ };
1585
+
1586
+ // src/dependencies/index.ts
1587
+ import path3 from "path";
1588
+ import fs from "fs";
1589
+ import os from "os";
1590
+ import { execSync as execSync2 } from "child_process";
1591
+ import PackageJson from "@npmcli/package-json";
1592
+ import * as semver from "semver";
1593
+ import { load as parseToml } from "js-toml";
1594
+ import { _createCliContext } from "@stripe/extensibility-tool-utils";
1595
+ function _npmDep(name, version) {
1596
+ return { type: "npm", name, version };
1597
+ }
1598
+ function _devNpmDep(name, version) {
1599
+ return { type: "dev-npm", name, version };
1600
+ }
1601
+ function _stripeCliPluginDep(name, minVersion) {
1602
+ return minVersion ? { type: "stripe-cli-plugin", name, minVersion } : { type: "stripe-cli-plugin", name };
1603
+ }
1604
+ function _detectPackageManager(cwd) {
1605
+ if (fs.existsSync(path3.join(cwd, "pnpm-lock.yaml"))) {
1606
+ return "pnpm";
1607
+ }
1608
+ if (fs.existsSync(path3.join(cwd, "yarn.lock"))) {
1609
+ return "yarn";
1610
+ }
1611
+ if (fs.existsSync(path3.join(cwd, "package-lock.json"))) {
1612
+ return "npm";
1613
+ }
1614
+ let currentDir = cwd;
1615
+ const root = path3.parse(currentDir).root;
1616
+ while (currentDir !== root) {
1617
+ const parentDir = path3.dirname(currentDir);
1618
+ if (parentDir === currentDir) break;
1619
+ if (fs.existsSync(path3.join(parentDir, "pnpm-lock.yaml"))) {
1620
+ if (fs.existsSync(path3.join(parentDir, "pnpm-workspace.yaml"))) {
1621
+ return "pnpm";
1622
+ }
1623
+ }
1624
+ if (fs.existsSync(path3.join(parentDir, "yarn.lock"))) {
1625
+ return "yarn";
1626
+ }
1627
+ if (fs.existsSync(path3.join(parentDir, "package-lock.json"))) {
1628
+ return "npm";
1629
+ }
1630
+ currentDir = parentDir;
1631
+ }
1632
+ return "npm";
1633
+ }
1634
+ var _NpmDependencyHandler = class {
1635
+ cwd;
1636
+ quiet;
1637
+ devDependencies;
1638
+ context;
1639
+ constructor(options) {
1640
+ this.cwd = options.cwd;
1641
+ this.quiet = options.quiet;
1642
+ this.devDependencies = options.devDependencies ?? false;
1643
+ this.context = options.context ?? _createCliContext();
1644
+ }
1645
+ get dependencyKey() {
1646
+ return this.devDependencies ? "devDependencies" : "dependencies";
1647
+ }
1648
+ get dependencyLabel() {
1649
+ return this.devDependencies ? "devDependencies" : "dependencies";
1650
+ }
1651
+ /** Check whether the npm dependency is already present in package.json. */
1652
+ async check(dep) {
1653
+ const packageJsonPath = path3.join(this.cwd, "package.json");
1654
+ if (!fs.existsSync(packageJsonPath)) {
1655
+ return {
1656
+ satisfied: false,
1657
+ message: `package.json not found at ${this.cwd}`
1658
+ };
1659
+ }
1660
+ const pkgJson = await PackageJson.load(this.cwd);
1661
+ const rawDeps = pkgJson.content[this.dependencyKey];
1662
+ const deps = rawDeps ?? {};
1663
+ const currentVersion = deps[dep.name];
1664
+ if (currentVersion === void 0) {
1665
+ return {
1666
+ satisfied: false,
1667
+ message: `${dep.name} not found in ${this.dependencyLabel}`
1668
+ };
1669
+ }
1670
+ if (currentVersion === dep.version) {
1671
+ return {
1672
+ satisfied: true,
1673
+ currentVersion,
1674
+ message: `${dep.name}@${dep.version} already in ${this.dependencyLabel}`
1675
+ };
1676
+ }
1677
+ if (this.versionsCompatible(currentVersion, dep.version)) {
1678
+ return {
1679
+ satisfied: true,
1680
+ currentVersion,
1681
+ message: `${dep.name}@${currentVersion} satisfies ${dep.version}`
1682
+ };
1683
+ }
1684
+ return {
1685
+ satisfied: false,
1686
+ currentVersion,
1687
+ message: `${dep.name}@${currentVersion} does not satisfy ${dep.version}`
1688
+ };
1689
+ }
1690
+ /** Check whether the requested version conflicts with the currently installed version. */
1691
+ async checkConflict(dep) {
1692
+ const packageJsonPath = path3.join(this.cwd, "package.json");
1693
+ if (!fs.existsSync(packageJsonPath)) {
1694
+ return { hasConflict: false };
1695
+ }
1696
+ const pkgJson = await PackageJson.load(this.cwd);
1697
+ const rawDeps = pkgJson.content[this.dependencyKey];
1698
+ const deps = rawDeps ?? {};
1699
+ const existingVersion = deps[dep.name];
1700
+ if (existingVersion === void 0) {
1701
+ return { hasConflict: false };
1702
+ }
1703
+ if (existingVersion === dep.version) {
1704
+ return { hasConflict: false };
1705
+ }
1706
+ const existingMajor = this.extractMajorVersion(existingVersion);
1707
+ const requestedMajor = this.extractMajorVersion(dep.version);
1708
+ if (existingMajor !== null && requestedMajor !== null && existingMajor !== requestedMajor) {
1709
+ return {
1710
+ hasConflict: true,
1711
+ existingVersion,
1712
+ requestedVersion: dep.version,
1713
+ message: `Major version mismatch: existing ${existingVersion} vs requested ${dep.version}`
1714
+ };
1715
+ }
1716
+ if (!this.versionsCompatible(existingVersion, dep.version)) {
1717
+ return {
1718
+ hasConflict: true,
1719
+ existingVersion,
1720
+ requestedVersion: dep.version,
1721
+ message: `Incompatible version ranges: existing ${existingVersion} vs requested ${dep.version}`
1722
+ };
1723
+ }
1724
+ return { hasConflict: false };
1725
+ }
1726
+ /** Add or update the npm dependency in package.json. */
1727
+ async add(dep) {
1728
+ const packageJsonPath = path3.join(this.cwd, "package.json");
1729
+ if (!fs.existsSync(packageJsonPath)) {
1730
+ throw new Error(`package.json not found at ${this.cwd}`);
1731
+ }
1732
+ const pkgJson = await PackageJson.load(this.cwd);
1733
+ const rawDeps = pkgJson.content[this.dependencyKey];
1734
+ const deps = rawDeps ?? {};
1735
+ const existingVersion = deps[dep.name];
1736
+ const isUpdate = existingVersion !== void 0;
1737
+ const update = {
1738
+ [this.dependencyKey]: {
1739
+ ...deps,
1740
+ [dep.name]: dep.version
1741
+ }
1742
+ };
1743
+ pkgJson.update(update);
1744
+ await pkgJson.save();
1745
+ const action = isUpdate ? "update" : "add";
1746
+ const message = isUpdate ? `Updated ${dep.name} from ${existingVersion} to ${dep.version} in ${this.dependencyLabel}` : `Added ${dep.name}@${dep.version} to ${this.dependencyLabel}`;
1747
+ if (!this.quiet) {
1748
+ this.context.ux.log(`\u2713 ${message}`);
1749
+ }
1750
+ return { action, message };
1751
+ }
1752
+ /** Run the package manager install command in the working directory. */
1753
+ install(_deps) {
1754
+ const packageManager = _detectPackageManager(this.cwd);
1755
+ if (!this.quiet) {
1756
+ this.context.ux.log(`Running ${packageManager} install...`);
1757
+ }
1758
+ try {
1759
+ execSync2(`${packageManager} install`, {
1760
+ cwd: this.cwd,
1761
+ stdio: this.quiet ? "pipe" : "inherit"
1762
+ });
1763
+ } catch (error) {
1764
+ const baseMessage = `Failed to run ${packageManager} install`;
1765
+ if (error instanceof Error) {
1766
+ return Promise.reject(new Error(`${baseMessage}: ${error.message}`));
1767
+ }
1768
+ return Promise.reject(new Error(`${baseMessage}: ${String(error)}`));
1769
+ }
1770
+ return Promise.resolve();
1771
+ }
1772
+ versionsCompatible(existing, requested) {
1773
+ if (existing.startsWith("file:") || requested.startsWith("file:") || existing.startsWith("workspace:") || requested.startsWith("workspace:")) {
1774
+ return existing === requested;
1775
+ }
1776
+ if (!semver.validRange(existing) || !semver.validRange(requested)) {
1777
+ return existing === requested;
1778
+ }
1779
+ return semver.intersects(existing, requested);
1780
+ }
1781
+ extractMajorVersion(version) {
1782
+ if (version.startsWith("file:") || version.startsWith("workspace:")) {
1783
+ return null;
1784
+ }
1785
+ const coerced = semver.coerce(version);
1786
+ if (coerced) {
1787
+ return coerced.major;
1788
+ }
1789
+ return null;
1790
+ }
1791
+ };
1792
+ var _StripeCliPluginHandler = class {
1793
+ stripeConfigDir;
1794
+ quiet;
1795
+ context;
1796
+ constructor(options) {
1797
+ this.stripeConfigDir = options.stripeConfigDir;
1798
+ this.quiet = options.quiet;
1799
+ this.context = options.context ?? _createCliContext();
1800
+ }
1801
+ /** Check whether the Stripe CLI plugin is installed and meets the minimum version. */
1802
+ check(dep) {
1803
+ const pluginsTomlPath = path3.join(this.stripeConfigDir, "plugins.toml");
1804
+ if (!fs.existsSync(pluginsTomlPath)) {
1805
+ return Promise.resolve({
1806
+ satisfied: false,
1807
+ message: `Stripe CLI plugin '${dep.name}' is not installed (plugins.toml not found)`
1808
+ });
1809
+ }
1810
+ const pluginsContent = fs.readFileSync(pluginsTomlPath, "utf-8");
1811
+ const installedPlugin = this.findPluginInToml(pluginsContent, dep.name);
1812
+ if (!installedPlugin) {
1813
+ return Promise.resolve({
1814
+ satisfied: false,
1815
+ message: `Stripe CLI plugin '${dep.name}' is not installed`
1816
+ });
1817
+ }
1818
+ if (dep.minVersion && installedPlugin.version) {
1819
+ if (!this.isVersionSatisfied(installedPlugin.version, dep.minVersion)) {
1820
+ return Promise.resolve({
1821
+ satisfied: false,
1822
+ currentVersion: installedPlugin.version,
1823
+ message: `Stripe CLI plugin '${dep.name}' version ${installedPlugin.version} is below minimum ${dep.minVersion}`
1824
+ });
1825
+ }
1826
+ }
1827
+ const result = {
1828
+ satisfied: true,
1829
+ message: `Stripe CLI plugin '${dep.name}' is installed${installedPlugin.version ? ` (version ${installedPlugin.version})` : ""}`
1830
+ };
1831
+ if (installedPlugin.version) {
1832
+ result.currentVersion = installedPlugin.version;
1833
+ }
1834
+ return Promise.resolve(result);
1835
+ }
1836
+ /** Check whether the installed plugin version conflicts with the requested minimum. */
1837
+ async checkConflict(dep) {
1838
+ const checkResult = await this.check(dep);
1839
+ if (checkResult.satisfied) {
1840
+ return { hasConflict: false };
1841
+ }
1842
+ if (checkResult.currentVersion && dep.minVersion) {
1843
+ return {
1844
+ hasConflict: true,
1845
+ existingVersion: checkResult.currentVersion,
1846
+ requestedVersion: dep.minVersion,
1847
+ message: `Installed version ${checkResult.currentVersion} is below minimum ${dep.minVersion}`
1848
+ };
1849
+ }
1850
+ return { hasConflict: false };
1851
+ }
1852
+ /** Stage a Stripe CLI plugin for installation; the actual install happens in `install`. */
1853
+ async add(dep) {
1854
+ const checkResult = await this.check(dep);
1855
+ const isUpdate = checkResult.currentVersion !== void 0;
1856
+ const action = isUpdate ? "update" : "add";
1857
+ const message = isUpdate ? `Will update Stripe CLI plugin '${dep.name}'` : `Will install Stripe CLI plugin '${dep.name}'`;
1858
+ return { action, message };
1859
+ }
1860
+ /** Install Stripe CLI plugins using `stripe plugin install`. */
1861
+ async install(deps) {
1862
+ for (const dep of deps) {
1863
+ const checkResult = await this.check(dep);
1864
+ const isUpdate = checkResult.currentVersion !== void 0;
1865
+ try {
1866
+ execSync2(`stripe plugin install ${dep.name}`, {
1867
+ stdio: this.quiet ? "pipe" : "inherit"
1868
+ });
1869
+ const message = isUpdate ? `Updated Stripe CLI plugin '${dep.name}'` : `Installed Stripe CLI plugin '${dep.name}'`;
1870
+ if (!this.quiet) {
1871
+ this.context.ux.log(`\u2713 ${message}`);
1872
+ }
1873
+ } catch (error) {
1874
+ const baseMessage = `Failed to install Stripe CLI plugin '${dep.name}'`;
1875
+ if (error instanceof Error) {
1876
+ throw new Error(`${baseMessage}: ${error.message}`);
1877
+ }
1878
+ throw new Error(`${baseMessage}: ${String(error)}`);
1879
+ }
1880
+ }
1881
+ }
1882
+ findPluginInToml(content, pluginName) {
1883
+ try {
1884
+ const parsed = parseToml(content);
1885
+ const plugins = parsed.Plugin;
1886
+ if (!plugins || !Array.isArray(plugins)) {
1887
+ return null;
1888
+ }
1889
+ const plugin = plugins.find((p) => p.Shortname === pluginName);
1890
+ if (!plugin) {
1891
+ return null;
1892
+ }
1893
+ if (plugin.Release && Array.isArray(plugin.Release) && plugin.Release.length > 0) {
1894
+ const currentArch = os.arch();
1895
+ const currentOS = os.platform();
1896
+ const normalizedArch = currentArch === "x64" ? "amd64" : currentArch;
1897
+ const normalizedOS = currentOS === "win32" ? "windows" : currentOS;
1898
+ const platformReleases = plugin.Release.filter(
1899
+ (r) => r.Arch === normalizedArch && r.OS === normalizedOS
1900
+ );
1901
+ if (platformReleases.length === 0) {
1902
+ return null;
1903
+ }
1904
+ const localBuildRelease = platformReleases.find(
1905
+ (r) => r.Version === "local.build.dev"
1906
+ );
1907
+ if (localBuildRelease) {
1908
+ return { version: "local.build.dev" };
1909
+ }
1910
+ const versions = platformReleases.map((r) => r.Version).filter((v) => v !== void 0);
1911
+ if (versions.length === 0) {
1912
+ return null;
1913
+ }
1914
+ const sortedVersions = versions.map((v) => ({ original: v, parsed: semver.coerce(v) })).filter(
1915
+ (v) => v.parsed !== null
1916
+ ).sort((a, b) => semver.rcompare(a.parsed, b.parsed));
1917
+ if (sortedVersions.length === 0) {
1918
+ return { version: versions[0] };
1919
+ }
1920
+ return { version: sortedVersions[0]?.original };
1921
+ }
1922
+ return { version: plugin.Version };
1923
+ } catch {
1924
+ return null;
1925
+ }
1926
+ }
1927
+ /**
1928
+ * Check if installed version satisfies the required minimum version.
1929
+ *
1930
+ * Permissive policy: Non-semver versions (e.g., "local.build.dev", "dev", "canary-abc123")
1931
+ * always satisfy version requirements. This avoids forcing upgrades during local development
1932
+ * when developers are using locally built plugins.
1933
+ *
1934
+ * For valid semver versions, uses the semver library for proper semantic version comparison.
1935
+ *
1936
+ * @param installed - The installed version string
1937
+ * @param required - The required minimum version string
1938
+ * @returns true if installed version satisfies requirement
1939
+ */
1940
+ isVersionSatisfied(installed, required) {
1941
+ const installedSemver = semver.coerce(installed);
1942
+ const requiredSemver = semver.coerce(required);
1943
+ if (!installedSemver) {
1944
+ return true;
1945
+ }
1946
+ if (!requiredSemver) {
1947
+ return true;
1948
+ }
1949
+ return semver.gte(installedSemver, requiredSemver);
1950
+ }
1951
+ };
1952
+ function dependencyKey(dep) {
1953
+ return `${dep.type}:${dep.name}`;
1954
+ }
1955
+ var _DependencyManager = class {
1956
+ cwd;
1957
+ stripeConfigDir;
1958
+ quiet;
1959
+ context;
1960
+ npmHandler;
1961
+ devNpmHandler;
1962
+ stripeCliPluginHandler;
1963
+ /** Internal state: pending changes indexed by dependency key */
1964
+ pendingChanges = /* @__PURE__ */ new Map();
1965
+ /** Whether commit() has been called */
1966
+ committed = false;
1967
+ constructor(options = {}) {
1968
+ this.cwd = options.cwd ?? process.cwd();
1969
+ this.stripeConfigDir = options.stripeConfigDir ?? path3.join(os.homedir(), ".config", "stripe");
1970
+ this.quiet = options.quiet ?? false;
1971
+ this.context = options.context ?? _createCliContext();
1972
+ this.npmHandler = new _NpmDependencyHandler({
1973
+ cwd: this.cwd,
1974
+ quiet: this.quiet,
1975
+ devDependencies: false,
1976
+ context: this.context
1977
+ });
1978
+ this.devNpmHandler = new _NpmDependencyHandler({
1979
+ cwd: this.cwd,
1980
+ quiet: this.quiet,
1981
+ devDependencies: true,
1982
+ context: this.context
1983
+ });
1984
+ this.stripeCliPluginHandler = new _StripeCliPluginHandler({
1985
+ stripeConfigDir: this.stripeConfigDir,
1986
+ quiet: this.quiet,
1987
+ context: this.context
1988
+ });
1989
+ }
1990
+ /**
1991
+ * Analyze dependencies and accumulate changes.
1992
+ * Can be called multiple times before commit().
1993
+ * Returns the changes for this specific call.
1994
+ */
1995
+ async ensureDependencies(input) {
1996
+ if (this.committed) {
1997
+ throw new Error("DependencyManager has already been committed");
1998
+ }
1999
+ const { required, optional = [] } = input;
2000
+ const changes = [];
2001
+ for (const dep of [...required, ...optional]) {
2002
+ const change = await this.analyzeDependency(dep);
2003
+ changes.push(change);
2004
+ this.pendingChanges.set(dependencyKey(dep), change);
2005
+ }
2006
+ return changes;
2007
+ }
2008
+ /**
2009
+ * Resolve a conflict by marking it for force install.
2010
+ * Throws if the dependency is not in conflict state.
2011
+ */
2012
+ resolveConflict(dep) {
2013
+ if (this.committed) {
2014
+ throw new Error("DependencyManager has already been committed");
2015
+ }
2016
+ const key = dependencyKey(dep);
2017
+ const change = this.pendingChanges.get(key);
2018
+ if (!change) {
2019
+ throw new Error(`Dependency '${dep.name}' not found in pending changes`);
2020
+ }
2021
+ if (change.action !== "conflict") {
2022
+ throw new Error(
2023
+ `Dependency '${dep.name}' is not in conflict (action: ${change.action})`
2024
+ );
2025
+ }
2026
+ change.conflictResolved = true;
2027
+ }
2028
+ /**
2029
+ * Get all pending changes (accumulated across all ensureDependencies calls).
2030
+ */
2031
+ getPendingChanges() {
2032
+ return Array.from(this.pendingChanges.values());
2033
+ }
2034
+ /**
2035
+ * Commit all accumulated changes.
2036
+ * - For npm deps: updates package.json, optionally runs package manager install
2037
+ * - For Stripe CLI deps: always installs (no separate add step)
2038
+ *
2039
+ * @param options - Commit options. `options.runInstall`: if true, run package manager install for npm deps (default: true)
2040
+ * @returns Summary of changes made
2041
+ * @throws If called more than once
2042
+ */
2043
+ async commit(options = {}) {
2044
+ if (this.committed) {
2045
+ throw new Error("DependencyManager has already been committed");
2046
+ }
2047
+ this.committed = true;
2048
+ const { runInstall = true } = options;
2049
+ let added = 0;
2050
+ let updated = 0;
2051
+ const npmDeps = [];
2052
+ const stripeCliDeps = [];
2053
+ for (const change of this.pendingChanges.values()) {
2054
+ if (change.action === "already-satisfied") {
2055
+ continue;
2056
+ }
2057
+ if (change.action === "conflict" && !change.conflictResolved) {
2058
+ continue;
2059
+ }
2060
+ const dep = change.dependency;
2061
+ if (dep.type === "npm" || dep.type === "dev-npm") {
2062
+ npmDeps.push(dep);
2063
+ } else {
2064
+ stripeCliDeps.push(dep);
2065
+ }
2066
+ }
2067
+ for (const dep of npmDeps) {
2068
+ const handler = dep.type === "npm" ? this.npmHandler : this.devNpmHandler;
2069
+ const result = await handler.add(dep);
2070
+ if (result.action === "add") {
2071
+ added++;
2072
+ } else {
2073
+ updated++;
2074
+ }
2075
+ }
2076
+ if (runInstall && npmDeps.length > 0) {
2077
+ await this.npmHandler.install(npmDeps);
2078
+ }
2079
+ if (stripeCliDeps.length > 0) {
2080
+ await this.stripeCliPluginHandler.install(stripeCliDeps);
2081
+ for (const dep of stripeCliDeps) {
2082
+ const change = this.pendingChanges.get(dependencyKey(dep));
2083
+ if (change?.action === "add" || change?.action === "conflict" && !change.previousVersion) {
2084
+ added++;
2085
+ } else {
2086
+ updated++;
2087
+ }
2088
+ }
2089
+ }
2090
+ return { added, updated };
2091
+ }
2092
+ async analyzeDependency(dep) {
2093
+ const handler = this.getHandler(dep);
2094
+ const checkResult = await handler.check(dep);
2095
+ if (checkResult.satisfied) {
2096
+ return {
2097
+ dependency: dep,
2098
+ action: "already-satisfied",
2099
+ message: checkResult.message
2100
+ };
2101
+ }
2102
+ const conflictResult = await handler.checkConflict(dep);
2103
+ if (conflictResult.hasConflict) {
2104
+ const result2 = {
2105
+ dependency: dep,
2106
+ action: "conflict",
2107
+ message: conflictResult.message ?? "Dependency conflict detected",
2108
+ conflict: conflictResult
2109
+ };
2110
+ if (conflictResult.existingVersion) {
2111
+ result2.previousVersion = conflictResult.existingVersion;
2112
+ }
2113
+ return result2;
2114
+ }
2115
+ const isUpdate = checkResult.currentVersion !== void 0;
2116
+ const result = {
2117
+ dependency: dep,
2118
+ action: isUpdate ? "update" : "add",
2119
+ message: isUpdate ? `Will update ${dep.name} from ${String(checkResult.currentVersion)}` : `Will add ${dep.name}`
2120
+ };
2121
+ if (checkResult.currentVersion) {
2122
+ result.previousVersion = checkResult.currentVersion;
2123
+ }
2124
+ return result;
2125
+ }
2126
+ getHandler(dep) {
2127
+ switch (dep.type) {
2128
+ case "npm":
2129
+ return this.npmHandler;
2130
+ case "dev-npm":
2131
+ return this.devNpmHandler;
2132
+ case "stripe-cli-plugin":
2133
+ return this.stripeCliPluginHandler;
2134
+ }
2135
+ }
2136
+ };
2137
+
2138
+ // src/templates/extensions/base.ts
2139
+ import { _workspaceVersion } from "@stripe/extensibility-tool-utils";
2140
+ var SDK_PACKAGE_NAME = "@stripe/extensibility-sdk";
2141
+ var LANGUAGE_SERVER_PACKAGE_NAME = "@stripe/extensibility-language-server";
2142
+ var LANGUAGE_SERVER_PACKAGE_VERSION = "^0.2.0";
2143
+ function _createExtensionEslintConfigFile(params, context) {
2144
+ const { id, extensionInterfaceId } = params;
2145
+ const { fs: fs2 } = context;
2146
+ return {
2147
+ path: `extensions/${id}/eslint.config.mts`,
2148
+ content: fs2.mustache(
2149
+ { extensionInterfaceId },
2150
+ "common",
2151
+ "eslint.config.mts.mustache"
2152
+ ),
2153
+ precious: true
2154
+ };
2155
+ }
2156
+ function _createBaseOutput(params, context) {
2157
+ const { id } = params;
2158
+ const { fs: fs2 } = context;
2159
+ return {
2160
+ files: [
2161
+ {
2162
+ path: `extensions/${id}/package.json`,
2163
+ content: fs2.mustache(params, "common", "package.json.mustache")
2164
+ },
2165
+ {
2166
+ ..._createExtensionEslintConfigFile(params, context)
2167
+ },
2168
+ {
2169
+ path: `extensions/${id}/tsconfig.build.json`,
2170
+ content: fs2.mustache(params, "common", "tsconfig.build.json.mustache")
2171
+ },
2172
+ {
2173
+ path: `extensions/${id}/tsconfig.json`,
2174
+ content: fs2.mustache(params, "common", "tsconfig.json.mustache")
2175
+ },
2176
+ {
2177
+ path: `extensions/${id}/.prettierignore`,
2178
+ content: fs2.textFile("common", ".prettierignore")
2179
+ }
2180
+ ],
2181
+ methods: {},
2182
+ dependencies: {
2183
+ // Exact pin (no caret) — the SDK is tightly coupled to dev-tools and
2184
+ // must match the version that generated the extension scaffolding.
2185
+ runtime: [_npmDep(SDK_PACKAGE_NAME, _workspaceVersion(SDK_PACKAGE_NAME))],
2186
+ dev: [_devNpmDep(LANGUAGE_SERVER_PACKAGE_NAME, LANGUAGE_SERVER_PACKAGE_VERSION)]
2187
+ },
2188
+ postGenerationHooks: [
2189
+ {
2190
+ script: "build",
2191
+ description: "Build extension"
2192
+ },
2193
+ {
2194
+ exec: "prettier --write .",
2195
+ description: "Format generated files"
2196
+ }
2197
+ ]
2198
+ };
2199
+ }
2200
+
2201
+ // src/templates/extensions/core.workflows.custom_action.ts
2202
+ var EXTENSION_INTERFACE_ID = "core.workflows.custom_action";
2203
+ var customActionTemplate = {
2204
+ methods: {
2205
+ execute: { implementation_types: ["script", "remote-function"] },
2206
+ get_form_state: { implementation_types: ["script", "remote-function"] }
2207
+ },
2208
+ description: "Custom actions let your app define actions that users can add to their automated workflows. When a workflow triggers a custom action, Stripe calls your app to execute it.",
2209
+ generate: (params, context) => {
2210
+ const { id } = params;
2211
+ const { fs: fs2 } = context;
2212
+ const base = _createBaseOutput(
2213
+ {
2214
+ ...params,
2215
+ extensionInterfaceId: EXTENSION_INTERFACE_ID,
2216
+ executionProfile: "egress"
2217
+ },
2218
+ context
2219
+ );
2220
+ return {
2221
+ ...base,
2222
+ files: [
2223
+ {
2224
+ path: `extensions/${id}/src/index.ts`,
2225
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "index.ts"),
2226
+ precious: true
2227
+ },
2228
+ {
2229
+ path: `extensions/${id}/src/custom_input.schema.json`,
2230
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "custom_input.schema.json"),
2231
+ precious: true
2232
+ },
2233
+ {
2234
+ path: `extensions/${id}/src/index.test.ts`,
2235
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "index.test.ts"),
2236
+ precious: true
2237
+ },
2238
+ ...base.files
2239
+ ],
2240
+ methods: {
2241
+ execute: {
2242
+ implementation_type: "script",
2243
+ custom_input: {
2244
+ input_schema: {
2245
+ type: "json_schema",
2246
+ content: `extensions/${id}/src/custom_input.schema.json`
2247
+ }
2248
+ }
2249
+ },
2250
+ get_form_state: {
2251
+ implementation_type: "script"
2252
+ }
2253
+ }
2254
+ };
2255
+ }
2256
+ };
2257
+ var core_workflows_custom_action_default = {
2258
+ [EXTENSION_INTERFACE_ID]: customActionTemplate
2259
+ };
2260
+
2261
+ // src/templates/extensions/extend.objects.custom_objects.ts
2262
+ var EXTENSION_INTERFACE_ID2 = "extend.objects.custom_objects";
2263
+ var customObjectsTemplate = {
2264
+ methods: {
2265
+ execute_method: { implementation_types: ["script"] }
2266
+ },
2267
+ description: "Methods extension for custom object actions. Generated at build time \u2014 the transformed custom object class becomes the entry point.",
2268
+ hidden: true,
2269
+ generate: (params, context) => {
2270
+ const base = _createBaseOutput(
2271
+ {
2272
+ ...params,
2273
+ extensionInterfaceId: EXTENSION_INTERFACE_ID2,
2274
+ executionProfile: "egress"
2275
+ },
2276
+ context
2277
+ );
2278
+ return {
2279
+ ...base,
2280
+ methods: {
2281
+ execute_method: {
2282
+ implementation_type: "script"
2283
+ }
2284
+ }
2285
+ };
2286
+ }
2287
+ };
2288
+ var extend_objects_custom_objects_default = {
2289
+ [EXTENSION_INTERFACE_ID2]: customObjectsTemplate
2290
+ };
2291
+
2292
+ // src/templates/extensions/extend.workflows.custom_action.ts
2293
+ var EXTENSION_INTERFACE_ID3 = "extend.workflows.custom_action";
2294
+ var extendCustomActionTemplate = {
2295
+ methods: {
2296
+ execute: { implementation_types: ["script", "remote-function"] },
2297
+ get_form_state: { implementation_types: ["script", "remote-function"] }
2298
+ },
2299
+ description: "Custom actions let your app define actions that users can add to their automated workflows. When a workflow triggers a custom action, Stripe calls your app to execute it.",
2300
+ generate: (params, context) => {
2301
+ const { id } = params;
2302
+ const { fs: fs2 } = context;
2303
+ const base = _createBaseOutput(
2304
+ {
2305
+ ...params,
2306
+ extensionInterfaceId: EXTENSION_INTERFACE_ID3,
2307
+ executionProfile: "egress"
2308
+ },
2309
+ context
2310
+ );
2311
+ return {
2312
+ ...base,
2313
+ files: [
2314
+ {
2315
+ path: `extensions/${id}/src/index.ts`,
2316
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "index.ts"),
2317
+ precious: true
2318
+ },
2319
+ {
2320
+ path: `extensions/${id}/src/custom_input.schema.json`,
2321
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "custom_input.schema.json"),
2322
+ precious: true
2323
+ },
2324
+ {
2325
+ path: `extensions/${id}/src/index.test.ts`,
2326
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "index.test.ts"),
2327
+ precious: true
2328
+ },
2329
+ ...base.files
2330
+ ],
2331
+ methods: {
2332
+ execute: {
2333
+ implementation_type: "script",
2334
+ custom_input: {
2335
+ input_schema: {
2336
+ type: "json_schema",
2337
+ content: `extensions/${id}/src/custom_input.schema.json`
2338
+ }
2339
+ }
2340
+ },
2341
+ get_form_state: {
2342
+ implementation_type: "script"
2343
+ }
2344
+ }
2345
+ };
2346
+ }
2347
+ };
2348
+ var extend_workflows_custom_action_default = {
2349
+ [EXTENSION_INTERFACE_ID3]: extendCustomActionTemplate
2350
+ };
2351
+
2352
+ // src/templates/extensions/billing.customer_balance_application.ts
2353
+ var EXTENSION_INTERFACE_ID4 = "billing.customer_balance_application";
2354
+ var customerBalanceApplicationTemplate = {
2355
+ methods: {
2356
+ compute_applied_customer_balance: { implementation_types: ["script"] }
2357
+ },
2358
+ description: "Implement custom logic to control when and how much customer balance is applied to subscription invoices using scripts.",
2359
+ generate: (params, context) => {
2360
+ const { id } = params;
2361
+ const { fs: fs2 } = context;
2362
+ const base = _createBaseOutput(
2363
+ {
2364
+ ...params,
2365
+ extensionInterfaceId: EXTENSION_INTERFACE_ID4,
2366
+ executionProfile: "restricted"
2367
+ },
2368
+ context
2369
+ );
2370
+ return {
2371
+ ...base,
2372
+ files: [
2373
+ {
2374
+ path: `extensions/${id}/src/index.ts`,
2375
+ content: fs2.textFile(EXTENSION_INTERFACE_ID4, "index.ts"),
2376
+ precious: true
2377
+ },
2378
+ {
2379
+ path: `extensions/${id}/src/index.test.ts`,
2380
+ content: fs2.textFile(EXTENSION_INTERFACE_ID4, "index.test.ts"),
2381
+ precious: true
2382
+ },
2383
+ ...base.files
2384
+ ],
2385
+ methods: {
2386
+ compute_applied_customer_balance: {
2387
+ implementation_type: "script"
2388
+ }
2389
+ }
2390
+ };
2391
+ }
2392
+ };
2393
+ var billing_customer_balance_application_default = {
2394
+ [EXTENSION_INTERFACE_ID4]: customerBalanceApplicationTemplate
2395
+ };
2396
+
2397
+ // src/templates/extensions/billing.bill.discount_calculation.ts
2398
+ var EXTENSION_INTERFACE_ID5 = "billing.bill.discount_calculation";
2399
+ var discountCalculationTemplate = {
2400
+ hidden: true,
2401
+ methods: {
2402
+ compute_discounts: { implementation_types: ["script"] }
2403
+ },
2404
+ description: "Create coupons with custom scripting logic for dynamic discounts based on subscription attributes, customer metadata, and complex business rules.",
2405
+ generate: (params, context) => {
2406
+ const { id } = params;
2407
+ const { fs: fs2 } = context;
2408
+ const base = _createBaseOutput(
2409
+ {
2410
+ ...params,
2411
+ extensionInterfaceId: EXTENSION_INTERFACE_ID5,
2412
+ executionProfile: "restricted"
2413
+ },
2414
+ context
2415
+ );
2416
+ return {
2417
+ ...base,
2418
+ files: [
2419
+ {
2420
+ path: `extensions/${id}/src/index.ts`,
2421
+ content: fs2.textFile(EXTENSION_INTERFACE_ID5, "index.ts"),
2422
+ precious: true
2423
+ },
2424
+ {
2425
+ path: `extensions/${id}/src/index.test.ts`,
2426
+ content: fs2.textFile(EXTENSION_INTERFACE_ID5, "index.test.ts"),
2427
+ precious: true
2428
+ },
2429
+ ...base.files
2430
+ ],
2431
+ methods: {
2432
+ compute_discounts: {
2433
+ implementation_type: "script"
2434
+ }
2435
+ }
2436
+ };
2437
+ }
2438
+ };
2439
+ var billing_bill_discount_calculation_default = {
2440
+ [EXTENSION_INTERFACE_ID5]: discountCalculationTemplate
2441
+ };
2442
+
2443
+ // src/templates/extensions/billing.invoice_collection_setting.ts
2444
+ var EXTENSION_INTERFACE_ID6 = "billing.invoice_collection_setting";
2445
+ var invoiceCollectionSettingTemplate = {
2446
+ hidden: true,
2447
+ methods: {
2448
+ collection_override: { implementation_types: ["script"] }
2449
+ },
2450
+ description: "Use Stripe Scripts to create custom invoice collection logic that controls how your integration handles invoices generated from subscriptions.",
2451
+ generate: (params, context) => {
2452
+ const { id } = params;
2453
+ const { fs: fs2 } = context;
2454
+ const base = _createBaseOutput(
2455
+ {
2456
+ ...params,
2457
+ extensionInterfaceId: EXTENSION_INTERFACE_ID6,
2458
+ executionProfile: "restricted"
2459
+ },
2460
+ context
2461
+ );
2462
+ return {
2463
+ ...base,
2464
+ files: [
2465
+ {
2466
+ path: `extensions/${id}/src/index.ts`,
2467
+ content: fs2.textFile(EXTENSION_INTERFACE_ID6, "index.ts"),
2468
+ precious: true
2469
+ },
2470
+ {
2471
+ path: `extensions/${id}/src/index.test.ts`,
2472
+ content: fs2.textFile(EXTENSION_INTERFACE_ID6, "index.test.ts"),
2473
+ precious: true
2474
+ },
2475
+ ...base.files
2476
+ ],
2477
+ methods: {
2478
+ collection_override: {
2479
+ implementation_type: "script"
2480
+ }
2481
+ }
2482
+ };
2483
+ }
2484
+ };
2485
+ var billing_invoice_collection_setting_default = {
2486
+ [EXTENSION_INTERFACE_ID6]: invoiceCollectionSettingTemplate
2487
+ };
2488
+
2489
+ // src/templates/extensions/billing.prorations.ts
2490
+ var EXTENSION_INTERFACE_ID7 = "billing.prorations";
2491
+ var prorationsTemplate = {
2492
+ methods: {
2493
+ prorate_items: { implementation_types: ["script"] }
2494
+ },
2495
+ description: "Create custom proration logic for subscriptions using scripts to handle upgrades, downgrades, and mid-cycle changes.",
2496
+ generate: (params, context) => {
2497
+ const { id } = params;
2498
+ const { fs: fs2 } = context;
2499
+ const base = _createBaseOutput(
2500
+ {
2501
+ ...params,
2502
+ extensionInterfaceId: EXTENSION_INTERFACE_ID7,
2503
+ executionProfile: "restricted"
2504
+ },
2505
+ context
2506
+ );
2507
+ return {
2508
+ ...base,
2509
+ files: [
2510
+ {
2511
+ path: `extensions/${id}/src/index.ts`,
2512
+ content: fs2.textFile(EXTENSION_INTERFACE_ID7, "index.ts"),
2513
+ precious: true
2514
+ },
2515
+ {
2516
+ path: `extensions/${id}/src/index.test.ts`,
2517
+ content: fs2.textFile(EXTENSION_INTERFACE_ID7, "index.test.ts"),
2518
+ precious: true
2519
+ },
2520
+ ...base.files
2521
+ ],
2522
+ methods: {
2523
+ prorate_items: {
2524
+ implementation_type: "script"
2525
+ }
2526
+ }
2527
+ };
2528
+ }
2529
+ };
2530
+ var billing_prorations_default = {
2531
+ [EXTENSION_INTERFACE_ID7]: prorationsTemplate
2532
+ };
2533
+
2534
+ // src/templates/extensions/billing.recurring_billing_item_handling.ts
2535
+ var EXTENSION_INTERFACE_ID8 = "billing.recurring_billing_item_handling";
2536
+ var template = {
2537
+ methods: {
2538
+ before_item_creation: { implementation_types: ["script"] },
2539
+ filter_items: { implementation_types: ["script"] },
2540
+ group_items: { implementation_types: ["script"] }
2541
+ },
2542
+ description: "Customize how recurring billing items are filtered, grouped, and created during subscription billing runs.",
2543
+ generate: (params, context) => {
2544
+ const { id } = params;
2545
+ const { fs: fs2 } = context;
2546
+ const base = _createBaseOutput(
2547
+ {
2548
+ ...params,
2549
+ extensionInterfaceId: EXTENSION_INTERFACE_ID8,
2550
+ executionProfile: "restricted"
2551
+ },
2552
+ context
2553
+ );
2554
+ return {
2555
+ ...base,
2556
+ files: [
2557
+ {
2558
+ path: `extensions/${id}/src/index.ts`,
2559
+ content: fs2.textFile(EXTENSION_INTERFACE_ID8, "index.ts"),
2560
+ precious: true
2561
+ },
2562
+ {
2563
+ path: `extensions/${id}/src/index.test.ts`,
2564
+ content: fs2.textFile(EXTENSION_INTERFACE_ID8, "index.test.ts"),
2565
+ precious: true
2566
+ },
2567
+ ...base.files
2568
+ ],
2569
+ methods: {
2570
+ before_item_creation: {
2571
+ implementation_type: "script"
2572
+ },
2573
+ filter_items: {
2574
+ implementation_type: "script"
2575
+ },
2576
+ group_items: {
2577
+ implementation_type: "script"
2578
+ }
2579
+ }
2580
+ };
2581
+ }
2582
+ };
2583
+ var billing_recurring_billing_item_handling_default = {
2584
+ [EXTENSION_INTERFACE_ID8]: template
2585
+ };
2586
+
2587
+ // src/templates/extensions/registry.ts
2588
+ var DEFAULT_TEMPLATES = {
2589
+ ...core_workflows_custom_action_default,
2590
+ ...extend_objects_custom_objects_default,
2591
+ ...extend_workflows_custom_action_default,
2592
+ ...billing_customer_balance_application_default,
2593
+ ...billing_bill_discount_calculation_default,
2594
+ ...billing_invoice_collection_setting_default,
2595
+ ...billing_prorations_default,
2596
+ ...billing_recurring_billing_item_handling_default
2597
+ };
2598
+ var registry_default = DEFAULT_TEMPLATES;
2599
+
2600
+ // src/templates/extensions/index.ts
2601
+ var _templateManager = new _ExtensionTemplateManager(
2602
+ registry_default,
2603
+ _fs.scope("extensions")
2604
+ );
2605
+
2606
+ // src/templates/root/index.ts
2607
+ import { _workspaceVersion as _workspaceVersion2 } from "@stripe/extensibility-tool-utils";
2608
+ var EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME = "@stripe/extensibility-eslint-plugin";
2609
+ var EXTENSIBILITY_ESLINT_PLUGIN_VERSION = `^${_workspaceVersion2(EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME)}`;
2610
+ var _rootWorkspaceTemplate = {
2611
+ generate: (params, context) => {
2612
+ const { fs: fs2 } = context;
2613
+ return {
2614
+ files: [
2615
+ {
2616
+ path: "stripe-app.yaml",
2617
+ content: fs2.mustache(params, "stripe-app.yaml.mustache"),
2618
+ precious: true
2619
+ },
2620
+ {
2621
+ path: "package.json",
2622
+ content: fs2.mustache(params, "package.json.mustache")
2623
+ },
2624
+ {
2625
+ path: ".husky/pre-commit",
2626
+ content: fs2.textFile(".husky/pre-commit")
2627
+ },
2628
+ {
2629
+ path: "tsconfig.base.json",
2630
+ content: fs2.textFile("tsconfig.base.json")
2631
+ },
2632
+ {
2633
+ path: "tsconfig.json",
2634
+ content: fs2.textFile("tsconfig.json")
2635
+ },
2636
+ {
2637
+ path: "eslint.config.mts",
2638
+ content: fs2.textFile("eslint.config.mts")
2639
+ },
2640
+ {
2641
+ path: "vitest.config.mts",
2642
+ content: fs2.textFile("vitest.config.mts")
2643
+ },
2644
+ {
2645
+ path: ".gitignore",
2646
+ content: fs2.textFile("_gitignore")
2647
+ },
2648
+ {
2649
+ path: "pnpm-workspace.yaml",
2650
+ content: fs2.textFile("pnpm-workspace.yaml")
2651
+ },
2652
+ {
2653
+ path: ".prettierrc",
2654
+ content: fs2.textFile(".prettierrc")
2655
+ },
2656
+ {
2657
+ path: ".prettierignore",
2658
+ content: fs2.textFile(".prettierignore")
2659
+ },
2660
+ {
2661
+ path: "custom-objects/package.json",
2662
+ content: fs2.textFile("custom-objects/package.json"),
2663
+ precious: true
2664
+ },
2665
+ {
2666
+ path: "custom-objects/tsconfig.json",
2667
+ content: fs2.textFile("custom-objects/tsconfig.json"),
2668
+ precious: true
2669
+ },
2670
+ {
2671
+ path: "ui/package.json",
2672
+ content: fs2.textFile("ui/package.json"),
2673
+ precious: true
2674
+ },
2675
+ {
2676
+ path: "tools/test.mts",
2677
+ content: fs2.textFile("tools/test.mts")
2678
+ },
2679
+ {
2680
+ // temporarily add dummy JSON manifest until stripe apps plugin is fixed
2681
+ path: "stripe-app.json",
2682
+ content: "{}\n"
2683
+ }
2684
+ ],
2685
+ dependencies: {
2686
+ dev: [
2687
+ _devNpmDep("@eslint/js", "^9.0.0"),
2688
+ _devNpmDep(
2689
+ EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME,
2690
+ EXTENSIBILITY_ESLINT_PLUGIN_VERSION
2691
+ ),
2692
+ _devNpmDep(LANGUAGE_SERVER_PACKAGE_NAME, LANGUAGE_SERVER_PACKAGE_VERSION),
2693
+ _devNpmDep("@types/node", "^20.19.0"),
2694
+ _devNpmDep(
2695
+ "@stripe/extensibility-dev-tools",
2696
+ `^${_workspaceVersion2("@stripe/extensibility-dev-tools")}`
2697
+ ),
2698
+ _devNpmDep("concurrently", "^9.2.1"),
2699
+ _devNpmDep("eslint", "^9.0.0"),
2700
+ _devNpmDep("eslint-config-prettier", "^10.1.8"),
2701
+ _devNpmDep("eslint-plugin-workspaces", "^0.12.1"),
2702
+ _devNpmDep("globals", "^17.4.0"),
2703
+ _devNpmDep("husky", "^9.1.7"),
2704
+ _devNpmDep("jiti", "^2.6.1"),
2705
+ _devNpmDep("lint-staged", "^16.2.7"),
2706
+ _devNpmDep("chokidar-cli", "^3.0.0"),
2707
+ _devNpmDep("prettier", "^3.8.1"),
2708
+ _devNpmDep("ts-node", "^10.9.2"),
2709
+ _devNpmDep("tsx", "^4.21.0"),
2710
+ _devNpmDep("typescript", "^5.9.3"),
2711
+ _devNpmDep("typescript-eslint", "^8.54.0"),
2712
+ _devNpmDep("vitest", "^3.0.0")
2713
+ ]
2714
+ },
2715
+ postGenerationHooks: [
2716
+ {
2717
+ exec: "prettier --write .",
2718
+ description: "Format generated files"
2719
+ }
2720
+ ]
2721
+ };
2722
+ }
2723
+ };
2724
+ var _rootTemplateManager = new _SingleTemplateManager(_rootWorkspaceTemplate, _fs.scope("root"));
2725
+
2726
+ // src/manifest/stripe-app-manifest.ts
2727
+ import { _toSnakeCase } from "@stripe/extensibility-tool-utils";
2728
+
2729
+ // src/manifest/manifest-v1.ts
2730
+ import { readFileSync, writeFileSync, existsSync } from "fs";
2731
+ function formatCustomObjectEntry(entry) {
2732
+ return `${entry.filePath}#${entry.className}`;
2733
+ }
2734
+ function parseCustomObjectEntry(entryString) {
2735
+ const parts = entryString.split("#");
2736
+ if (parts.length !== 2) {
2737
+ throw new Error(
2738
+ `Invalid object entry format: ${entryString}. Expected format: "path/to/file.d.ts#ClassName"`
2739
+ );
2740
+ }
2741
+ const [filePath, className] = parts;
2742
+ if (!filePath || !className) {
2743
+ throw new Error(
2744
+ `Invalid object entry format: ${entryString}. Expected format: "path/to/file.d.ts#ClassName"`
2745
+ );
2746
+ }
2747
+ return { filePath, className };
2748
+ }
2749
+ var _ManifestV1 = class __ManifestV1 {
2750
+ constructor(filePath, data) {
2751
+ this.filePath = filePath;
2752
+ this.data = data;
2753
+ }
2754
+ /**
2755
+ * Load stripe-app.json from disk
2756
+ * @param filePath - Path to stripe-app.json
2757
+ * @throws Error if file is invalid or cannot be read
2758
+ */
2759
+ static load(filePath) {
2760
+ if (!existsSync(filePath)) {
2761
+ throw new Error(`Manifest file not found: ${filePath}`);
2762
+ }
2763
+ const content = readFileSync(filePath, "utf-8");
2764
+ const data = JSON.parse(content);
2765
+ if (!data.id) {
2766
+ throw new Error('Manifest must contain "id" field');
2767
+ }
2768
+ return new __ManifestV1(filePath, data);
2769
+ }
2770
+ /**
2771
+ * Get the app ID from the manifest
2772
+ */
2773
+ getAppId() {
2774
+ return this.data.id;
2775
+ }
2776
+ /**
2777
+ * Get the app name from the manifest
2778
+ */
2779
+ getAppName() {
2780
+ return this.data.name;
2781
+ }
2782
+ /**
2783
+ * Get all custom objects as structured entries
2784
+ */
2785
+ getCustomObjects() {
2786
+ const entries = [];
2787
+ if (this.data.exported_custom_objects) {
2788
+ for (const entry of this.data.exported_custom_objects) {
2789
+ entries.push(parseCustomObjectEntry(entry));
2790
+ }
2791
+ }
2792
+ return entries;
2793
+ }
2794
+ /**
2795
+ * Check if a custom object entry exists in the manifest
2796
+ */
2797
+ hasCustomObject(entry) {
2798
+ const objects = this.getCustomObjects();
2799
+ return objects.some(
2800
+ (existing) => existing.filePath === entry.filePath && existing.className === entry.className
2801
+ );
2802
+ }
2803
+ /**
2804
+ * Add a custom object entry to the manifest
2805
+ * Does nothing if entry already exists
2806
+ * @returns true if entry was added, false if it already existed
2807
+ */
2808
+ addCustomObject(entry) {
2809
+ if (this.hasCustomObject(entry)) {
2810
+ return false;
2811
+ }
2812
+ const entryString = formatCustomObjectEntry(entry);
2813
+ this.data.exported_custom_objects ??= [];
2814
+ this.data.exported_custom_objects.push(entryString);
2815
+ return true;
2816
+ }
2817
+ /**
2818
+ * Remove a custom object entry from the manifest
2819
+ * @returns true if entry was removed, false if it didn't exist
2820
+ */
2821
+ removeCustomObject(entry) {
2822
+ if (!this.data.exported_custom_objects) {
2823
+ return false;
2824
+ }
2825
+ const entryString = formatCustomObjectEntry(entry);
2826
+ const originalLength = this.data.exported_custom_objects.length;
2827
+ this.data.exported_custom_objects = this.data.exported_custom_objects.filter(
2828
+ (e) => e !== entryString
2829
+ );
2830
+ if (this.data.exported_custom_objects.length === 0) {
2831
+ delete this.data.exported_custom_objects;
2832
+ }
2833
+ return this.data.exported_custom_objects?.length !== originalLength;
2834
+ }
2835
+ /**
2836
+ * Get the raw manifest data (for reading other fields)
2837
+ */
2838
+ getRawData() {
2839
+ return this.data;
2840
+ }
2841
+ /**
2842
+ * Save changes back to disk
2843
+ */
2844
+ save() {
2845
+ writeFileSync(this.filePath, JSON.stringify(this.data, null, 2) + "\n");
2846
+ }
2847
+ };
2848
+
2849
+ // src/manifest/manifest-v2.ts
2850
+ import { readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
2851
+ import * as yaml from "yaml";
2852
+ import { _toPascalCase } from "@stripe/extensibility-tool-utils";
2853
+ function isNonEmptyString(value) {
2854
+ return typeof value === "string" && value.trim().length > 0;
2855
+ }
2856
+ function isYamlObject(value) {
2857
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2858
+ }
2859
+ function validateManifestV2Data(data) {
2860
+ if (!isNonEmptyString(data.id)) {
2861
+ throw new Error('Manifest must contain non-empty "id" field');
2862
+ }
2863
+ if (!isNonEmptyString(data.name)) {
2864
+ throw new Error('Manifest must contain non-empty "name" field');
2865
+ }
2866
+ if (!isNonEmptyString(data.version)) {
2867
+ throw new Error('Manifest must contain non-empty "version" field');
2868
+ }
2869
+ if ("extensions" in data && !Array.isArray(data.extensions)) {
2870
+ throw new Error('Manifest field "extensions" must be an array when provided');
2871
+ }
2872
+ if ("custom_object_definitions" in data && !isYamlObject(data.custom_object_definitions)) {
2873
+ throw new Error(
2874
+ 'Manifest field "custom_object_definitions" must be an object with a "definitions" array'
2875
+ );
2876
+ }
2877
+ const coBlock = data.custom_object_definitions;
2878
+ const definitions = isYamlObject(coBlock) ? coBlock.definitions : void 0;
2879
+ if (!definitions) {
2880
+ return;
2881
+ }
2882
+ if (!Array.isArray(definitions)) {
2883
+ throw new Error(
2884
+ 'Manifest field "custom_object_definitions.definitions" must be an array'
2885
+ );
2886
+ }
2887
+ for (let i = 0; i < definitions.length; i++) {
2888
+ const def = definitions[i];
2889
+ const prefix = `custom_object_definitions.definitions[${String(i)}]`;
2890
+ if (!isYamlObject(def) || !isNonEmptyString(def.id)) {
2891
+ throw new Error(
2892
+ `${prefix}: missing or invalid "id" field. Got: ${JSON.stringify(def)}`
2893
+ );
2894
+ }
2895
+ if (!isYamlObject(def.specification)) {
2896
+ throw new Error(
2897
+ `${prefix}: missing or invalid "specification" field. Expected: { type: "typescript", content: "path/to/file.ts" }. Got: ${JSON.stringify(def)}`
2898
+ );
2899
+ }
2900
+ if (!isNonEmptyString(def.specification.type)) {
2901
+ throw new Error(
2902
+ `${prefix}: missing or invalid "specification.type" field. Got: ${JSON.stringify(def)}`
2903
+ );
2904
+ }
2905
+ if (!isNonEmptyString(def.specification.content)) {
2906
+ throw new Error(
2907
+ `${prefix}: missing or invalid "specification.content" field. Got: ${JSON.stringify(def)}`
2908
+ );
2909
+ }
2910
+ }
2911
+ }
2912
+ var _ManifestV2 = class __ManifestV2 {
2913
+ constructor(filePath, data) {
2914
+ this.filePath = filePath;
2915
+ this.data = data;
2916
+ }
2917
+ /**
2918
+ * Load stripe-app.yaml from disk
2919
+ * @param filePath - Path to stripe-app.yaml
2920
+ * @throws Error if file is invalid or cannot be read
2921
+ */
2922
+ static async load(filePath) {
2923
+ try {
2924
+ const content = await readFile3(filePath, "utf-8");
2925
+ const parsed = yaml.parse(content);
2926
+ if (!isYamlObject(parsed)) {
2927
+ throw new Error("Invalid stripe-app.yaml format: root must be an object");
2928
+ }
2929
+ validateManifestV2Data(parsed);
2930
+ const data = parsed;
2931
+ data.extensions ??= [];
2932
+ return new __ManifestV2(filePath, data);
2933
+ } catch (err) {
2934
+ if (err instanceof Error) {
2935
+ throw new Error(`Error reading stripe-app.yaml: ${err.message}`);
2936
+ }
2937
+ throw new Error(`Error reading stripe-app.yaml: ${String(err)}`);
2938
+ }
2939
+ }
2940
+ /**
2941
+ * Get the app ID from the manifest
2942
+ */
2943
+ getAppId() {
2944
+ return this.data.id;
2945
+ }
2946
+ /**
2947
+ * Get the app name from the manifest
2948
+ */
2949
+ getAppName() {
2950
+ return this.data.name;
2951
+ }
2952
+ // ============================================================
2953
+ // Custom Objects
2954
+ // ============================================================
2955
+ /**
2956
+ * Get all custom object definitions, parsed into internal format.
2957
+ * Entries are guaranteed structurally valid by load-time validation.
2958
+ */
2959
+ getCustomObjects() {
2960
+ const definitions = this.data.custom_object_definitions?.definitions;
2961
+ if (!definitions || definitions.length === 0) {
2962
+ return [];
2963
+ }
2964
+ return definitions.map((def) => ({
2965
+ id: def.id,
2966
+ type: def.specification.type,
2967
+ path: def.specification.content,
2968
+ name: _toPascalCase(def.id)
2969
+ }));
2970
+ }
2971
+ /**
2972
+ * Check if a custom object exists by id
2973
+ */
2974
+ hasCustomObject(id) {
2975
+ const definitions = this.data.custom_object_definitions?.definitions;
2976
+ if (!definitions) return false;
2977
+ return definitions.some((def) => def.id === id);
2978
+ }
2979
+ /**
2980
+ * Add a custom object definition.
2981
+ *
2982
+ * Identity is keyed on `id` alone. The export name is derived via
2983
+ * `_toPascalCase(id)` at read time, so `id` should be valid snake_case
2984
+ * (e.g., "device", "loyalty_card", "http_request").
2985
+ *
2986
+ * @param id - Object identifier (e.g., "device", "loyalty_card")
2987
+ * @param content - Path to the definition file (e.g., "src/device.object.ts")
2988
+ * @param type - Specification type, defaults to "typescript"
2989
+ * @returns true if added, false if already exists
2990
+ */
2991
+ addCustomObject(id, content, type = "typescript") {
2992
+ if (this.hasCustomObject(id)) {
2993
+ return false;
2994
+ }
2995
+ this.data.custom_object_definitions ??= {};
2996
+ this.data.custom_object_definitions.definitions ??= [];
2997
+ this.data.custom_object_definitions.definitions.push({
2998
+ id,
2999
+ specification: { type, content }
3000
+ });
3001
+ return true;
3002
+ }
3003
+ /**
3004
+ * Remove a custom object definition by id
3005
+ * @param id - Object identifier to remove
3006
+ * @returns true if removed, false if not found
3007
+ */
3008
+ removeCustomObject(id) {
3009
+ const block = this.data.custom_object_definitions;
3010
+ if (!block?.definitions) {
3011
+ return false;
3012
+ }
3013
+ const originalLength = block.definitions.length;
3014
+ block.definitions = block.definitions.filter((def) => def.id !== id);
3015
+ const newLength = block.definitions.length;
3016
+ if (newLength === 0) {
3017
+ delete this.data.custom_object_definitions;
3018
+ }
3019
+ return newLength < originalLength;
3020
+ }
3021
+ // ============================================================
3022
+ // Extensions
3023
+ // ============================================================
3024
+ /**
3025
+ * Add a new extension or update an existing one by ID
3026
+ * If an extension with the provided ID exists, it will be replaced entirely
3027
+ * @param extension - Extension configuration with all required fields including id
3028
+ * @returns The extension ID
3029
+ */
3030
+ addOrUpdateExtension(extension) {
3031
+ const newExtension = {
3032
+ id: extension.id,
3033
+ name: extension.name,
3034
+ interface_id: extension.interface_id,
3035
+ version: extension.version,
3036
+ ...extension.description !== void 0 && {
3037
+ description: extension.description
3038
+ },
3039
+ ...extension.stripe_version !== void 0 && {
3040
+ stripe_version: extension.stripe_version
3041
+ },
3042
+ ...extension.script_entry_point !== void 0 && {
3043
+ script_entry_point: extension.script_entry_point
3044
+ },
3045
+ ...extension.script !== void 0 && { script: extension.script },
3046
+ permissions: extension.permissions,
3047
+ methods: extension.methods,
3048
+ ...extension.configuration !== void 0 && {
3049
+ configuration: extension.configuration
3050
+ },
3051
+ ...extension.endpoints !== void 0 && {
3052
+ endpoints: extension.endpoints
3053
+ }
3054
+ };
3055
+ this.data.extensions ??= [];
3056
+ const existingIndex = this.data.extensions.findIndex(
3057
+ (ext) => ext.id === extension.id
3058
+ );
3059
+ if (existingIndex !== -1) {
3060
+ this.data.extensions[existingIndex] = newExtension;
3061
+ } else {
3062
+ this.data.extensions.push(newExtension);
3063
+ }
3064
+ return extension.id;
3065
+ }
3066
+ /**
3067
+ * Get a read-only view of all extensions
3068
+ */
3069
+ getExtensions() {
3070
+ return this.data.extensions ?? [];
3071
+ }
3072
+ /**
3073
+ * Get the raw manifest data (for reading other fields)
3074
+ */
3075
+ getRawData() {
3076
+ return this.data;
3077
+ }
3078
+ /**
3079
+ * Save changes back to disk
3080
+ * @throws Error if file cannot be written
3081
+ */
3082
+ async save() {
3083
+ try {
3084
+ const updatedContent = yaml.stringify(this.data);
3085
+ await writeFile2(this.filePath, updatedContent, "utf-8");
3086
+ } catch (err) {
3087
+ if (err instanceof Error) {
3088
+ throw new Error(`Error writing stripe-app.yaml: ${err.message}`);
3089
+ }
3090
+ throw new Error(`Error writing stripe-app.yaml: ${String(err)}`);
3091
+ }
3092
+ }
3093
+ };
3094
+
3095
+ // src/manifest/stripe-app-manifest.ts
3096
+ var _StripeAppManifest = class __StripeAppManifest {
3097
+ constructor(manifestPath, version, v1, v2) {
3098
+ this.manifestPath = manifestPath;
3099
+ this.version = version;
3100
+ this.v1 = v1;
3101
+ this.v2 = v2;
3102
+ }
3103
+ /**
3104
+ * Load a manifest file, automatically detecting the version.
3105
+ * @param manifestPath - Path to stripe-app.json or stripe-app.yaml
3106
+ * @returns Loaded manifest instance
3107
+ */
3108
+ static async load(manifestPath) {
3109
+ const version = __StripeAppManifest.detectVersion(manifestPath);
3110
+ if (version === "v1") {
3111
+ const reader = _ManifestV1.load(manifestPath);
3112
+ return new __StripeAppManifest(manifestPath, version, reader, null);
3113
+ } else {
3114
+ const reader = await _ManifestV2.load(manifestPath);
3115
+ return new __StripeAppManifest(manifestPath, version, null, reader);
3116
+ }
3117
+ }
3118
+ /**
3119
+ * Detect manifest version from file path.
3120
+ * TODO: Add content-based detection if needed.
3121
+ */
3122
+ static detectVersion(manifestPath) {
3123
+ const lowerPath = manifestPath.toLowerCase();
3124
+ if (lowerPath.endsWith(".yaml") || lowerPath.endsWith(".yml")) {
3125
+ return "v2";
3126
+ }
3127
+ if (lowerPath.endsWith(".json")) {
3128
+ return "v1";
3129
+ }
3130
+ throw new Error(
3131
+ `Cannot detect manifest version from path: ${manifestPath}. Expected .json (v1) or .yaml/.yml (v2) extension.`
3132
+ );
3133
+ }
3134
+ /**
3135
+ * Get the detected manifest version
3136
+ */
3137
+ getVersion() {
3138
+ return this.version;
3139
+ }
3140
+ /**
3141
+ * Get the manifest file path
3142
+ */
3143
+ getManifestPath() {
3144
+ return this.manifestPath;
3145
+ }
3146
+ // ============================================================
3147
+ // App Metadata (supported by both V1 and V2)
3148
+ // ============================================================
3149
+ /**
3150
+ * Get the app ID from the manifest
3151
+ */
3152
+ getAppId() {
3153
+ if (this.v1) {
3154
+ return this.v1.getAppId();
3155
+ }
3156
+ if (this.v2) {
3157
+ return this.v2.getAppId();
3158
+ }
3159
+ return void 0;
3160
+ }
3161
+ /**
3162
+ * Get the app name from the manifest
3163
+ */
3164
+ getAppName() {
3165
+ if (this.v1) {
3166
+ return this.v1.getAppName();
3167
+ }
3168
+ if (this.v2) {
3169
+ return this.v2.getAppName();
3170
+ }
3171
+ return void 0;
3172
+ }
3173
+ // ============================================================
3174
+ // Custom Objects (supported by both V1 and V2)
3175
+ // ============================================================
3176
+ /**
3177
+ * Get all custom objects from the manifest
3178
+ */
3179
+ getCustomObjects() {
3180
+ if (this.v1) {
3181
+ return this.v1.getCustomObjects();
3182
+ }
3183
+ if (this.v2) {
3184
+ return this.v2.getCustomObjects().map((obj) => ({
3185
+ filePath: obj.path,
3186
+ className: obj.name
3187
+ }));
3188
+ }
3189
+ return [];
3190
+ }
3191
+ /**
3192
+ * Check if a custom object entry exists in the manifest.
3193
+ *
3194
+ * **V2 note:** Identity is keyed on `_toSnakeCase(className)` alone — `filePath`
3195
+ * is not considered. Two entries with the same class name but different file
3196
+ * paths are treated as the same object. The `_toSnakeCase` → `_toPascalCase`
3197
+ * round-trip is lossless for typical class names but lossy for consecutive
3198
+ * uppercase (e.g., `HTTPClient` → `http_client` → `HttpClient`). The manifest
3199
+ * `id` field is the source of truth; see `_CustomObjectDefinitionYaml` docs.
3200
+ */
3201
+ hasCustomObject(entry) {
3202
+ if (this.v1) {
3203
+ return this.v1.hasCustomObject(entry);
3204
+ }
3205
+ if (this.v2) {
3206
+ return this.v2.hasCustomObject(_toSnakeCase(entry.className));
3207
+ }
3208
+ return false;
3209
+ }
3210
+ /**
3211
+ * Add a custom object entry to the manifest.
3212
+ *
3213
+ * **V2 note:** The manifest `id` is derived as `_toSnakeCase(className)` and
3214
+ * `filePath` is stored as the specification `content` path. Identity/dedup
3215
+ * is based on `id` alone — see `hasCustomObject` for details.
3216
+ *
3217
+ * @param entry - The custom object entry to add
3218
+ * @returns true if entry was added, false if it already existed
3219
+ */
3220
+ addCustomObject(entry) {
3221
+ if (this.v1) {
3222
+ return this.v1.addCustomObject(entry);
3223
+ }
3224
+ if (this.v2) {
3225
+ return this.v2.addCustomObject(_toSnakeCase(entry.className), entry.filePath);
3226
+ }
3227
+ return false;
3228
+ }
3229
+ /**
3230
+ * Remove a custom object entry from the manifest.
3231
+ *
3232
+ * **V2 note:** Removal is keyed on `_toSnakeCase(className)` — `filePath` is
3233
+ * not considered. See `hasCustomObject` for identity semantics.
3234
+ *
3235
+ * @param entry - The custom object entry to remove
3236
+ * @returns true if entry was removed, false if it didn't exist
3237
+ */
3238
+ removeCustomObject(entry) {
3239
+ if (this.v1) {
3240
+ return this.v1.removeCustomObject(entry);
3241
+ }
3242
+ if (this.v2) {
3243
+ return this.v2.removeCustomObject(_toSnakeCase(entry.className));
3244
+ }
3245
+ return false;
3246
+ }
3247
+ // ============================================================
3248
+ // Extensions (V2 only)
3249
+ // ============================================================
3250
+ /**
3251
+ * Get all extensions from the manifest
3252
+ * @throws Error if manifest version doesn't support extensions
3253
+ */
3254
+ getExtensions() {
3255
+ if (this.v2) {
3256
+ return this.v2.getExtensions();
3257
+ }
3258
+ throw new Error("Extensions are not supported in V1 manifests (stripe-app.json)");
3259
+ }
3260
+ /**
3261
+ * Add or update an extension in the manifest.
3262
+ * If an extension with the same ID exists, it will be replaced.
3263
+ *
3264
+ * @param config - Full extension configuration
3265
+ * @returns The extension ID
3266
+ * @throws Error if manifest version doesn't support extensions
3267
+ */
3268
+ addOrUpdateExtension(config) {
3269
+ if (this.v2) {
3270
+ return this.v2.addOrUpdateExtension(config);
3271
+ }
3272
+ throw new Error("Extensions are not supported in V1 manifests (stripe-app.json)");
3273
+ }
3274
+ // ============================================================
3275
+ // Persistence
3276
+ // ============================================================
3277
+ /**
3278
+ * Save changes back to disk
3279
+ */
3280
+ async save() {
3281
+ if (this.v1) {
3282
+ this.v1.save();
3283
+ return;
3284
+ }
3285
+ if (this.v2) {
3286
+ await this.v2.save();
3287
+ return;
3288
+ }
3289
+ throw new Error("No reader loaded - this should never happen");
3290
+ }
3291
+ };
3292
+
3293
+ // src/workspace/index.ts
3294
+ import { z } from "zod";
3295
+ import path4 from "path";
3296
+ import { existsSync as existsSync2 } from "fs";
3297
+ import { readFile as readFile4 } from "fs/promises";
3298
+ import { execSync as execSync3 } from "child_process";
3299
+ import {
3300
+ _customObjectGenerators,
3301
+ _customObjectsWorkspaceGenerator
3302
+ } from "@stripe/extensibility-custom-objects-tools/internal";
3303
+ import {
3304
+ _GeneratorRunner,
3305
+ _createCliContext as _createCliContext2,
3306
+ _toSnakeCase as _toSnakeCase2,
3307
+ _openStripeAppManifest,
3308
+ _beginTransaction
3309
+ } from "@stripe/extensibility-tool-utils";
3310
+ var _regenWorkspaceOptionsSchema = z.object({
3311
+ /** Workspace template ID (e.g., 'core.workflows.custom_action', 'custom-objects'). Absence means root workspace mode. */
3312
+ templateId: z.string().optional(),
3313
+ /** Path to project root. Resolved relative to cwd. Defaults to cwd. */
3314
+ root: z.string().optional(),
3315
+ /** Path to directory containing package.json (resolved relative to cwd). Used for reading existing metadata. If undefined, package.json is not read. */
3316
+ packageDir: z.string().optional(),
3317
+ /** Workspace ID. Validated against package.json if both are present. */
3318
+ workspaceId: z.string().optional(),
3319
+ /** Workspace name. Overrides package.json description if provided. */
3320
+ workspaceName: z.string().optional(),
3321
+ /** Skip dependency installation */
3322
+ skipDependencies: z.boolean().optional(),
3323
+ /** Skip post-generation hooks */
3324
+ skipHooks: z.boolean().optional(),
3325
+ /** Force overwrite all files without prompting */
3326
+ force: z.boolean().optional(),
3327
+ /** Custom object name. Required when templateId is 'custom-object'. */
3328
+ name: z.string().optional(),
3329
+ /** Implementation type. When 'remote-function', only .schema.json files are written and dependencies/hooks are skipped. */
3330
+ implementationType: z.enum(["script", "remote-function"]).optional()
3331
+ });
3332
+ async function readPackageMetadata(dir) {
3333
+ const pkgPath = path4.join(dir, "package.json");
3334
+ try {
3335
+ const pkgContent = await readFile4(pkgPath, "utf-8");
3336
+ const pkg = JSON.parse(pkgContent);
3337
+ return {
3338
+ ...pkg.name !== void 0 && { id: pkg.name },
3339
+ ...pkg.description !== void 0 && { name: pkg.description },
3340
+ ...pkg.version !== void 0 && { version: pkg.version }
3341
+ };
3342
+ } catch {
3343
+ return null;
3344
+ }
3345
+ }
3346
+ async function _resolvePackageMetadata(providedId, providedName, packageDir) {
3347
+ let id = providedId;
3348
+ let name = providedName;
3349
+ let version = "0.0.1";
3350
+ if (packageDir !== void 0) {
3351
+ const pkgMetadata = await readPackageMetadata(packageDir);
3352
+ if (pkgMetadata) {
3353
+ if (id && pkgMetadata.id && id !== pkgMetadata.id) {
3354
+ throw new Error(
3355
+ `Workspace ID mismatch: --workspace-id "${id}" does not match package.json name "${pkgMetadata.id}"`
3356
+ );
3357
+ }
3358
+ id ??= pkgMetadata.id;
3359
+ name ??= pkgMetadata.name;
3360
+ if (pkgMetadata.version) {
3361
+ version = pkgMetadata.version;
3362
+ }
3363
+ }
3364
+ }
3365
+ if (!id) {
3366
+ throw new Error(
3367
+ "ID required: provide --workspace-id or ensure package.json has a name field"
3368
+ );
3369
+ }
3370
+ name ??= id;
3371
+ return { id, name, version };
3372
+ }
3373
+ function runPostGenerationHooks(hooks, workingDir, disabled = false, context = _createCliContext2()) {
3374
+ if (!hooks || hooks.length === 0 || disabled) {
3375
+ return Promise.resolve();
3376
+ }
3377
+ context.ux.log("\nRunning post-generation hooks...");
3378
+ for (const hook of hooks) {
3379
+ const description = hook.description ? ` (${hook.description})` : "";
3380
+ let command;
3381
+ let hookName;
3382
+ if ("script" in hook) {
3383
+ command = `pnpm run ${hook.script}`;
3384
+ hookName = hook.script;
3385
+ } else {
3386
+ command = `pnpm exec ${hook.exec}`;
3387
+ hookName = hook.exec;
3388
+ }
3389
+ context.ux.log(`
3390
+ Running: ${command}${description}`);
3391
+ try {
3392
+ execSync3(command, {
3393
+ cwd: workingDir,
3394
+ stdio: "inherit"
3395
+ });
3396
+ context.ux.log(`\u2713 Hook completed: ${hookName}`);
3397
+ } catch (error) {
3398
+ context.ux.error(`! Hook failed: ${hookName}`);
3399
+ if (error instanceof Error) {
3400
+ context.ux.error(` ${error.message}`);
3401
+ }
3402
+ }
3403
+ }
3404
+ return Promise.resolve();
3405
+ }
3406
+ async function installDependencies(services, cwd, dependencies, context) {
3407
+ if (dependencies.length === 0) {
3408
+ return;
3409
+ }
3410
+ const depManager = services.createDepManager({ cwd, context });
3411
+ const pendingChanges = await depManager.ensureDependencies({
3412
+ required: dependencies
3413
+ });
3414
+ for (const pendingChange of pendingChanges) {
3415
+ if (pendingChange.action === "conflict") {
3416
+ depManager.resolveConflict(pendingChange.dependency);
3417
+ }
3418
+ }
3419
+ await depManager.commit();
3420
+ }
3421
+ async function backfillMissingExtensionEslintConfigs(services, projectRoot) {
3422
+ const manifestPath = path4.join(projectRoot, "stripe-app.yaml");
3423
+ if (!existsSync2(manifestPath)) {
3424
+ return [];
3425
+ }
3426
+ const manifest = await services.loadManifest(manifestPath);
3427
+ const extensions = manifest.getExtensions();
3428
+ return extensions.flatMap((extension) => {
3429
+ const eslintConfigPath = `extensions/${extension.id}/eslint.config.mts`;
3430
+ if (existsSync2(path4.join(projectRoot, eslintConfigPath))) {
3431
+ return [];
3432
+ }
3433
+ return _createExtensionEslintConfigFile(
3434
+ {
3435
+ id: extension.id,
3436
+ extensionInterfaceId: extension.interface_id
3437
+ },
3438
+ { fs: _fs.scope("extensions") }
3439
+ );
3440
+ });
3441
+ }
3442
+ function resolveMode(options, projectRoot, packageDir) {
3443
+ if (!options.templateId) {
3444
+ return {
3445
+ label: "root",
3446
+ workspaceDir: () => packageDir ?? projectRoot,
3447
+ generate: (svc, meta) => svc.generateRoot({
3448
+ appId: meta.id,
3449
+ appName: meta.name,
3450
+ version: meta.version
3451
+ })
3452
+ };
3453
+ }
3454
+ if (options.templateId === "custom-objects") {
3455
+ return {
3456
+ label: "custom-objects",
3457
+ workspaceDir: () => packageDir ?? path4.join(projectRoot, "custom-objects"),
3458
+ generate: async (svc) => {
3459
+ const workspaceResult = await svc.generateCustomObjectsWorkspace({});
3460
+ return {
3461
+ ...workspaceResult,
3462
+ files: workspaceResult.files.map((f) => ({ ...f, precious: true }))
3463
+ };
3464
+ }
3465
+ };
3466
+ }
3467
+ if (options.templateId === "custom-object") {
3468
+ const objectName = options.name;
3469
+ if (!objectName) {
3470
+ throw new Error("--name is required when --template-id is 'custom-object'");
3471
+ }
3472
+ return {
3473
+ label: `custom-object:${objectName}`,
3474
+ workspaceDir: () => packageDir ?? path4.join(projectRoot, "custom-objects"),
3475
+ generate: async (svc) => {
3476
+ const customObjectsWorkspaceDir = packageDir ?? path4.join(projectRoot, "custom-objects");
3477
+ const workspaceExists = existsSync2(path4.join(customObjectsWorkspaceDir, "package.json")) && existsSync2(path4.join(customObjectsWorkspaceDir, "tsconfig.json"));
3478
+ const objectResult = await svc.generateCustomObject({ name: objectName });
3479
+ if (workspaceExists) {
3480
+ return objectResult;
3481
+ }
3482
+ const workspaceResult = await svc.generateCustomObjectsWorkspace({});
3483
+ return {
3484
+ ...objectResult,
3485
+ files: [
3486
+ ...workspaceResult.files.map((f) => ({ ...f, precious: true })),
3487
+ ...objectResult.files
3488
+ ]
3489
+ };
3490
+ },
3491
+ finalize: async (_svc, _meta, root, _output, context) => {
3492
+ context.ux.log("\nUpdating stripe-app.yaml...");
3493
+ const manifestPath = path4.join(root, "stripe-app.yaml");
3494
+ const manifest = await _openStripeAppManifest(manifestPath);
3495
+ const apiName = _toSnakeCase2(objectName);
3496
+ if (!manifest.hasCustomObject(apiName)) {
3497
+ manifest.addCustomObject(apiName, `custom-objects/src/${apiName}.object.ts`);
3498
+ const tx = _beginTransaction();
3499
+ tx.adopt(manifest);
3500
+ const report = await tx.commit();
3501
+ if (report.written.length > 0) {
3502
+ context.ux.log("\u2713 Updated stripe-app.yaml");
3503
+ }
3504
+ } else {
3505
+ context.ux.log("- Custom object already registered in stripe-app.yaml");
3506
+ }
3507
+ }
3508
+ };
3509
+ }
3510
+ const interfaceId = options.templateId;
3511
+ function buildRemoteFunctionMethodsAndEndpoints(extensionId, outputMethods) {
3512
+ const methods = {};
3513
+ const endpoints = Object.entries(outputMethods).map(([methodName, methodConfig]) => {
3514
+ const endpointId = `${extensionId}.${methodName}`;
3515
+ const customInput = typeof methodConfig === "object" && methodConfig !== null && "custom_input" in methodConfig ? Reflect.get(methodConfig, "custom_input") : void 0;
3516
+ methods[methodName] = {
3517
+ implementation_type: "remote_function",
3518
+ ...customInput !== void 0 && { custom_input: customInput },
3519
+ endpoint_id: endpointId
3520
+ };
3521
+ return {
3522
+ id: endpointId,
3523
+ type: "remote_function",
3524
+ live: { url: "https://example.com/" }
3525
+ };
3526
+ });
3527
+ return { methods, endpoints };
3528
+ }
3529
+ return {
3530
+ label: interfaceId,
3531
+ workspaceDir: (meta) => packageDir ?? path4.join(projectRoot, "extensions", meta.id),
3532
+ generate: (svc, meta) => svc.generateExtension(interfaceId, {
3533
+ id: meta.id,
3534
+ name: meta.name,
3535
+ version: meta.version
3536
+ }),
3537
+ finalize: async (svc, meta, root, output, context) => {
3538
+ if (!output.methods) return;
3539
+ context.ux.log("\nUpdating stripe-app.yaml...");
3540
+ const manifest = await svc.loadManifest(path4.join(root, "stripe-app.yaml"));
3541
+ const permissions = [];
3542
+ const baseConfig = {
3543
+ id: meta.id,
3544
+ name: meta.name,
3545
+ interface_id: interfaceId,
3546
+ version: meta.version,
3547
+ permissions
3548
+ };
3549
+ if (options.implementationType === "remote-function") {
3550
+ const { methods, endpoints } = buildRemoteFunctionMethodsAndEndpoints(
3551
+ meta.id,
3552
+ output.methods
3553
+ );
3554
+ manifest.addOrUpdateExtension({ ...baseConfig, methods, endpoints });
3555
+ } else {
3556
+ manifest.addOrUpdateExtension({
3557
+ ...baseConfig,
3558
+ script: {
3559
+ type: "typescript",
3560
+ content: `extensions/${meta.id}/src/index.ts`
3561
+ },
3562
+ methods: output.methods,
3563
+ configuration: {
3564
+ input_schema: {
3565
+ type: "json_schema",
3566
+ content: `extensions/${meta.id}/generated/config.schema.json`
3567
+ },
3568
+ ui_schema: {
3569
+ type: "jsonforms",
3570
+ content: `extensions/${meta.id}/generated/config.ui.json`
3571
+ }
3572
+ }
3573
+ });
3574
+ }
3575
+ await manifest.save();
3576
+ }
3577
+ };
3578
+ }
3579
+ var _defaultServices = {
3580
+ generateRoot: (vars) => _rootTemplateManager.generate(vars),
3581
+ generateExtension: (key, vars) => _templateManager.generate(key, vars),
3582
+ generateCustomObject: async (vars) => {
3583
+ const plan = await _customObjectGenerators.plan(vars, {
3584
+ scope: "project",
3585
+ projectRoot: process.cwd()
3586
+ });
3587
+ return {
3588
+ files: plan.files.map((f) => ({ path: f.path, content: f.content }))
3589
+ };
3590
+ },
3591
+ generateCustomObjectsWorkspace: async (vars) => {
3592
+ const runner = new _GeneratorRunner(_customObjectsWorkspaceGenerator);
3593
+ const plan = await runner.plan(vars, {
3594
+ scope: "project",
3595
+ projectRoot: process.cwd()
3596
+ });
3597
+ return {
3598
+ files: plan.files.map((f) => ({ path: f.path, content: f.content }))
3599
+ };
3600
+ },
3601
+ writeFiles: _writeGeneratedFiles,
3602
+ createDepManager: ({ cwd, context }) => new _DependencyManager({ cwd, ...context !== void 0 && { context } }),
3603
+ loadManifest: (manifestPath) => _StripeAppManifest.load(manifestPath),
3604
+ runHooks: runPostGenerationHooks
3605
+ };
3606
+ async function _regenAppProjectWorkspace(options, services = _defaultServices, context = _createCliContext2()) {
3607
+ const isCustomObjectMode = options.templateId === "custom-object";
3608
+ if (!isCustomObjectMode && !options.packageDir && !options.workspaceId) {
3609
+ throw new Error("At least one of packageDir or workspaceId is required");
3610
+ }
3611
+ const projectRoot = path4.resolve(options.root ?? ".");
3612
+ const packageDir = options.packageDir ? path4.resolve(options.packageDir) : void 0;
3613
+ const mode = resolveMode(options, projectRoot, packageDir);
3614
+ const metadata = isCustomObjectMode ? { id: "", name: "", version: "" } : await _resolvePackageMetadata(
3615
+ options.workspaceId,
3616
+ options.workspaceName,
3617
+ packageDir
3618
+ );
3619
+ const workspaceDir = mode.workspaceDir(metadata);
3620
+ const isRootRegen = options.templateId === void 0;
3621
+ context.ux.log(`Generating files from template: ${mode.label}...`);
3622
+ const templateOutput = await mode.generate(services, metadata);
3623
+ const allFiles = isRootRegen ? [
3624
+ ...templateOutput.files,
3625
+ ...await backfillMissingExtensionEslintConfigs(services, projectRoot)
3626
+ ] : templateOutput.files;
3627
+ const filesToWrite = options.implementationType === "remote-function" ? allFiles.filter((f) => f.path.endsWith(".schema.json")) : allFiles;
3628
+ if (isRootRegen) {
3629
+ const existingPkgPath = path4.join(projectRoot, "package.json");
3630
+ let existingOverrides;
3631
+ try {
3632
+ const existingPkg = JSON.parse(await readFile4(existingPkgPath, "utf-8"));
3633
+ existingOverrides = existingPkg.pnpm?.overrides;
3634
+ } catch {
3635
+ }
3636
+ if (existingOverrides && Object.keys(existingOverrides).length > 0) {
3637
+ const pkgFile = filesToWrite.find((f) => f.path === "package.json");
3638
+ if (pkgFile) {
3639
+ let newPkg;
3640
+ try {
3641
+ newPkg = JSON.parse(pkgFile.content);
3642
+ } catch (err) {
3643
+ throw new Error(
3644
+ `Failed to parse generated package.json while preserving pnpm.overrides: ${err instanceof Error ? err.message : String(err)}`
3645
+ );
3646
+ }
3647
+ newPkg.pnpm = {
3648
+ ...newPkg.pnpm,
3649
+ overrides: { ...newPkg.pnpm?.overrides, ...existingOverrides }
3650
+ };
3651
+ pkgFile.content = JSON.stringify(newPkg, null, 2) + "\n";
3652
+ }
3653
+ }
3654
+ }
3655
+ if (isRootRegen) {
3656
+ const existingPkgPath = path4.join(projectRoot, "package.json");
3657
+ try {
3658
+ const existingPkg = JSON.parse(await readFile4(existingPkgPath, "utf-8"));
3659
+ const existingOverrides = existingPkg.pnpm?.overrides;
3660
+ if (existingOverrides && Object.keys(existingOverrides).length > 0) {
3661
+ const pkgFile = filesToWrite.find((f) => f.path === "package.json");
3662
+ if (pkgFile) {
3663
+ const newPkg = JSON.parse(pkgFile.content);
3664
+ newPkg.pnpm = {
3665
+ ...newPkg.pnpm,
3666
+ overrides: { ...newPkg.pnpm?.overrides, ...existingOverrides }
3667
+ };
3668
+ pkgFile.content = JSON.stringify(newPkg, null, 2) + "\n";
3669
+ }
3670
+ }
3671
+ } catch {
3672
+ }
3673
+ }
3674
+ context.ux.log("Writing files...");
3675
+ const writeResult = await services.writeFiles(filesToWrite, {
3676
+ cwd: projectRoot,
3677
+ write: options.force ? "overwrite-all" : (path5, cwd, newContent) => _advancedDiffPrompt(path5, cwd, newContent),
3678
+ onFileWritten: (file, wasOverwrite) => {
3679
+ const verb = wasOverwrite ? "Updated" : "Wrote";
3680
+ context.ux.log(`\u2713 ${verb} ${file.path}`);
3681
+ },
3682
+ onFileSkipped: (file) => {
3683
+ context.ux.log(`- Skipped ${file.path}`);
3684
+ },
3685
+ onFileIdentical: (file) => {
3686
+ context.ux.log(`= Identical ${file.path}`);
3687
+ }
3688
+ });
3689
+ if (writeResult.aborted) {
3690
+ context.ux.log("\nAborted by user.");
3691
+ return;
3692
+ }
3693
+ if (options.implementationType !== "remote-function" && !options.skipDependencies && templateOutput.dependencies) {
3694
+ context.ux.log("\nInstalling dependencies...");
3695
+ const allDeps = [
3696
+ ...templateOutput.dependencies.runtime ?? [],
3697
+ ...templateOutput.dependencies.dev ?? []
3698
+ ];
3699
+ await installDependencies(services, workspaceDir, allDeps, context);
3700
+ }
3701
+ if (options.implementationType !== "remote-function" && !options.skipDependencies && !isRootRegen && !isCustomObjectMode) {
3702
+ await installDependencies(
3703
+ services,
3704
+ projectRoot,
3705
+ [
3706
+ _devNpmDep(
3707
+ EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME,
3708
+ EXTENSIBILITY_ESLINT_PLUGIN_VERSION
3709
+ )
3710
+ ],
3711
+ context
3712
+ );
3713
+ }
3714
+ await mode.finalize?.(services, metadata, projectRoot, templateOutput, context);
3715
+ if (options.implementationType !== "remote-function" && !options.skipHooks) {
3716
+ await services.runHooks(
3717
+ templateOutput.postGenerationHooks,
3718
+ workspaceDir,
3719
+ false,
3720
+ context
3721
+ );
3722
+ }
3723
+ context.ux.log("\n\u2713 Regeneration complete");
3724
+ }
3725
+
3726
+ // src/index.ts
3727
+ import { _CliUx, _createCliContext as _createCliContext3 } from "@stripe/extensibility-tool-utils";
3728
+ export {
3729
+ _CliUx,
3730
+ _DependencyManager,
3731
+ _ExtensionTemplateManager,
3732
+ _ManifestV1,
3733
+ _ManifestV2,
3734
+ _NpmDependencyHandler,
3735
+ _SingleTemplateManager,
3736
+ _StripeAppManifest,
3737
+ _StripeCliPluginHandler,
3738
+ _TemplateManager,
3739
+ _advancedDiffPrompt,
3740
+ _createCliContext3 as _createCliContext,
3741
+ _createExtensionEslintConfigFile,
3742
+ _createSimpleSingleFileTemplate,
3743
+ _createSimpleTemplate,
3744
+ _defaultServices,
3745
+ _detectPackageManager,
3746
+ _devNpmDep,
3747
+ _fs,
3748
+ _npmDep,
3749
+ _promptOverwrite,
3750
+ _regenAppProjectWorkspace,
3751
+ _regenWorkspaceOptionsSchema,
3752
+ _resolvePackageMetadata,
3753
+ _rootTemplateManager,
3754
+ _rootWorkspaceTemplate,
3755
+ _stripeCliPluginDep,
3756
+ _templateManager,
3757
+ _writeGeneratedFiles
3758
+ };