@velastack/patterns 0.2.12 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +4 -3
  2. package/dist/chunks/{collections-CcL5bbBk.js → collections-CgdvZXmh.js} +17 -17
  3. package/dist/chunks/{collections-CcL5bbBk.js.map → collections-CgdvZXmh.js.map} +1 -1
  4. package/dist/chunks/{compose-handle-D16KmBVd.js → compose-handle-Cg9jnCsS.js} +21 -21
  5. package/dist/chunks/{compose-handle-D16KmBVd.js.map → compose-handle-Cg9jnCsS.js.map} +1 -1
  6. package/dist/chunks/dispatch-BRnt8PcW.js +6 -0
  7. package/dist/chunks/dispatch-BRnt8PcW.js.map +1 -0
  8. package/dist/chunks/generate-BkQ1xMDp.js +30 -0
  9. package/dist/chunks/generate-BkQ1xMDp.js.map +1 -0
  10. package/dist/chunks/{generate-Va1sxVPG.js → generate-DRA63W0r.js} +17 -64
  11. package/dist/chunks/generate-DRA63W0r.js.map +1 -0
  12. package/dist/chunks/generate-_LvrYK6i.js +55 -0
  13. package/dist/chunks/generate-_LvrYK6i.js.map +1 -0
  14. package/dist/chunks/generate-iQP31-m1.js +252 -0
  15. package/dist/chunks/generate-iQP31-m1.js.map +1 -0
  16. package/dist/chunks/{generate.runtime-j1gfY6Xq.js → generate.runtime-B0hhtyAL.js} +2 -2
  17. package/dist/chunks/{generate.runtime-j1gfY6Xq.js.map → generate.runtime-B0hhtyAL.js.map} +1 -1
  18. package/dist/chunks/{generate.runtime-CSXj-ebM.js → generate.runtime-B49wetSx.js} +12 -12
  19. package/dist/chunks/{generate.runtime-CSXj-ebM.js.map → generate.runtime-B49wetSx.js.map} +1 -1
  20. package/dist/chunks/{generate.runtime-DAkg7Fy5.js → generate.runtime-B7LRx-BU.js} +2 -2
  21. package/dist/chunks/{generate.runtime-DAkg7Fy5.js.map → generate.runtime-B7LRx-BU.js.map} +1 -1
  22. package/dist/chunks/generate.runtime-BKo-Nidn.js +38 -0
  23. package/dist/chunks/generate.runtime-BKo-Nidn.js.map +1 -0
  24. package/dist/chunks/{generate.runtime-Zh5n8XpR.js → generate.runtime-BORbegw_.js} +106 -96
  25. package/dist/chunks/generate.runtime-BORbegw_.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-BL7uKgW7.js → generate.runtime-BbIN0tUZ.js} +16 -16
  27. package/dist/chunks/{generate.runtime-BL7uKgW7.js.map → generate.runtime-BbIN0tUZ.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-CwzHEcKv.js → generate.runtime-BnWE4qsu.js} +24 -24
  29. package/dist/chunks/generate.runtime-BnWE4qsu.js.map +1 -0
  30. package/dist/chunks/{generate.runtime-CiTmbkAk.js → generate.runtime-BwhGDnGu.js} +3 -3
  31. package/dist/chunks/generate.runtime-BwhGDnGu.js.map +1 -0
  32. package/dist/chunks/{generate.runtime-BdPtilz4.js → generate.runtime-CCg2Pjcv.js} +13 -13
  33. package/dist/chunks/{generate.runtime-BdPtilz4.js.map → generate.runtime-CCg2Pjcv.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-BbNMkG4j.js → generate.runtime-CRYjWJRe.js} +9 -9
  35. package/dist/chunks/{generate.runtime-BbNMkG4j.js.map → generate.runtime-CRYjWJRe.js.map} +1 -1
  36. package/dist/chunks/generate.runtime-CcuAXuV2.js +60 -0
  37. package/dist/chunks/generate.runtime-CcuAXuV2.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-DPIH5sSI.js → generate.runtime-D0icLb5j.js} +51 -48
  39. package/dist/chunks/{generate.runtime-DPIH5sSI.js.map → generate.runtime-D0icLb5j.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-CJVy-mMN.js → generate.runtime-D2e_KRj0.js} +2 -2
  41. package/dist/chunks/{generate.runtime-CJVy-mMN.js.map → generate.runtime-D2e_KRj0.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-DnWw9tL1.js → generate.runtime-D44gjxRA.js} +105 -102
  43. package/dist/chunks/generate.runtime-D44gjxRA.js.map +1 -0
  44. package/dist/chunks/{generate.runtime-1gbaOucO.js → generate.runtime-D8vgh5MH.js} +48 -7
  45. package/dist/chunks/generate.runtime-D8vgh5MH.js.map +1 -0
  46. package/dist/chunks/generate.runtime-DAmYsIvF.js +32 -0
  47. package/dist/chunks/generate.runtime-DAmYsIvF.js.map +1 -0
  48. package/dist/chunks/{generate.runtime-CVLtEsXb.js → generate.runtime-DNaQxed-.js} +35 -35
  49. package/dist/chunks/{generate.runtime-CVLtEsXb.js.map → generate.runtime-DNaQxed-.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-d9HT4v-7.js → generate.runtime-DOuufRLr.js} +4 -4
  51. package/dist/chunks/generate.runtime-DOuufRLr.js.map +1 -0
  52. package/dist/chunks/{generate.runtime-A8wfItN7.js → generate.runtime-DSqkXvps.js} +12 -12
  53. package/dist/chunks/{generate.runtime-A8wfItN7.js.map → generate.runtime-DSqkXvps.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-BX53l-rL.js → generate.runtime-DhkaXTq3.js} +3 -3
  55. package/dist/chunks/{generate.runtime-BX53l-rL.js.map → generate.runtime-DhkaXTq3.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-Dywp4xth.js → generate.runtime-DoZdSh9W.js} +2 -2
  57. package/dist/chunks/{generate.runtime-Dywp4xth.js.map → generate.runtime-DoZdSh9W.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-T9DZJH8m.js → generate.runtime-S5RIgbQx.js} +103 -100
  59. package/dist/chunks/generate.runtime-S5RIgbQx.js.map +1 -0
  60. package/dist/chunks/{generate.runtime-CN3v78hx.js → generate.runtime-WmSMWL15.js} +17 -17
  61. package/dist/chunks/{generate.runtime-CN3v78hx.js.map → generate.runtime-WmSMWL15.js.map} +1 -1
  62. package/dist/chunks/generate.runtime-acRmiU7e.js +81 -0
  63. package/dist/chunks/generate.runtime-acRmiU7e.js.map +1 -0
  64. package/dist/chunks/{generate.runtime-l-Tiahb2.js → generate.runtime-flFRYzpi.js} +34 -59
  65. package/dist/chunks/generate.runtime-flFRYzpi.js.map +1 -0
  66. package/dist/chunks/generate.runtime-gtpOuLNO.js +110 -0
  67. package/dist/chunks/generate.runtime-gtpOuLNO.js.map +1 -0
  68. package/dist/chunks/{generate.runtime-Dx8Mcs2i.js → generate.runtime-kLxeDGnS.js} +13 -13
  69. package/dist/chunks/{generate.runtime-Dx8Mcs2i.js.map → generate.runtime-kLxeDGnS.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-BqxVaq5P.js → generate.runtime-wA1G3tQ4.js} +18 -18
  71. package/dist/chunks/{generate.runtime-BqxVaq5P.js.map → generate.runtime-wA1G3tQ4.js.map} +1 -1
  72. package/dist/chunks/{modify-file-BlWTOkCH.js → modify-file-GQD6uNgI.js} +52 -10
  73. package/dist/chunks/modify-file-GQD6uNgI.js.map +1 -0
  74. package/dist/chunks/{pocketbase-ewxQLtse.js → pocketbase-CeG5BMN2.js} +59 -52
  75. package/dist/chunks/{pocketbase-ewxQLtse.js.map → pocketbase-CeG5BMN2.js.map} +1 -1
  76. package/dist/chunks/providers-DO9kMyzB.js +69 -0
  77. package/dist/chunks/providers-DO9kMyzB.js.map +1 -0
  78. package/dist/chunks/rolldown-runtime-DArdT4gl.js +23 -0
  79. package/dist/chunks/{shared-Bm3eMFy-.js → shared-BwHQM-a9.js} +2 -2
  80. package/dist/chunks/{shared-Bm3eMFy-.js.map → shared-BwHQM-a9.js.map} +1 -1
  81. package/dist/chunks/site-D027dpBm.js +55 -0
  82. package/dist/chunks/site-D027dpBm.js.map +1 -0
  83. package/dist/chunks/{ui-CD-psDWi.js → ui-B4Tuit-7.js} +2 -2
  84. package/dist/chunks/{ui-CD-psDWi.js.map → ui-B4Tuit-7.js.map} +1 -1
  85. package/dist/chunks/{write-result-DBKv-Q7J.js → write-result-DewHCNhM.js} +2 -2
  86. package/dist/chunks/{write-result-DBKv-Q7J.js.map → write-result-DewHCNhM.js.map} +1 -1
  87. package/dist/index.d.ts +268 -62
  88. package/dist/index.js +2265 -2246
  89. package/dist/index.js.map +1 -1
  90. package/package.json +3 -3
  91. package/dist/chunks/dispatch-B5PfQ2CA.js +0 -6
  92. package/dist/chunks/dispatch-B5PfQ2CA.js.map +0 -1
  93. package/dist/chunks/generate-Va1sxVPG.js.map +0 -1
  94. package/dist/chunks/generate.runtime-1gbaOucO.js.map +0 -1
  95. package/dist/chunks/generate.runtime-Bb64J0ab.js +0 -87
  96. package/dist/chunks/generate.runtime-Bb64J0ab.js.map +0 -1
  97. package/dist/chunks/generate.runtime-CiTmbkAk.js.map +0 -1
  98. package/dist/chunks/generate.runtime-CwzHEcKv.js.map +0 -1
  99. package/dist/chunks/generate.runtime-Dj22Kx0W.js +0 -107
  100. package/dist/chunks/generate.runtime-Dj22Kx0W.js.map +0 -1
  101. package/dist/chunks/generate.runtime-DnWw9tL1.js.map +0 -1
  102. package/dist/chunks/generate.runtime-T9DZJH8m.js.map +0 -1
  103. package/dist/chunks/generate.runtime-Zh5n8XpR.js.map +0 -1
  104. package/dist/chunks/generate.runtime-d9HT4v-7.js.map +0 -1
  105. package/dist/chunks/generate.runtime-l-Tiahb2.js.map +0 -1
  106. package/dist/chunks/modify-file-BlWTOkCH.js.map +0 -1
