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