package/README.md CHANGED
@@ -70,13 +70,14 @@ The `preview-modifies` directory is the mock modify output used only for preview
70
70
 
71
71
  A capability with several implementations (`vela enable analytics --provider plausible|google|posthog`) declares
72
72
  them on the pattern as `providers: [{ id, label, env }]`, in prompt order. The CLI reads that list to prompt for
73
- a provider and validate `--provider`, and asks for each declared `env` key (blank allowed). Files for each
73
+ a provider and validate `--provider`, and asks for each declared `env` key (blank allowed; a `secret: true` key,
74
+ such as `vela enable ai`'s API keys, is asked for without echo). Files for each
74
75
  provider live in `providers/<id>/**` and are bundled like `creates`; `generate.ts` picks the chosen set with
75
76
  `resolveProvider(META, options)` + `providerCreates(raw, id)` from `src/core/providers.ts`. `resolveProvider`
76
77
  reads `input.provider`, then `--provider` in argv; an unknown id is an `InvalidArgumentError` listing the known
77
78
  ones, a missing one is an error at runtime and the first provider in preview (the website loads patterns with
78
- argv only). Shared behaviour (the layout modifier, writing the env keys to `.env`) stays in the pattern's
79
- `generate.runtime.ts`. Providers are a separate dimension from `variants`.
79
+ argv only). Shared behaviour (the layout modifier, writing the env keys to `.env` with `providerEnvEdits` +
80
+ `suppliedProviderEnv`) stays in the pattern's `generate.runtime.ts`. Providers are a separate dimension from `variants`.
80
81
 
81
82
  ### Plain forms
82
83
 
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./errors-D6gyegUK.js";
2
2
  import { a as t } from "./util-BLYliuUK.js";
3
3
  import { n, t as r } from "./logger-CQONztPm.js";
4
- import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-ewxQLtse.js";
4
+ import { i, n as a, t as o } from "./pocketbase-CeG5BMN2.js";
5
5
  import { readFileSync as s } from "node:fs";
6
6
  //#region src/runtime/collections.ts
7
7
  function c(e) {
@@ -44,12 +44,12 @@ function d(e) {
44
44
  let t = {};
45
45
  return e.listRule !== void 0 && (t.listRule = e.listRule), e.viewRule !== void 0 && (t.viewRule = e.viewRule), e.createRule !== void 0 && (t.createRule = e.createRule), e.updateRule !== void 0 && (t.updateRule = e.updateRule), e.deleteRule !== void 0 && (t.deleteRule = e.deleteRule), t;
46
46
  }
47
- async function f(e, n, o, c = r) {
47
+ async function f(e, n, i, c = r) {
48
48
  let l = [];
49
49
  for (let r of n) {
50
50
  let n = r.collectionName.replace(/'/g, "''"), u = await e.collections.getFirstListItem(`name='${n}'`);
51
- if (c.info(`Updating rules on collection "${r.collectionName}"`), await e.collections.update(u.id, d(r)), await a(), o) {
52
- let e = i(r.collectionName, "updated", o);
51
+ if (c.info(`Updating rules on collection "${r.collectionName}"`), await e.collections.update(u.id, d(r)), await a(), i) {
52
+ let e = o(r.collectionName, "updated", i);
53
53
  e && l.push({
54
54
  path: e,
55
55
  language: t(e),
@@ -84,12 +84,12 @@ function p(t, n) {
84
84
  }
85
85
  return r;
86
86
  }
87
- async function m(e, n, o, c = r) {
87
+ async function m(e, n, i, c = r) {
88
88
  let l = [];
89
89
  for (let r of n) {
90
90
  let n = await e.collections.getOne(r.collectionName), u = p(n.fields, r);
91
91
  c.info(`Updating fields on collection "${r.collectionName}"`), await e.collections.update(n.id, { fields: u }), await a();
92
- let d = i(r.collectionName, "updated", o);
92
+ let d = o(r.collectionName, "updated", i);
93
93
  d && l.push({
94
94
  path: d,
95
95
  language: t(d),
@@ -151,13 +151,13 @@ async function _(e, t) {
151
151
  async function v(e, r) {
152
152
  if (e.length === 0) return [];
153
153
  let c = [], l = n(r);
154
- return await o(r.root, async (n) => {
155
- for (let o of e) {
156
- l.info(`Dropping collection "${o.name}"`);
157
- let { dropped: e } = await h(n, o.name, l);
154
+ return await i(r.root, async (n) => {
155
+ for (let i of e) {
156
+ l.info(`Dropping collection "${i.name}"`);
157
+ let { dropped: e } = await h(n, i.name, l);
158
158
  if (!e) continue;
159
159
  await a();
160
- let u = i(o.name, "deleted", r);
160
+ let u = o(i.name, "deleted", r);
161
161
  u && c.push({
162
162
  path: u,
163
163
  language: t(u),
@@ -170,13 +170,13 @@ async function v(e, r) {
170
170
  async function y(e, r) {
171
171
  if (e.length === 0) return [];
172
172
  let c = [], l = n(r);
173
- return await o(r.root, async (n) => {
174
- for (let o of e) {
175
- l.info(`Creating collection "${o.name}"`);
176
- let { created: e } = await u(n, o, l);
173
+ return await i(r.root, async (n) => {
174
+ for (let i of e) {
175
+ l.info(`Creating collection "${i.name}"`);
176
+ let { created: e } = await u(n, i, l);
177
177
  if (!e) continue;
178
178
  await a();
179
- let d = i(o.name, "created", r);
179
+ let d = o(i.name, "created", r);
180
180
  d && c.push({
181
181
  path: d,
182
182
  language: t(d),
@@ -189,4 +189,4 @@ async function y(e, r) {
189
189
  //#endregion
190
190
  export { m as applyCollectionFieldsPatches, f as applyCollectionRulePatches, u as createCollectionIdempotent, y as createCollections, v as dropCollections, _ as planCollectionDrops };
191
191
 
192
- //# sourceMappingURL=collections-CcL5bbBk.js.map
192
+ //# sourceMappingURL=collections-CgdvZXmh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collections-CcL5bbBk.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAG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,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CA+BhC,OA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
1
+ {"version":3,"file":"collections-CgdvZXmh.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAe,EACb,GACA,GACgC;CAChC,IAAM,IAAU,EAA0C,QACpD,KAAa,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAU,EAAM,SAAS,cAAc,EAAM,YAChD;CACA,IAAI,EAAU,WAAW,GAAG,OAAO;CAEnC,IAAM,IAAW,MAAM,EAAG,YAAY,YAAY,GAC5C,IAAM,IAAI,IAAI,EAAS,KAAK,MAAM,EAAE,EAAE,CAAC,GACvC,IAAS,IAAI,IAAI,EAAS,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFI,EAAU,OAAO,MAAU,EAAI,IAAI,EAAM,YAAa,CAAC,IAAU,IAE9D;EACL,GAAG;EACH,QAAQ,EAAQ,KAAK,MAAU;GAC7B,IAAI,EAAM,SAAS,cAAc,CAAC,EAAM,cAAc,OAAO;GAC7D,IAAM,IAAK,EAAO,IAAI,EAAM,YAAY;GACxC,OAAO,KAAM,CAAC,EAAI,IAAI,EAAM,YAAY,IACpC;IAAE,GAAG;IAAO,cAAc;GAAG,IAC7B;EACN,CAAC;CACH;AACF;AAaA,eAAsB,EACpB,GACA,GACA,IAA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M,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAQ,GAAO;GACxB,EAAO,KAAK,wBAAwB,EAAK,KAAK,EAAE;GAChD,IAAM,EAAE,eAAY,MAAM,EAAyB,GAAI,EAAK,MAAM,CAAM;GACxE,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,CAAO;GAC/D,KAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CA+BhC,OA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
@@ -1,4 +1,4 @@
1
- import { c as e, n as t, o as n, u as r } from "./modify-file-BlWTOkCH.js";
1
+ import { f as e, l as t, n, s as r } from "./modify-file-GQD6uNgI.js";
2
2
  import { Node as i, SyntaxKind as a, ts as o } from "ts-morph";
3
3
  //#region src/runtime/compose-handle.ts
4
4
  var s = "@sveltejs/kit/hooks", c = "handleApp";
@@ -80,9 +80,9 @@ function p(e, t) {
80
80
  moduleSpecifier: s
81
81
  });
82
82
  }
83
- function m(n) {
84
- let { wasRemoved: r } = e(n, s, "sequence");
85
- r && t(n);
83
+ function m(e) {
84
+ let { wasRemoved: r } = t(e, s, "sequence");
85
+ r && n(e);
86
86
  }
87
87
  function h(e, t) {
88
88
  if (!i.isCallExpression(e)) return !1;
@@ -190,12 +190,12 @@ function j(e) {
190
190
  reason: e
191
191
  };
192
192
  }
193
- function M(e, t) {
194
- let n = !t.inlineExport;
195
- if (t.kind === "variable" && t.statement.getDeclarations().length > 1 ? t.decl.remove() : r(e, D(t)), n) for (let t of e.getExportDeclarations()) {
196
- if (t.getModuleSpecifier() !== void 0) continue;
197
- let e = t.getNamedExports().find((e) => e.getName() === "handle");
198
- e && (t.getNamedExports().length === 1 ? t.remove() : e.remove());
193
+ function M(t, n) {
194
+ let r = !n.inlineExport;
195
+ if (n.kind === "variable" && n.statement.getDeclarations().length > 1 ? n.decl.remove() : e(t, D(n)), r) for (let e of t.getExportDeclarations()) {
196
+ if (e.getModuleSpecifier() !== void 0) continue;
197
+ let t = e.getNamedExports().find((e) => e.getName() === "handle");
198
+ t && (e.getNamedExports().length === 1 ? e.remove() : t.remove());
199
199
  }
200
200
  }
201
201
  function N(e, t, n, r, i) {
@@ -298,25 +298,25 @@ function L(e, t) {
298
298
  }
299
299
  return m(e), k(e);
300
300
  }
301
- function R(e, t, r) {
302
- let i = r.name ?? r.expression, a = l(e);
301
+ function R(e, t, n) {
302
+ let i = n.name ?? n.expression, a = l(e);
303
303
  if ("unsupported" in a) return j(a.unsupported);
304
304
  let { site: o } = a;
305
- if (!o || o.kind === "function") return F(e, r);
305
+ if (!o || o.kind === "function") return F(e, n);
306
306
  let s = u(e), c = g(o.decl.getInitializerOrThrow());
307
307
  if (_(c, i) || v(c, i, s)) return _(c, t) || v(c, t, s) ? L(e, t) : A(o);
308
- if (_(c, t)) return c.replaceWithText(r.expression), n(e, e.getVariableStatementOrThrow("handle")), k(e);
308
+ if (_(c, t)) return c.replaceWithText(n.expression), r(e, e.getVariableStatementOrThrow("handle")), k(e);
309
309
  let d = v(c, t, s);
310
310
  if (d) {
311
- let t = d.calls[d.calls.length - 1], n = x(t);
312
- return n[d.index] = {
313
- ...n[d.index],
314
- text: r.expression
315
- }, E(t, n), k(e);
311
+ let t = d.calls[d.calls.length - 1], r = x(t);
312
+ return r[d.index] = {
313
+ ...r[d.index],
314
+ text: n.expression
315
+ }, E(t, r), k(e);
316
316
  }
317
- return y(c, t) ? j("ambiguous-reference") : F(e, r);
317
+ return y(c, t) ? j("ambiguous-reference") : F(e, n);
318
318
  }
319
319
  //#endregion
320
320
  export { L as n, R as r, F as t };
321
321
 
322
- //# sourceMappingURL=compose-handle-D16KmBVd.js.map
322
+ //# sourceMappingURL=compose-handle-Cg9jnCsS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compose-handle-D16KmBVd.js","names":[],"sources":["../../src/runtime/compose-handle.ts"],"sourcesContent":["import {\n Node,\n SyntaxKind,\n ts,\n type CallExpression,\n type Expression,\n type FunctionDeclaration,\n type SourceFile,\n type Statement,\n type VariableDeclaration,\n type VariableStatement,\n} from \"ts-morph\";\nimport {\n ensureBlankLineAfterImports,\n removeAttachedComments,\n removeNamedImportIfUnused,\n removeStatementWithComments,\n} from \"./ts-morph-helpers\";\n\n/**\n * Composes the server `handle` hook in `hooks.server.ts`.\n *\n * Patterns add and subtract handles in the exported `handle` without caring\n * what shape it is in: a lone expression becomes `sequence(new, old)`, a\n * `sequence(...)` gains or loses an argument, and a handle that is a function\n * is moved to a local `handleApp` so it can take part. Subtracting back to one\n * handle unwraps the `sequence` again, and puts a `handleApp` back the way it\n * was written, so enabling then disabling a pattern round-trips.\n *\n * Nothing here formats or saves: callers do, as they always have. A result of\n * `unsupported` means the file was left exactly as it was found.\n */\n\nconst KIT_HOOKS = \"@sveltejs/kit/hooks\";\nconst EXTRACTED = \"handleApp\";\n\nexport interface HandleSpec {\n /** Source text of the sequence argument: `handleWuchale`, `handlePocketbase({ ... })`. */\n expression: string;\n /** Identifier, or callee identifier, that marks this handle. Defaults to `expression`. */\n name?: string;\n /** Where it goes in the chain. */\n position?: \"first\" | \"last\";\n}\n\nexport type Unsupported =\n /** `export { handle } from '…'`, `export { x as handle }`, or `export *` with no local handle. */\n | \"re-export\"\n /** A local `handle` SvelteKit cannot see. */\n | \"not-exported\"\n /** `export const { handle } = …` */\n | \"destructured\"\n /** `export default function handle` */\n | \"default-export\"\n /** `export let handle;` */\n | \"no-initializer\"\n /** A `sequence` in scope that is not `@sveltejs/kit/hooks`'. */\n | \"foreign-sequence\"\n /** The handle has to move to `handleApp`, and the name is taken. */\n | \"name-collision\"\n /** The handle has to move to `handleApp`, and shares its statement with other declarations. */\n | \"multi-declarator\"\n /** The handle is referenced outside the composition (`dev ? a : handleX`, or inside a function handle). */\n | \"ambiguous-reference\";\n\nexport type ComposeResult =\n /** `statement` is the `handle` declaration, when there still is one. */\n | { status: \"changed\"; statement?: Statement }\n | { status: \"unchanged\"; statement?: Statement }\n | { status: \"unsupported\"; reason: Unsupported };\n\ntype Site =\n | {\n kind: \"variable\";\n decl: VariableDeclaration;\n statement: VariableStatement;\n inlineExport: boolean;\n }\n | { kind: \"function\"; fn: FunctionDeclaration; inlineExport: boolean };\n\ntype Located =\n { site: Site | null; starExport: boolean } | { unsupported: Unsupported };\n\n/** A `sequence(...)` argument with the comments that belong to it. */\ninterface Piece {\n leading: string[];\n text: string;\n trailing: string[];\n}\n\n/** How `sequence` from `@sveltejs/kit/hooks` is bound in this file, if at all. */\ninterface KitSequence {\n local: string | null;\n namespace: string | null;\n}\n\n/** Find the exported `handle`, or say why it cannot be composed. */\nfunction locate(sf: SourceFile): Located {\n let exportedBySpecifier = false;\n let starExport = false;\n\n for (const ed of sf.getExportDeclarations()) {\n const fromModule = ed.getModuleSpecifier() !== undefined;\n if (ed.isNamespaceExport()) {\n if (ed.getNamespaceExport()?.getName() === \"handle\") {\n return { unsupported: \"re-export\" };\n }\n if (fromModule) starExport = true;\n continue;\n }\n for (const spec of ed.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== \"handle\") continue;\n if (fromModule || spec.getName() !== \"handle\") {\n return { unsupported: \"re-export\" };\n }\n exportedBySpecifier = true;\n }\n }\n\n const fn = sf.getFunctions().find((f) => f.getName() === \"handle\");\n if (fn) {\n if (fn.isDefaultExport()) return { unsupported: \"default-export\" };\n if (!fn.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n return {\n site: { kind: \"function\", fn, inlineExport: fn.hasExportKeyword() },\n starExport,\n };\n }\n\n for (const statement of sf.getVariableStatements()) {\n for (const decl of statement.getDeclarations()) {\n const nameNode = decl.getNameNode();\n if (!Node.isIdentifier(nameNode)) {\n const bindsHandle = nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === \"handle\");\n if (bindsHandle) return { unsupported: \"destructured\" };\n continue;\n }\n if (nameNode.getText() !== \"handle\") continue;\n if (!statement.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n if (!decl.getInitializer()) return { unsupported: \"no-initializer\" };\n return {\n site: {\n kind: \"variable\",\n decl,\n statement,\n inlineExport: statement.hasExportKeyword(),\n },\n starExport,\n };\n }\n }\n\n // `export { handle }` naming something that is not a local variable or\n // function: an import passed straight through, or a class.\n if (exportedBySpecifier) return { unsupported: \"re-export\" };\n return { site: null, starExport };\n}\n\nfunction kitSequence(sf: SourceFile): KitSequence {\n const found: KitSequence = { local: null, namespace: null };\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getModuleSpecifierValue() !== KIT_HOOKS || decl.isTypeOnly()) {\n continue;\n }\n const namespace = decl.getNamespaceImport();\n if (namespace) found.namespace = namespace.getText();\n for (const named of decl.getNamedImports()) {\n if (named.getName() !== \"sequence\" || named.isTypeOnly()) continue;\n found.local = named.getAliasNode()?.getText() ?? \"sequence\";\n }\n }\n return found;\n}\n\n/** Whether `name` is declared at the top level or imported. */\nfunction isBound(sf: SourceFile, name: string): boolean {\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getDefaultImport()?.getText() === name) return true;\n if (decl.getNamespaceImport()?.getText() === name) return true;\n for (const named of decl.getNamedImports()) {\n if ((named.getAliasNode()?.getText() ?? named.getName()) === name) {\n return true;\n }\n }\n }\n if (sf.getFunction(name) || sf.getClass(name) || sf.getEnum(name)) {\n return true;\n }\n return sf.getVariableDeclarations().some((d) => {\n const nameNode = d.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;\n return nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === name);\n });\n}\n\n/** The callee to write for a new `sequence(...)`, or null when none can be had. */\nfunction sequenceCallee(sf: SourceFile, kit: KitSequence): string | null {\n if (kit.local) return kit.local;\n if (kit.namespace) return `${kit.namespace}.sequence`;\n return isBound(sf, \"sequence\") ? null : \"sequence\";\n}\n\nfunction ensureSequenceImport(sf: SourceFile, kit: KitSequence): void {\n if (kit.local || kit.namespace) return;\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n !d.isTypeOnly() &&\n !d.getNamespaceImport(),\n );\n if (decl) decl.addNamedImport(\"sequence\");\n else {\n sf.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: KIT_HOOKS,\n });\n }\n}\n\nfunction pruneSequenceImport(sf: SourceFile): void {\n // ts-morph takes the blank line after the imports with a removed import.\n const { wasRemoved } = removeNamedImportIfUnused(sf, KIT_HOOKS, \"sequence\");\n if (wasRemoved) ensureBlankLineAfterImports(sf);\n}\n\nfunction isSequenceCall(node: Node, kit: KitSequence): node is CallExpression {\n if (!Node.isCallExpression(node)) return false;\n const callee = node.getExpression();\n if (Node.isIdentifier(callee)) return callee.getText() === kit.local;\n if (Node.isPropertyAccessExpression(callee)) {\n return (\n kit.namespace !== null &&\n callee.getExpression().getText() === kit.namespace &&\n callee.getName() === \"sequence\"\n );\n }\n return false;\n}\n\n/** Strip `( )`, `satisfies T`, `as T`, `<T>` and `!` down to the composition. */\nfunction unwrap(node: Expression): Expression {\n for (;;) {\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)\n ) {\n node = node.getExpression();\n } else {\n return node;\n }\n }\n}\n\n/** `name`, or a call of `name`: `handleWuchale`, `handlePocketbase({ ... })`. */\nfunction isHandle(node: Node, name: string): boolean {\n if (Node.isIdentifier(node)) return node.getText() === name;\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n return Node.isIdentifier(callee) && callee.getText() === name;\n }\n return false;\n}\n\n/** The chain of `sequence` calls down to the argument that is `name`. */\nfunction findInSequence(\n node: Node,\n name: string,\n kit: KitSequence,\n): { calls: CallExpression[]; index: number } | null {\n if (!isSequenceCall(node, kit)) return null;\n const args = node.getArguments();\n const index = args.findIndex((arg) => isHandle(arg, name));\n if (index >= 0) return { calls: [node], index };\n for (const arg of args) {\n const inner = findInSequence(arg, name, kit);\n if (inner) return { calls: [node, ...inner.calls], index: inner.index };\n }\n return null;\n}\n\nfunction references(node: Node, name: string): boolean {\n if (Node.isIdentifier(node) && node.getText() === name) return true;\n return node\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name);\n}\n\nfunction commentTexts(text: string, ranges: ts.CommentRange[]): string[] {\n return ranges.map((r) => text.slice(r.pos, r.end));\n}\n\n/**\n * The arguments of a `sequence(...)` call, each with its comments. A comment\n * after an argument's comma on the same line is that argument's; comments on\n * the lines above an argument are its own too.\n */\nfunction pieces(call: CallExpression): Piece[] {\n const text = call.getSourceFile().getFullText();\n const args = call.getArguments();\n const openParen = call.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken);\n const closeParen = call.getLastChildByKindOrThrow(SyntaxKind.CloseParenToken);\n\n const result = args.map((arg, i): Piece => {\n let leadingFrom = openParen.getEnd();\n if (i > 0) {\n const prevComma = args[i - 1].getNextSiblingIfKind(SyntaxKind.CommaToken);\n leadingFrom = prevComma?.getEnd() ?? args[i - 1].getEnd();\n const prevTrailing = ts.getTrailingCommentRanges(text, leadingFrom);\n if (prevTrailing?.length) {\n leadingFrom = prevTrailing[prevTrailing.length - 1].end;\n }\n }\n const leading = (\n ts.getLeadingCommentRanges(text, leadingFrom) ?? []\n ).filter((r) => r.end <= arg.getStart());\n const comma = arg.getNextSiblingIfKind(SyntaxKind.CommaToken);\n const trailing =\n ts.getTrailingCommentRanges(text, comma?.getEnd() ?? arg.getEnd()) ?? [];\n return {\n leading: commentTexts(text, leading),\n text: arg.getText(),\n trailing: commentTexts(text, trailing),\n };\n });\n\n // Comments on their own lines just before `)` go with the last argument.\n const last = result[result.length - 1];\n if (last) {\n const lastArg = args[args.length - 1];\n let from =\n lastArg.getNextSiblingIfKind(SyntaxKind.CommaToken)?.getEnd() ??\n lastArg.getEnd();\n const sameLine = ts.getTrailingCommentRanges(text, from);\n if (sameLine?.length) from = sameLine[sameLine.length - 1].end;\n const dangling = (ts.getLeadingCommentRanges(text, from) ?? []).filter(\n (r) => r.end <= closeParen.getStart(),\n );\n last.trailing.push(...commentTexts(text, dangling));\n }\n return result;\n}\n\nfunction hasComments(list: Piece[]): boolean {\n return list.some((p) => p.leading.length > 0 || p.trailing.length > 0);\n}\n\nfunction renderCall(callee: string, list: Piece[], multiline: boolean): string {\n if (!multiline && !hasComments(list)) {\n return `${callee}(${list.map((p) => p.text).join(\", \")})`;\n }\n const lines = list.map((p) => {\n const leading = p.leading.map((c) => `${c}\\n`).join(\"\");\n const trailing = p.trailing.length ? ` ${p.trailing.join(\" \")}` : \"\";\n return `${leading}${p.text},${trailing}`;\n });\n return `${callee}(\\n${lines.join(\"\\n\")}\\n)`;\n}\n\n/** A lone argument taken out of a nested `sequence`: its comments go above it. */\nfunction renderAlone(piece: Piece): string {\n const comments = [...piece.leading, ...piece.trailing];\n return comments.map((c) => `${c}\\n`).join(\"\") + piece.text;\n}\n\nfunction isMultiline(call: CallExpression): boolean {\n return call\n .getArguments()\n .some((arg, i, args) =>\n i === 0\n ? false\n : arg.getStartLineNumber() !== args[i - 1].getEndLineNumber(),\n );\n}\n\nfunction rewriteSequence(call: CallExpression, list: Piece[]): Node {\n const multiline = isMultiline(call);\n return call.replaceWithText(\n renderCall(call.getExpression().getText(), list, multiline),\n );\n}\n\nfunction handleStatement(site: Site): Statement {\n return site.kind === \"function\" ? site.fn : site.statement;\n}\n\n/** The `handle` statement as it stands now; nodes go stale on every edit. */\nfunction currentStatement(sf: SourceFile): Statement | undefined {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return undefined;\n return handleStatement(located.site);\n}\n\nfunction changed(sf: SourceFile): ComposeResult {\n return { status: \"changed\", statement: currentStatement(sf) };\n}\n\nfunction unchanged(site: Site | null): ComposeResult {\n return {\n status: \"unchanged\",\n statement: site ? handleStatement(site) : undefined,\n };\n}\n\nfunction unsupported(reason: Unsupported): ComposeResult {\n return { status: \"unsupported\", reason };\n}\n\n/**\n * Take the whole `handle` out: its declarator, or its statement with the\n * comments above it, and an `export { handle }` naming it.\n */\nfunction removeWholeHandle(sf: SourceFile, site: Site): void {\n const viaSpecifier = !site.inlineExport;\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n site.decl.remove();\n } else {\n removeStatementWithComments(sf, handleStatement(site));\n }\n if (!viaSpecifier) return;\n for (const ed of sf.getExportDeclarations()) {\n if (ed.getModuleSpecifier() !== undefined) continue;\n const spec = ed.getNamedExports().find((s) => s.getName() === \"handle\");\n if (!spec) continue;\n if (ed.getNamedExports().length === 1) ed.remove();\n else spec.remove();\n }\n}\n\n/**\n * Move a handle that is a function out of the way: rename it `handleApp`,\n * un-export it, and export `sequence(...)` of it right after, so `handleApp`\n * is declared before anything reads it.\n */\nfunction extract(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n callee: string,\n kit: KitSequence,\n): ComposeResult {\n const position = spec.position ?? \"first\";\n const args =\n position === \"first\"\n ? [spec.expression, EXTRACTED]\n : [EXTRACTED, spec.expression];\n const exportKeyword = site.inlineExport ? \"export \" : \"\";\n const composed = `${exportKeyword}const handle = ${callee}(${args.join(\", \")});`;\n\n if (site.kind === \"function\") {\n if (site.inlineExport) site.fn.setIsExported(false);\n sf.getFunctionOrThrow(\"handle\").getNameNode()!.replaceWithText(EXTRACTED);\n const fn = sf.getFunctionOrThrow(EXTRACTED);\n sf.insertText(fn.getEnd(), `\\n\\n${composed}`);\n } else {\n if (site.inlineExport) site.statement.setIsExported(false);\n sf.getVariableDeclarationOrThrow(\"handle\")\n .getNameNode()\n .replaceWithText(EXTRACTED);\n const statement = sf.getVariableStatementOrThrow(EXTRACTED);\n sf.insertText(statement.getEnd(), `\\n\\n${composed}`);\n }\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\n/**\n * After a `sequence` unwraps to `handleApp` alone, put the function back the\n * way `extract` found it: `handleApp` renamed to `handle` and exported, and\n * the `handle = handleApp` statement gone.\n */\nfunction restoreExtracted(sf: SourceFile): void {\n const located = locate(sf);\n if (\"unsupported\" in located || located.site?.kind !== \"variable\") return;\n const { decl, statement, inlineExport } = located.site;\n const init = decl.getInitializer();\n if (\n !init ||\n !Node.isIdentifier(init) ||\n init.getText() !== EXTRACTED ||\n decl.getTypeNode() ||\n statement.getDeclarations().length > 1\n ) {\n return;\n }\n\n const uses = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .filter((id) => id.getText() === EXTRACTED);\n // Its declaration and the one use in `handle`.\n if (uses.length !== 2) return;\n\n const fn = sf.getFunction(EXTRACTED);\n const variable = sf.getVariableStatements().find((s) => {\n const decls = s.getDeclarations();\n return decls.length === 1 && decls[0].getName() === EXTRACTED;\n });\n const target = fn ?? variable;\n if (!target || target.hasExportKeyword()) return;\n\n statement.remove();\n if (fn) {\n const restored = sf.getFunctionOrThrow(EXTRACTED);\n restored.getNameNode()!.replaceWithText(\"handle\");\n if (inlineExport) sf.getFunctionOrThrow(\"handle\").setIsExported(true);\n } else {\n const restored = sf.getVariableDeclarationOrThrow(EXTRACTED);\n restored.getNameNode().replaceWithText(\"handle\");\n if (inlineExport) {\n sf.getVariableStatementOrThrow(\"handle\").setIsExported(true);\n }\n }\n}\n\n/**\n * Add a handle to the exported `handle`. Already present anywhere in the\n * composition: unchanged. No `handle` yet: `export const handle = <expression>`.\n */\nexport function addHandle(sf: SourceFile, spec: HandleSpec): ComposeResult {\n const name = spec.name ?? spec.expression;\n const position = spec.position ?? \"first\";\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n const kit = kitSequence(sf);\n\n if (!site) {\n if (located.starExport) return unsupported(\"re-export\");\n const blank = sf.getStatementsWithComments().length > 0 ? \"\\n\" : \"\";\n sf.addStatements(`${blank}export const handle = ${spec.expression};`);\n return changed(sf);\n }\n\n if (site.kind === \"function\") {\n if (references(site.fn, name)) return unsupported(\"ambiguous-reference\");\n return extractChecked(sf, site, spec, kit);\n }\n\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name) || findInSequence(core, name, kit)) {\n return unchanged(site);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n\n if (isSequenceCall(core, kit)) {\n const list = pieces(core);\n const piece: Piece = { leading: [], text: spec.expression, trailing: [] };\n if (position === \"first\") list.unshift(piece);\n else list.push(piece);\n rewriteSequence(core, list);\n return changed(sf);\n }\n\n if (Node.isArrowFunction(core) || Node.isFunctionExpression(core)) {\n return extractChecked(sf, site, spec, kit);\n }\n\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const existing = core.getText();\n const args =\n position === \"first\"\n ? [spec.expression, existing]\n : [existing, spec.expression];\n const multiline = args.some((a) => a.includes(\"\\n\"));\n core.replaceWithText(\n renderCall(\n callee,\n args.map((text) => ({ leading: [], text, trailing: [] })),\n multiline,\n ),\n );\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\nfunction extractChecked(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n kit: KitSequence,\n): ComposeResult {\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const taken = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === EXTRACTED);\n if (taken) return unsupported(\"name-collision\");\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n return unsupported(\"multi-declarator\");\n }\n return extract(sf, site, spec, callee, kit);\n}\n\n/**\n * Take a handle out of the exported `handle`. A `sequence` left with one\n * argument unwraps to it; the last handle takes the `handle` export with it.\n */\nexport function removeHandle(sf: SourceFile, name: string): ComposeResult {\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site) return unchanged(null);\n\n if (site.kind === \"function\") {\n return references(site.fn, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name)) {\n removeWholeHandle(sf, site);\n pruneSequenceImport(sf);\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (!found) {\n return references(core, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n // Innermost call first; a nested `sequence` emptied by the removal is in\n // turn removed from the one around it.\n const calls = [...found.calls];\n let index = found.index;\n for (;;) {\n const call = calls.pop()!;\n const list = pieces(call);\n list.splice(index, 1);\n const outer = calls[calls.length - 1];\n\n if (list.length === 0) {\n if (!outer) {\n removeWholeHandle(sf, site);\n break;\n }\n index = outer.getArguments().indexOf(call);\n continue;\n }\n if (list.length === 1 && outer) {\n call.replaceWithText(renderAlone(list[0]));\n break;\n }\n if (list.length === 1) {\n // `handle = sequence(x)` unwraps to `handle = x`, and x's comments move\n // above the statement rather than dangle after the `=`.\n const [kept] = list;\n const comments = [...kept.leading, ...kept.trailing];\n call.replaceWithText(kept.text);\n if (comments.length === 0) restoreExtracted(sf);\n else {\n const statement = currentStatement(sf)!;\n sf.insertText(\n statement.getStart(true),\n comments.map((c) => `${c}\\n`).join(\"\"),\n );\n }\n break;\n }\n rewriteSequence(call, list);\n break;\n }\n\n pruneSequenceImport(sf);\n return changed(sf);\n}\n\n/**\n * Swap handle `name` for `spec` in the same place in the chain. When `name`\n * was the whole `handle`, the comments above the statement go too: they\n * described the old handle. With `name` absent this is `addHandle`.\n */\nexport function replaceHandle(\n sf: SourceFile,\n name: string,\n spec: HandleSpec,\n): ComposeResult {\n const newName = spec.name ?? spec.expression;\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site || site.kind === \"function\") return addHandle(sf, spec);\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, newName) || findInSequence(core, newName, kit)) {\n const stale = isHandle(core, name) || findInSequence(core, name, kit);\n return stale ? removeHandle(sf, name) : unchanged(site);\n }\n\n if (isHandle(core, name)) {\n core.replaceWithText(spec.expression);\n removeAttachedComments(sf, sf.getVariableStatementOrThrow(\"handle\"));\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (found) {\n const call = found.calls[found.calls.length - 1];\n const list = pieces(call);\n list[found.index] = { ...list[found.index], text: spec.expression };\n rewriteSequence(call, list);\n return changed(sf);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n return addHandle(sf, spec);\n}\n\n/**\n * The handles in the exported `handle`, in order: each argument's identifier,\n * or its callee's, or its source text. A function handle is `handle` itself.\n * `null` when there is no `handle` to compose.\n */\nexport function listHandles(sf: SourceFile): string[] | null {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return null;\n if (located.site.kind === \"function\") return [\"handle\"];\n const kit = kitSequence(sf);\n\n const names = (node: Node): string[] => {\n if (isSequenceCall(node, kit)) return node.getArguments().flatMap(names);\n if (Node.isIdentifier(node)) return [node.getText()];\n if (\n Node.isCallExpression(node) &&\n Node.isIdentifier(node.getExpression())\n ) {\n return [node.getExpression().getText()];\n }\n return [node.getText()];\n };\n return names(unwrap(located.site.decl.getInitializerOrThrow()));\n}\n"],"mappings":";;;AAiCA,IAAM,IAAY,uBACZ,IAAY;AA+DlB,SAAS,EAAO,GAAyB;CACvC,IAAI,IAAsB,IACtB,IAAa;CAEjB,KAAK,IAAM,KAAM,EAAG,sBAAsB,GAAG;EAC3C,IAAM,IAAa,EAAG,mBAAmB,MAAM,KAAA;EAC/C,IAAI,EAAG,kBAAkB,GAAG;GAC1B,IAAI,EAAG,mBAAmB,CAAC,EAAE,QAAQ,MAAM,UACzC,OAAO,EAAE,aAAa,YAAY;GAEpC,AAAI,MAAY,IAAa;GAC7B;EACF;EACA,KAAK,IAAM,KAAQ,EAAG,gBAAgB,GAEpC,KADiB,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAK,EAAK,QAAQ,OAC/C,UACjB;OAAI,KAAc,EAAK,QAAQ,MAAM,UACnC,OAAO,EAAE,aAAa,YAAY;GAEpC,IAAsB;EAFc;CAIxC;CAEA,IAAM,IAAK,EAAG,aAAa,CAAC,CAAC,MAAM,MAAM,EAAE,QAAQ,MAAM,QAAQ;CACjE,IAAI,GAKF,OAJI,EAAG,gBAAgB,IAAU,EAAE,aAAa,iBAAiB,IAC7D,CAAC,EAAG,iBAAiB,KAAK,CAAC,IACtB,EAAE,aAAa,eAAe,IAEhC;EACL,MAAM;GAAE,MAAM;GAAY;GAAI,cAAc,EAAG,iBAAiB;EAAE;EAClE;CACF;CAGF,KAAK,IAAM,KAAa,EAAG,sBAAsB,GAC/C,KAAK,IAAM,KAAQ,EAAU,gBAAgB,GAAG;EAC9C,IAAM,IAAW,EAAK,YAAY;EAClC,IAAI,CAAC,EAAK,aAAa,CAAQ,GAAG;GAIhC,IAHoB,EACjB,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,YAAY,CAAC,CAAC,QAAQ,MAAM,QAC3C,GAAa,OAAO,EAAE,aAAa,eAAe;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AC5D,EAAQ,CAAE;CAGnB,IAAM,IAAQ,EAAe,GAAM,GAAM,CAAG;CAC5C,IAAI,GAAO;EACT,IAAM,IAAO,EAAM,MAAM,EAAM,MAAM,SAAS,IACxC,IAAO,EAAO,CAAI;EAGxB,OAFA,EAAK,EAAM,SAAS;GAAE,GAAG,EAAK,EAAM;GAAQ,MAAM,EAAK;EAAW,GAClE,EAAgB,GAAM,CAAI,GACnB,EAAQ,CAAE;CACnB;CAEA,OADI,EAAW,GAAM,CAAI,IAAU,EAAY,qBAAqB,IAC7D,EAAU,GAAI,CAAI;AAC3B"}
1
+ {"version":3,"file":"compose-handle-Cg9jnCsS.js","names":[],"sources":["../../src/runtime/compose-handle.ts"],"sourcesContent":["import {\n Node,\n SyntaxKind,\n ts,\n type CallExpression,\n type Expression,\n type FunctionDeclaration,\n type SourceFile,\n type Statement,\n type VariableDeclaration,\n type VariableStatement,\n} from \"ts-morph\";\nimport {\n ensureBlankLineAfterImports,\n removeAttachedComments,\n removeNamedImportIfUnused,\n removeStatementWithComments,\n} from \"./ts-morph-helpers\";\n\n/**\n * Composes the server `handle` hook in `hooks.server.ts`.\n *\n * Patterns add and subtract handles in the exported `handle` without caring\n * what shape it is in: a lone expression becomes `sequence(new, old)`, a\n * `sequence(...)` gains or loses an argument, and a handle that is a function\n * is moved to a local `handleApp` so it can take part. Subtracting back to one\n * handle unwraps the `sequence` again, and puts a `handleApp` back the way it\n * was written, so enabling then disabling a pattern round-trips.\n *\n * Nothing here formats or saves: callers do, as they always have. A result of\n * `unsupported` means the file was left exactly as it was found.\n */\n\nconst KIT_HOOKS = \"@sveltejs/kit/hooks\";\nconst EXTRACTED = \"handleApp\";\n\nexport interface HandleSpec {\n /** Source text of the sequence argument: `handleWuchale`, `handlePocketbase({ ... })`. */\n expression: string;\n /** Identifier, or callee identifier, that marks this handle. Defaults to `expression`. */\n name?: string;\n /** Where it goes in the chain. */\n position?: \"first\" | \"last\";\n}\n\nexport type Unsupported =\n /** `export { handle } from '…'`, `export { x as handle }`, or `export *` with no local handle. */\n | \"re-export\"\n /** A local `handle` SvelteKit cannot see. */\n | \"not-exported\"\n /** `export const { handle } = …` */\n | \"destructured\"\n /** `export default function handle` */\n | \"default-export\"\n /** `export let handle;` */\n | \"no-initializer\"\n /** A `sequence` in scope that is not `@sveltejs/kit/hooks`'. */\n | \"foreign-sequence\"\n /** The handle has to move to `handleApp`, and the name is taken. */\n | \"name-collision\"\n /** The handle has to move to `handleApp`, and shares its statement with other declarations. */\n | \"multi-declarator\"\n /** The handle is referenced outside the composition (`dev ? a : handleX`, or inside a function handle). */\n | \"ambiguous-reference\";\n\nexport type ComposeResult =\n /** `statement` is the `handle` declaration, when there still is one. */\n | { status: \"changed\"; statement?: Statement }\n | { status: \"unchanged\"; statement?: Statement }\n | { status: \"unsupported\"; reason: Unsupported };\n\ntype Site =\n | {\n kind: \"variable\";\n decl: VariableDeclaration;\n statement: VariableStatement;\n inlineExport: boolean;\n }\n | { kind: \"function\"; fn: FunctionDeclaration; inlineExport: boolean };\n\ntype Located =\n { site: Site | null; starExport: boolean } | { unsupported: Unsupported };\n\n/** A `sequence(...)` argument with the comments that belong to it. */\ninterface Piece {\n leading: string[];\n text: string;\n trailing: string[];\n}\n\n/** How `sequence` from `@sveltejs/kit/hooks` is bound in this file, if at all. */\ninterface KitSequence {\n local: string | null;\n namespace: string | null;\n}\n\n/** Find the exported `handle`, or say why it cannot be composed. */\nfunction locate(sf: SourceFile): Located {\n let exportedBySpecifier = false;\n let starExport = false;\n\n for (const ed of sf.getExportDeclarations()) {\n const fromModule = ed.getModuleSpecifier() !== undefined;\n if (ed.isNamespaceExport()) {\n if (ed.getNamespaceExport()?.getName() === \"handle\") {\n return { unsupported: \"re-export\" };\n }\n if (fromModule) starExport = true;\n continue;\n }\n for (const spec of ed.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== \"handle\") continue;\n if (fromModule || spec.getName() !== \"handle\") {\n return { unsupported: \"re-export\" };\n }\n exportedBySpecifier = true;\n }\n }\n\n const fn = sf.getFunctions().find((f) => f.getName() === \"handle\");\n if (fn) {\n if (fn.isDefaultExport()) return { unsupported: \"default-export\" };\n if (!fn.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n return {\n site: { kind: \"function\", fn, inlineExport: fn.hasExportKeyword() },\n starExport,\n };\n }\n\n for (const statement of sf.getVariableStatements()) {\n for (const decl of statement.getDeclarations()) {\n const nameNode = decl.getNameNode();\n if (!Node.isIdentifier(nameNode)) {\n const bindsHandle = nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === \"handle\");\n if (bindsHandle) return { unsupported: \"destructured\" };\n continue;\n }\n if (nameNode.getText() !== \"handle\") continue;\n if (!statement.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n if (!decl.getInitializer()) return { unsupported: \"no-initializer\" };\n return {\n site: {\n kind: \"variable\",\n decl,\n statement,\n inlineExport: statement.hasExportKeyword(),\n },\n starExport,\n };\n }\n }\n\n // `export { handle }` naming something that is not a local variable or\n // function: an import passed straight through, or a class.\n if (exportedBySpecifier) return { unsupported: \"re-export\" };\n return { site: null, starExport };\n}\n\nfunction kitSequence(sf: SourceFile): KitSequence {\n const found: KitSequence = { local: null, namespace: null };\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getModuleSpecifierValue() !== KIT_HOOKS || decl.isTypeOnly()) {\n continue;\n }\n const namespace = decl.getNamespaceImport();\n if (namespace) found.namespace = namespace.getText();\n for (const named of decl.getNamedImports()) {\n if (named.getName() !== \"sequence\" || named.isTypeOnly()) continue;\n found.local = named.getAliasNode()?.getText() ?? \"sequence\";\n }\n }\n return found;\n}\n\n/** Whether `name` is declared at the top level or imported. */\nfunction isBound(sf: SourceFile, name: string): boolean {\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getDefaultImport()?.getText() === name) return true;\n if (decl.getNamespaceImport()?.getText() === name) return true;\n for (const named of decl.getNamedImports()) {\n if ((named.getAliasNode()?.getText() ?? named.getName()) === name) {\n return true;\n }\n }\n }\n if (sf.getFunction(name) || sf.getClass(name) || sf.getEnum(name)) {\n return true;\n }\n return sf.getVariableDeclarations().some((d) => {\n const nameNode = d.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;\n return nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === name);\n });\n}\n\n/** The callee to write for a new `sequence(...)`, or null when none can be had. */\nfunction sequenceCallee(sf: SourceFile, kit: KitSequence): string | null {\n if (kit.local) return kit.local;\n if (kit.namespace) return `${kit.namespace}.sequence`;\n return isBound(sf, \"sequence\") ? null : \"sequence\";\n}\n\nfunction ensureSequenceImport(sf: SourceFile, kit: KitSequence): void {\n if (kit.local || kit.namespace) return;\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n !d.isTypeOnly() &&\n !d.getNamespaceImport(),\n );\n if (decl) decl.addNamedImport(\"sequence\");\n else {\n sf.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: KIT_HOOKS,\n });\n }\n}\n\nfunction pruneSequenceImport(sf: SourceFile): void {\n // ts-morph takes the blank line after the imports with a removed import.\n const { wasRemoved } = removeNamedImportIfUnused(sf, KIT_HOOKS, \"sequence\");\n if (wasRemoved) ensureBlankLineAfterImports(sf);\n}\n\nfunction isSequenceCall(node: Node, kit: KitSequence): node is CallExpression {\n if (!Node.isCallExpression(node)) return false;\n const callee = node.getExpression();\n if (Node.isIdentifier(callee)) return callee.getText() === kit.local;\n if (Node.isPropertyAccessExpression(callee)) {\n return (\n kit.namespace !== null &&\n callee.getExpression().getText() === kit.namespace &&\n callee.getName() === \"sequence\"\n );\n }\n return false;\n}\n\n/** Strip `( )`, `satisfies T`, `as T`, `<T>` and `!` down to the composition. */\nfunction unwrap(node: Expression): Expression {\n for (;;) {\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)\n ) {\n node = node.getExpression();\n } else {\n return node;\n }\n }\n}\n\n/** `name`, or a call of `name`: `handleWuchale`, `handlePocketbase({ ... })`. */\nfunction isHandle(node: Node, name: string): boolean {\n if (Node.isIdentifier(node)) return node.getText() === name;\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n return Node.isIdentifier(callee) && callee.getText() === name;\n }\n return false;\n}\n\n/** The chain of `sequence` calls down to the argument that is `name`. */\nfunction findInSequence(\n node: Node,\n name: string,\n kit: KitSequence,\n): { calls: CallExpression[]; index: number } | null {\n if (!isSequenceCall(node, kit)) return null;\n const args = node.getArguments();\n const index = args.findIndex((arg) => isHandle(arg, name));\n if (index >= 0) return { calls: [node], index };\n for (const arg of args) {\n const inner = findInSequence(arg, name, kit);\n if (inner) return { calls: [node, ...inner.calls], index: inner.index };\n }\n return null;\n}\n\nfunction references(node: Node, name: string): boolean {\n if (Node.isIdentifier(node) && node.getText() === name) return true;\n return node\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name);\n}\n\nfunction commentTexts(text: string, ranges: ts.CommentRange[]): string[] {\n return ranges.map((r) => text.slice(r.pos, r.end));\n}\n\n/**\n * The arguments of a `sequence(...)` call, each with its comments. A comment\n * after an argument's comma on the same line is that argument's; comments on\n * the lines above an argument are its own too.\n */\nfunction pieces(call: CallExpression): Piece[] {\n const text = call.getSourceFile().getFullText();\n const args = call.getArguments();\n const openParen = call.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken);\n const closeParen = call.getLastChildByKindOrThrow(SyntaxKind.CloseParenToken);\n\n const result = args.map((arg, i): Piece => {\n let leadingFrom = openParen.getEnd();\n if (i > 0) {\n const prevComma = args[i - 1].getNextSiblingIfKind(SyntaxKind.CommaToken);\n leadingFrom = prevComma?.getEnd() ?? args[i - 1].getEnd();\n const prevTrailing = ts.getTrailingCommentRanges(text, leadingFrom);\n if (prevTrailing?.length) {\n leadingFrom = prevTrailing[prevTrailing.length - 1].end;\n }\n }\n const leading = (\n ts.getLeadingCommentRanges(text, leadingFrom) ?? []\n ).filter((r) => r.end <= arg.getStart());\n const comma = arg.getNextSiblingIfKind(SyntaxKind.CommaToken);\n const trailing =\n ts.getTrailingCommentRanges(text, comma?.getEnd() ?? arg.getEnd()) ?? [];\n return {\n leading: commentTexts(text, leading),\n text: arg.getText(),\n trailing: commentTexts(text, trailing),\n };\n });\n\n // Comments on their own lines just before `)` go with the last argument.\n const last = result[result.length - 1];\n if (last) {\n const lastArg = args[args.length - 1];\n let from =\n lastArg.getNextSiblingIfKind(SyntaxKind.CommaToken)?.getEnd() ??\n lastArg.getEnd();\n const sameLine = ts.getTrailingCommentRanges(text, from);\n if (sameLine?.length) from = sameLine[sameLine.length - 1].end;\n const dangling = (ts.getLeadingCommentRanges(text, from) ?? []).filter(\n (r) => r.end <= closeParen.getStart(),\n );\n last.trailing.push(...commentTexts(text, dangling));\n }\n return result;\n}\n\nfunction hasComments(list: Piece[]): boolean {\n return list.some((p) => p.leading.length > 0 || p.trailing.length > 0);\n}\n\nfunction renderCall(callee: string, list: Piece[], multiline: boolean): string {\n if (!multiline && !hasComments(list)) {\n return `${callee}(${list.map((p) => p.text).join(\", \")})`;\n }\n const lines = list.map((p) => {\n const leading = p.leading.map((c) => `${c}\\n`).join(\"\");\n const trailing = p.trailing.length ? ` ${p.trailing.join(\" \")}` : \"\";\n return `${leading}${p.text},${trailing}`;\n });\n return `${callee}(\\n${lines.join(\"\\n\")}\\n)`;\n}\n\n/** A lone argument taken out of a nested `sequence`: its comments go above it. */\nfunction renderAlone(piece: Piece): string {\n const comments = [...piece.leading, ...piece.trailing];\n return comments.map((c) => `${c}\\n`).join(\"\") + piece.text;\n}\n\nfunction isMultiline(call: CallExpression): boolean {\n return call\n .getArguments()\n .some((arg, i, args) =>\n i === 0\n ? false\n : arg.getStartLineNumber() !== args[i - 1].getEndLineNumber(),\n );\n}\n\nfunction rewriteSequence(call: CallExpression, list: Piece[]): Node {\n const multiline = isMultiline(call);\n return call.replaceWithText(\n renderCall(call.getExpression().getText(), list, multiline),\n );\n}\n\nfunction handleStatement(site: Site): Statement {\n return site.kind === \"function\" ? site.fn : site.statement;\n}\n\n/** The `handle` statement as it stands now; nodes go stale on every edit. */\nfunction currentStatement(sf: SourceFile): Statement | undefined {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return undefined;\n return handleStatement(located.site);\n}\n\nfunction changed(sf: SourceFile): ComposeResult {\n return { status: \"changed\", statement: currentStatement(sf) };\n}\n\nfunction unchanged(site: Site | null): ComposeResult {\n return {\n status: \"unchanged\",\n statement: site ? handleStatement(site) : undefined,\n };\n}\n\nfunction unsupported(reason: Unsupported): ComposeResult {\n return { status: \"unsupported\", reason };\n}\n\n/**\n * Take the whole `handle` out: its declarator, or its statement with the\n * comments above it, and an `export { handle }` naming it.\n */\nfunction removeWholeHandle(sf: SourceFile, site: Site): void {\n const viaSpecifier = !site.inlineExport;\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n site.decl.remove();\n } else {\n removeStatementWithComments(sf, handleStatement(site));\n }\n if (!viaSpecifier) return;\n for (const ed of sf.getExportDeclarations()) {\n if (ed.getModuleSpecifier() !== undefined) continue;\n const spec = ed.getNamedExports().find((s) => s.getName() === \"handle\");\n if (!spec) continue;\n if (ed.getNamedExports().length === 1) ed.remove();\n else spec.remove();\n }\n}\n\n/**\n * Move a handle that is a function out of the way: rename it `handleApp`,\n * un-export it, and export `sequence(...)` of it right after, so `handleApp`\n * is declared before anything reads it.\n */\nfunction extract(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n callee: string,\n kit: KitSequence,\n): ComposeResult {\n const position = spec.position ?? \"first\";\n const args =\n position === \"first\"\n ? [spec.expression, EXTRACTED]\n : [EXTRACTED, spec.expression];\n const exportKeyword = site.inlineExport ? \"export \" : \"\";\n const composed = `${exportKeyword}const handle = ${callee}(${args.join(\", \")});`;\n\n if (site.kind === \"function\") {\n if (site.inlineExport) site.fn.setIsExported(false);\n sf.getFunctionOrThrow(\"handle\").getNameNode()!.replaceWithText(EXTRACTED);\n const fn = sf.getFunctionOrThrow(EXTRACTED);\n sf.insertText(fn.getEnd(), `\\n\\n${composed}`);\n } else {\n if (site.inlineExport) site.statement.setIsExported(false);\n sf.getVariableDeclarationOrThrow(\"handle\")\n .getNameNode()\n .replaceWithText(EXTRACTED);\n const statement = sf.getVariableStatementOrThrow(EXTRACTED);\n sf.insertText(statement.getEnd(), `\\n\\n${composed}`);\n }\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\n/**\n * After a `sequence` unwraps to `handleApp` alone, put the function back the\n * way `extract` found it: `handleApp` renamed to `handle` and exported, and\n * the `handle = handleApp` statement gone.\n */\nfunction restoreExtracted(sf: SourceFile): void {\n const located = locate(sf);\n if (\"unsupported\" in located || located.site?.kind !== \"variable\") return;\n const { decl, statement, inlineExport } = located.site;\n const init = decl.getInitializer();\n if (\n !init ||\n !Node.isIdentifier(init) ||\n init.getText() !== EXTRACTED ||\n decl.getTypeNode() ||\n statement.getDeclarations().length > 1\n ) {\n return;\n }\n\n const uses = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .filter((id) => id.getText() === EXTRACTED);\n // Its declaration and the one use in `handle`.\n if (uses.length !== 2) return;\n\n const fn = sf.getFunction(EXTRACTED);\n const variable = sf.getVariableStatements().find((s) => {\n const decls = s.getDeclarations();\n return decls.length === 1 && decls[0].getName() === EXTRACTED;\n });\n const target = fn ?? variable;\n if (!target || target.hasExportKeyword()) return;\n\n statement.remove();\n if (fn) {\n const restored = sf.getFunctionOrThrow(EXTRACTED);\n restored.getNameNode()!.replaceWithText(\"handle\");\n if (inlineExport) sf.getFunctionOrThrow(\"handle\").setIsExported(true);\n } else {\n const restored = sf.getVariableDeclarationOrThrow(EXTRACTED);\n restored.getNameNode().replaceWithText(\"handle\");\n if (inlineExport) {\n sf.getVariableStatementOrThrow(\"handle\").setIsExported(true);\n }\n }\n}\n\n/**\n * Add a handle to the exported `handle`. Already present anywhere in the\n * composition: unchanged. No `handle` yet: `export const handle = <expression>`.\n */\nexport function addHandle(sf: SourceFile, spec: HandleSpec): ComposeResult {\n const name = spec.name ?? spec.expression;\n const position = spec.position ?? \"first\";\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n const kit = kitSequence(sf);\n\n if (!site) {\n if (located.starExport) return unsupported(\"re-export\");\n const blank = sf.getStatementsWithComments().length > 0 ? \"\\n\" : \"\";\n sf.addStatements(`${blank}export const handle = ${spec.expression};`);\n return changed(sf);\n }\n\n if (site.kind === \"function\") {\n if (references(site.fn, name)) return unsupported(\"ambiguous-reference\");\n return extractChecked(sf, site, spec, kit);\n }\n\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name) || findInSequence(core, name, kit)) {\n return unchanged(site);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n\n if (isSequenceCall(core, kit)) {\n const list = pieces(core);\n const piece: Piece = { leading: [], text: spec.expression, trailing: [] };\n if (position === \"first\") list.unshift(piece);\n else list.push(piece);\n rewriteSequence(core, list);\n return changed(sf);\n }\n\n if (Node.isArrowFunction(core) || Node.isFunctionExpression(core)) {\n return extractChecked(sf, site, spec, kit);\n }\n\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const existing = core.getText();\n const args =\n position === \"first\"\n ? [spec.expression, existing]\n : [existing, spec.expression];\n const multiline = args.some((a) => a.includes(\"\\n\"));\n core.replaceWithText(\n renderCall(\n callee,\n args.map((text) => ({ leading: [], text, trailing: [] })),\n multiline,\n ),\n );\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\nfunction extractChecked(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n kit: KitSequence,\n): ComposeResult {\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const taken = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === EXTRACTED);\n if (taken) return unsupported(\"name-collision\");\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n return unsupported(\"multi-declarator\");\n }\n return extract(sf, site, spec, callee, kit);\n}\n\n/**\n * Take a handle out of the exported `handle`. A `sequence` left with one\n * argument unwraps to it; the last handle takes the `handle` export with it.\n */\nexport function removeHandle(sf: SourceFile, name: string): ComposeResult {\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site) return unchanged(null);\n\n if (site.kind === \"function\") {\n return references(site.fn, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name)) {\n removeWholeHandle(sf, site);\n pruneSequenceImport(sf);\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (!found) {\n return references(core, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n // Innermost call first; a nested `sequence` emptied by the removal is in\n // turn removed from the one around it.\n const calls = [...found.calls];\n let index = found.index;\n for (;;) {\n const call = calls.pop()!;\n const list = pieces(call);\n list.splice(index, 1);\n const outer = calls[calls.length - 1];\n\n if (list.length === 0) {\n if (!outer) {\n removeWholeHandle(sf, site);\n break;\n }\n index = outer.getArguments().indexOf(call);\n continue;\n }\n if (list.length === 1 && outer) {\n call.replaceWithText(renderAlone(list[0]));\n break;\n }\n if (list.length === 1) {\n // `handle = sequence(x)` unwraps to `handle = x`, and x's comments move\n // above the statement rather than dangle after the `=`.\n const [kept] = list;\n const comments = [...kept.leading, ...kept.trailing];\n call.replaceWithText(kept.text);\n if (comments.length === 0) restoreExtracted(sf);\n else {\n const statement = currentStatement(sf)!;\n sf.insertText(\n statement.getStart(true),\n comments.map((c) => `${c}\\n`).join(\"\"),\n );\n }\n break;\n }\n rewriteSequence(call, list);\n break;\n }\n\n pruneSequenceImport(sf);\n return changed(sf);\n}\n\n/**\n * Swap handle `name` for `spec` in the same place in the chain. When `name`\n * was the whole `handle`, the comments above the statement go too: they\n * described the old handle. With `name` absent this is `addHandle`.\n */\nexport function replaceHandle(\n sf: SourceFile,\n name: string,\n spec: HandleSpec,\n): ComposeResult {\n const newName = spec.name ?? spec.expression;\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site || site.kind === \"function\") return addHandle(sf, spec);\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, newName) || findInSequence(core, newName, kit)) {\n const stale = isHandle(core, name) || findInSequence(core, name, kit);\n return stale ? removeHandle(sf, name) : unchanged(site);\n }\n\n if (isHandle(core, name)) {\n core.replaceWithText(spec.expression);\n removeAttachedComments(sf, sf.getVariableStatementOrThrow(\"handle\"));\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (found) {\n const call = found.calls[found.calls.length - 1];\n const list = pieces(call);\n list[found.index] = { ...list[found.index], text: spec.expression };\n rewriteSequence(call, list);\n return changed(sf);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n return addHandle(sf, spec);\n}\n\n/**\n * The handles in the exported `handle`, in order: each argument's identifier,\n * or its callee's, or its source text. A function handle is `handle` itself.\n * `null` when there is no `handle` to compose.\n */\nexport function listHandles(sf: SourceFile): string[] | null {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return null;\n if (located.site.kind === \"function\") return [\"handle\"];\n const kit = kitSequence(sf);\n\n const names = (node: Node): string[] => {\n if (isSequenceCall(node, kit)) return node.getArguments().flatMap(names);\n if (Node.isIdentifier(node)) return [node.getText()];\n if (\n Node.isCallExpression(node) &&\n Node.isIdentifier(node.getExpression())\n ) {\n return [node.getExpression().getText()];\n }\n return [node.getText()];\n };\n return names(unwrap(located.site.decl.getInitializerOrThrow()));\n}\n"],"mappings":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O,EAAM,MAAM,EAAM,MAAM,SAAS,IACxC,IAAO,EAAO,CAAI;EAGxB,OAFA,EAAK,EAAM,SAAS;GAAE,GAAG,EAAK,EAAM;GAAQ,MAAM,EAAK;EAAW,GAClE,EAAgB,GAAM,CAAI,GACnB,EAAQ,CAAE;CACnB;CAEA,OADI,EAAW,GAAM,CAAI,IAAU,EAAY,qBAAqB,IAC7D,EAAU,GAAI,CAAI;AAC3B"}
@@ -0,0 +1,6 @@
1
+ //#region src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw
2
+ var e = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '$lib/assets/favicon.svg';\n import { site } from '$lib/site';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{site.name}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", t = "<script lang=\"ts\">\n import { toggleMode, mode } from \"mode-watcher\";\n import ChevronsUpDownIcon from \"@lucide/svelte/icons/chevrons-up-down\";\n import Settings2Icon from \"@lucide/svelte/icons/settings-2\";\n import CreditCardIcon from \"@lucide/svelte/icons/credit-card\";\n import LogOutIcon from \"@lucide/svelte/icons/log-out\";\n import MoonIcon from \"@lucide/svelte/icons/moon\";\n import SunIcon from \"@lucide/svelte/icons/sun\";\n import * as Avatar from \"$lib/components/ui/avatar\";\n import * as DropdownMenu from \"$lib/components/ui/dropdown-menu\";\n import * as Sidebar from \"$lib/components/ui/sidebar\";\n\n let data = {\n navUser: [\n {\n title: \"Settings\",\n url: \"/settings\",\n icon: Settings2Icon,\n },\n {\n title: \"Billing\",\n url: \"/billing\",\n icon: CreditCardIcon,\n },\n ],\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n\n // [!code highlight:1]\n const planLabel = $derived(subscription?.productName ?? \"Free\");\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs text-muted-foreground\">\n {planLabel}\n </span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? \"bottom\" : \"right\"}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs\">\n {planLabel}\n </span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === \"dark\"}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a\n href={item.url}\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button\n type=\"submit\"\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", n = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", r = "<script lang=\"ts\">\n import * as Sidebar from \"$lib/components/ui/sidebar\";\n import { Separator } from \"$lib/components/ui/separator\";\n import AppSidebar from \"$lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"$lib/components/ui/breadcrumb\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n \n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", i = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"$lib/stripe\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user.id }),\n );\n } catch {\n // The link-stripe-customer workflow started at signup has not finished.\n return {\n paymentMethods: [],\n user,\n billingReady: false,\n hasDefaultPaymentMethod: false,\n activeSubscription: null,\n availablePlans: [],\n };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const userId = locals.pb.authStore.record?.id;\n if (!userId) {\n return error(401, \"Unauthorized\");\n }\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${userId}\"`);\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n return customer;\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\n}\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", a = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, invalidateAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (invalidateAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n &bull;\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", o = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\nimport { handleSubscriptionCreated } from './subscription/created';\nimport { handleSubscriptionUpdated } from './subscription/updated';\nimport { handleSubscriptionDeleted } from './subscription/deleted';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n case 'customer.subscription.created':\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case 'customer.subscription.updated':\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n";
3
+ //#endregion
4
+ export { n as a, r as i, a as n, t as o, i as r, e as s, o as t };
5
+
6
+ //# sourceMappingURL=dispatch-BRnt8PcW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatch-BRnt8PcW.js","names":[],"sources":[],"mappings":""}
@@ -0,0 +1,30 @@
1
+ import { t as e } from "./providers-DO9kMyzB.js";
2
+ import { a as t, c as n, n as r, o as i, r as a, s as o } from "./generate-DRA63W0r.js";
3
+ import { n as s } from "./shared-BwHQM-a9.js";
4
+ //#region src/patterns/disable/analytics/generate.ts
5
+ var c = /* #__PURE__ */ Object.assign({
6
+ "../../enable/analytics/providers/google/src/lib/components/analytics/analytics.svelte": n,
7
+ "../../enable/analytics/providers/google/src/lib/components/analytics/gtag.ts": o,
8
+ "../../enable/analytics/providers/plausible/src/lib/components/analytics/analytics.svelte": i,
9
+ "../../enable/analytics/providers/posthog/src/lib/components/analytics/analytics.svelte": t
10
+ });
11
+ function l() {
12
+ return r.flatMap((e) => a(e));
13
+ }
14
+ async function u(t) {
15
+ return {
16
+ creates: [],
17
+ modifies: [],
18
+ deletes: e(c).map(s),
19
+ components: [],
20
+ packages: [],
21
+ uninstalls: ["posthog-js"],
22
+ collections: [],
23
+ collectionPatches: [],
24
+ collectionDrops: []
25
+ };
26
+ }
27
+ //#endregion
28
+ export { u as n, l as t };
29
+
30
+ //# sourceMappingURL=generate-BkQ1xMDp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-BkQ1xMDp.js","names":[],"sources":["../../src/patterns/disable/analytics/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { envEditsFor, PROVIDERS } from \"../../enable/analytics/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n \"../../enable/analytics/providers/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n/**\n * The `.env` lines every provider writes. The project only has one set, but\n * which one is not recorded anywhere, so all are removed; keys that are not\n * there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\nexport async function generate(_options: Options) {\n return {\n creates: [],\n modifies: [],\n // Every provider's files: missing ones are skipped, and the emptied\n // components/analytics directory goes with them.\n deletes: allProviderPaths(providersRaw).map(toDeleteEntry),\n components: [],\n packages: [],\n // PostHog's SDK; the other providers load a script and install nothing.\n uninstalls: [\"posthog-js\"],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAM,IAAe,uBAAA,OAAA;CAAA,yFAAA;CAAA,gFAAA;CAAA,4FAAA;CAAA,0FAAA;AAGrB,CAAA;AAOA,SAAgB,IAAyB;CACvC,OAAO,EAAU,SAAS,MAAa,EAAY,CAAQ,CAAC;AAC9D;AAEA,eAAsB,EAAS,GAAmB;CAChD,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAGX,SAAS,EAAiB,CAAY,CAAC,CAAC,IAAI,CAAa;EACzD,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,YAAY;EACzB,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}