@velastack/patterns 0.2.11 → 0.3.0

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 (132) hide show
  1. package/README.md +4 -3
  2. package/dist/chunks/{_layout-D0OmzCu1.js → _layout-DqH4lA_r.js} +8 -8
  3. package/dist/chunks/{_layout-D0OmzCu1.js.map → _layout-DqH4lA_r.js.map} +1 -1
  4. package/dist/chunks/{collections-DDYlpDNO.js → collections-CgdvZXmh.js} +17 -17
  5. package/dist/chunks/{collections-DDYlpDNO.js.map → collections-CgdvZXmh.js.map} +1 -1
  6. package/dist/chunks/compose-handle-Cg9jnCsS.js +322 -0
  7. package/dist/chunks/compose-handle-Cg9jnCsS.js.map +1 -0
  8. package/dist/chunks/{config-target-DOi8kI_f.js → config-target-Co-ij8p3.js} +9 -9
  9. package/dist/chunks/{config-target-DOi8kI_f.js.map → config-target-Co-ij8p3.js.map} +1 -1
  10. package/dist/chunks/dispatch-BRnt8PcW.js +6 -0
  11. package/dist/chunks/dispatch-BRnt8PcW.js.map +1 -0
  12. package/dist/chunks/format-result-Cb2hWsb8.js +64 -0
  13. package/dist/chunks/format-result-Cb2hWsb8.js.map +1 -0
  14. package/dist/chunks/generate-BkQ1xMDp.js +30 -0
  15. package/dist/chunks/generate-BkQ1xMDp.js.map +1 -0
  16. package/dist/chunks/{generate-Va1sxVPG.js → generate-DRA63W0r.js} +17 -64
  17. package/dist/chunks/generate-DRA63W0r.js.map +1 -0
  18. package/dist/chunks/generate-_LvrYK6i.js +55 -0
  19. package/dist/chunks/generate-_LvrYK6i.js.map +1 -0
  20. package/dist/chunks/generate-iQP31-m1.js +252 -0
  21. package/dist/chunks/generate-iQP31-m1.js.map +1 -0
  22. package/dist/chunks/{generate.runtime-Dtf2BI_5.js → generate.runtime-B0hhtyAL.js} +9 -9
  23. package/dist/chunks/{generate.runtime-Dtf2BI_5.js.map → generate.runtime-B0hhtyAL.js.map} +1 -1
  24. package/dist/chunks/generate.runtime-B49wetSx.js +122 -0
  25. package/dist/chunks/generate.runtime-B49wetSx.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-SQhCLSah.js → generate.runtime-B7LRx-BU.js} +13 -13
  27. package/dist/chunks/{generate.runtime-SQhCLSah.js.map → generate.runtime-B7LRx-BU.js.map} +1 -1
  28. package/dist/chunks/generate.runtime-BKo-Nidn.js +38 -0
  29. package/dist/chunks/generate.runtime-BKo-Nidn.js.map +1 -0
  30. package/dist/chunks/{generate.runtime-vTneb2SY.js → generate.runtime-BORbegw_.js} +111 -101
  31. package/dist/chunks/generate.runtime-BORbegw_.js.map +1 -0
  32. package/dist/chunks/{generate.runtime-BtX_9lLk.js → generate.runtime-BbIN0tUZ.js} +34 -34
  33. package/dist/chunks/{generate.runtime-BtX_9lLk.js.map → generate.runtime-BbIN0tUZ.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-OjW1XETW.js → generate.runtime-BnWE4qsu.js} +42 -42
  35. package/dist/chunks/generate.runtime-BnWE4qsu.js.map +1 -0
  36. package/dist/chunks/{generate.runtime-B_Fk1Jjs.js → generate.runtime-BwhGDnGu.js} +32 -35
  37. package/dist/chunks/generate.runtime-BwhGDnGu.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-BgezGu15.js → generate.runtime-CCg2Pjcv.js} +95 -94
  39. package/dist/chunks/generate.runtime-CCg2Pjcv.js.map +1 -0
  40. package/dist/chunks/{generate.runtime-DRcq4d5D.js → generate.runtime-CRYjWJRe.js} +31 -31
  41. package/dist/chunks/{generate.runtime-DRcq4d5D.js.map → generate.runtime-CRYjWJRe.js.map} +1 -1
  42. package/dist/chunks/generate.runtime-CcuAXuV2.js +60 -0
  43. package/dist/chunks/generate.runtime-CcuAXuV2.js.map +1 -0
  44. package/dist/chunks/{generate.runtime-DK7iXmAZ.js → generate.runtime-D0icLb5j.js} +50 -47
  45. package/dist/chunks/{generate.runtime-DK7iXmAZ.js.map → generate.runtime-D0icLb5j.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-fSDNxfGG.js → generate.runtime-D2e_KRj0.js} +11 -11
  47. package/dist/chunks/{generate.runtime-fSDNxfGG.js.map → generate.runtime-D2e_KRj0.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-CycY6kPr.js → generate.runtime-D44gjxRA.js} +102 -99
  49. package/dist/chunks/generate.runtime-D44gjxRA.js.map +1 -0
  50. package/dist/chunks/{generate.runtime-AjCpCfv3.js → generate.runtime-D8vgh5MH.js} +186 -138
  51. package/dist/chunks/generate.runtime-D8vgh5MH.js.map +1 -0
  52. package/dist/chunks/generate.runtime-DAmYsIvF.js +32 -0
  53. package/dist/chunks/generate.runtime-DAmYsIvF.js.map +1 -0
  54. package/dist/chunks/{generate.runtime-B6kxV3Bi.js → generate.runtime-DNaQxed-.js} +45 -45
  55. package/dist/chunks/{generate.runtime-B6kxV3Bi.js.map → generate.runtime-DNaQxed-.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-CZQoVNt3.js → generate.runtime-DOuufRLr.js} +35 -35
  57. package/dist/chunks/generate.runtime-DOuufRLr.js.map +1 -0
  58. package/dist/chunks/{generate.runtime-BpYOznG5.js → generate.runtime-DSqkXvps.js} +21 -21
  59. package/dist/chunks/{generate.runtime-BpYOznG5.js.map → generate.runtime-DSqkXvps.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-BYJZB1ad.js → generate.runtime-DhkaXTq3.js} +37 -57
  61. package/dist/chunks/generate.runtime-DhkaXTq3.js.map +1 -0
  62. package/dist/chunks/{generate.runtime-Cq1gqxzg.js → generate.runtime-DoZdSh9W.js} +22 -22
  63. package/dist/chunks/{generate.runtime-Cq1gqxzg.js.map → generate.runtime-DoZdSh9W.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-qjsxSPaH.js → generate.runtime-S5RIgbQx.js} +102 -99
  65. package/dist/chunks/generate.runtime-S5RIgbQx.js.map +1 -0
  66. package/dist/chunks/generate.runtime-WmSMWL15.js +82 -0
  67. package/dist/chunks/generate.runtime-WmSMWL15.js.map +1 -0
  68. package/dist/chunks/generate.runtime-acRmiU7e.js +81 -0
  69. package/dist/chunks/generate.runtime-acRmiU7e.js.map +1 -0
  70. package/dist/chunks/generate.runtime-flFRYzpi.js +145 -0
  71. package/dist/chunks/generate.runtime-flFRYzpi.js.map +1 -0
  72. package/dist/chunks/generate.runtime-gtpOuLNO.js +110 -0
  73. package/dist/chunks/generate.runtime-gtpOuLNO.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-DHRCNPVx.js → generate.runtime-kLxeDGnS.js} +23 -23
  75. package/dist/chunks/{generate.runtime-DHRCNPVx.js.map → generate.runtime-kLxeDGnS.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-DH9o-888.js → generate.runtime-wA1G3tQ4.js} +27 -27
  77. package/dist/chunks/{generate.runtime-DH9o-888.js.map → generate.runtime-wA1G3tQ4.js.map} +1 -1
  78. package/dist/chunks/modify-file-GQD6uNgI.js +254 -0
  79. package/dist/chunks/modify-file-GQD6uNgI.js.map +1 -0
  80. package/dist/chunks/{modify-svelte-config-remote-D3eBzcZc.js → modify-svelte-config-remote-CDKs_Qi0.js} +2 -2
  81. package/dist/chunks/{modify-svelte-config-remote-D3eBzcZc.js.map → modify-svelte-config-remote-CDKs_Qi0.js.map} +1 -1
  82. package/dist/chunks/{pocketbase-BerjVikJ.js → pocketbase-CeG5BMN2.js} +57 -50
  83. package/dist/chunks/{pocketbase-BerjVikJ.js.map → pocketbase-CeG5BMN2.js.map} +1 -1
  84. package/dist/chunks/providers-DO9kMyzB.js +69 -0
  85. package/dist/chunks/providers-DO9kMyzB.js.map +1 -0
  86. package/dist/chunks/rolldown-runtime-DArdT4gl.js +23 -0
  87. package/dist/chunks/{shared-Cmbzu7Od.js → shared-BwHQM-a9.js} +2 -2
  88. package/dist/chunks/{shared-Cmbzu7Od.js.map → shared-BwHQM-a9.js.map} +1 -1
  89. package/dist/chunks/site-D027dpBm.js +55 -0
  90. package/dist/chunks/site-D027dpBm.js.map +1 -0
  91. package/dist/chunks/svelte-file-B3RfgVdt.js +123 -0
  92. package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -0
  93. package/dist/chunks/{test-setup-DjbhQYZC.js → test-setup-B2hd8I-s.js} +15 -15
  94. package/dist/chunks/{test-setup-DjbhQYZC.js.map → test-setup-B2hd8I-s.js.map} +1 -1
  95. package/dist/chunks/{ui-BdkuOXPw.js → ui-B4Tuit-7.js} +12 -12
  96. package/dist/chunks/{ui-BdkuOXPw.js.map → ui-B4Tuit-7.js.map} +1 -1
  97. package/dist/chunks/ui-jhXrsw4T.js +12 -0
  98. package/dist/chunks/ui-jhXrsw4T.js.map +1 -0
  99. package/dist/chunks/{write-result-BVWPlGvE.js → write-result-DewHCNhM.js} +51 -51
  100. package/dist/chunks/{write-result-BVWPlGvE.js.map → write-result-DewHCNhM.js.map} +1 -1
  101. package/dist/index.d.ts +272 -65
  102. package/dist/index.js +2279 -2268
  103. package/dist/index.js.map +1 -1
  104. package/package.json +1 -1
  105. package/dist/chunks/dispatch-B5PfQ2CA.js +0 -6
  106. package/dist/chunks/dispatch-B5PfQ2CA.js.map +0 -1
  107. package/dist/chunks/format-result-BdAy5M8C.js +0 -50
  108. package/dist/chunks/format-result-BdAy5M8C.js.map +0 -1
  109. package/dist/chunks/generate-Va1sxVPG.js.map +0 -1
  110. package/dist/chunks/generate.runtime-AjCpCfv3.js.map +0 -1
  111. package/dist/chunks/generate.runtime-BYJZB1ad.js.map +0 -1
  112. package/dist/chunks/generate.runtime-B_Fk1Jjs.js.map +0 -1
  113. package/dist/chunks/generate.runtime-BcVAKzoY.js +0 -138
  114. package/dist/chunks/generate.runtime-BcVAKzoY.js.map +0 -1
  115. package/dist/chunks/generate.runtime-BgezGu15.js.map +0 -1
  116. package/dist/chunks/generate.runtime-CTiJEVF2.js +0 -107
  117. package/dist/chunks/generate.runtime-CTiJEVF2.js.map +0 -1
  118. package/dist/chunks/generate.runtime-CZQoVNt3.js.map +0 -1
  119. package/dist/chunks/generate.runtime-CycY6kPr.js.map +0 -1
  120. package/dist/chunks/generate.runtime-D2WfvXm2.js +0 -106
  121. package/dist/chunks/generate.runtime-D2WfvXm2.js.map +0 -1
  122. package/dist/chunks/generate.runtime-DEl6b1Ti.js +0 -87
  123. package/dist/chunks/generate.runtime-DEl6b1Ti.js.map +0 -1
  124. package/dist/chunks/generate.runtime-DaPNrIyg.js +0 -28
  125. package/dist/chunks/generate.runtime-DaPNrIyg.js.map +0 -1
  126. package/dist/chunks/generate.runtime-OjW1XETW.js.map +0 -1
  127. package/dist/chunks/generate.runtime-qjsxSPaH.js.map +0 -1
  128. package/dist/chunks/generate.runtime-vTneb2SY.js.map +0 -1
  129. package/dist/chunks/modify-file-Cgu_WeFk.js +0 -22
  130. package/dist/chunks/modify-file-Cgu_WeFk.js.map +0 -1
  131. package/dist/chunks/ts-morph-helpers-teS3yXg-.js +0 -229
  132. package/dist/chunks/ts-morph-helpers-teS3yXg-.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,6 +1,6 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import t from "node:path";
3
- import n from "node:fs";
2
+ import t from "node:fs";
3
+ import n from "node:path";
4
4
  //#region src/patterns/enable/i18n/modifies/+layout.ts
5
5
  var r = e`
6
6
  import { browser } from '$app/environment';
@@ -25,18 +25,18 @@ var r = e`
25
25
  r
26
26
  ].join("\n");
27
27
  function a(e) {
28
- if (n.existsSync(e)) {
29
- let t = n.readFileSync(e, "utf8");
30
- if (t.includes("loadLocale") || t.includes("translateUrl")) return {
28
+ if (t.existsSync(e)) {
29
+ let n = t.readFileSync(e, "utf8");
30
+ if (n.includes("loadLocale") || n.includes("translateUrl")) return {
31
31
  status: "success",
32
32
  changed: !1
33
33
  };
34
- if (/\bexport\s+(const|function)\s+load\b/.test(t)) return {
34
+ if (/\bexport\s+(const|function)\s+load\b/.test(n)) return {
35
35
  status: "failed",
36
36
  message: i
37
37
  };
38
38
  }
39
- return n.mkdirSync(t.dirname(e), { recursive: !0 }), n.writeFileSync(e, r + "\n"), {
39
+ return t.mkdirSync(n.dirname(e), { recursive: !0 }), t.writeFileSync(e, r + "\n"), {
40
40
  status: "success",
41
41
  changed: !0
42
42
  };
@@ -44,4 +44,4 @@ function a(e) {
44
44
  //#endregion
45
45
  export { a as n, r as t };
46
46
 
47
- //# sourceMappingURL=_layout-D0OmzCu1.js.map
47
+ //# sourceMappingURL=_layout-DqH4lA_r.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_layout-D0OmzCu1.js","names":[],"sources":["../../src/patterns/enable/i18n/modifies/+layout.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport const LOAD_SNIPPET = dedent`\n import { browser } from '$app/environment';\n import { loadLocale } from 'wuchale/load-utils';\n\n import { getLocale } from '$locales/main.url';\n import '$locales/main.loader.svelte';\n import '$locales/js.loader';\n\n export const load = async ({ url, data }) => {\n const locale = getLocale(url);\n\n if (browser) {\n await loadLocale(locale);\n }\n\n return data;\n };\n`;\n\nconst FAILURE_HINT = [\n \"Merge the wuchale loader into your existing load function in +layout.ts:\",\n \"\",\n LOAD_SNIPPET,\n].join(\"\\n\");\n\nexport function ensureRootLayoutI18n(layoutPath: string): ModifyOutcome {\n if (fs.existsSync(layoutPath)) {\n const existing = fs.readFileSync(layoutPath, \"utf8\");\n if (existing.includes(\"loadLocale\") || existing.includes(\"translateUrl\")) {\n return { status: \"success\", changed: false };\n }\n\n if (/\\bexport\\s+(const|function)\\s+load\\b/.test(existing)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n }\n\n fs.mkdirSync(path.dirname(layoutPath), { recursive: true });\n fs.writeFileSync(layoutPath, LOAD_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;AAKA,IAAa,IAAe,CAAM;;;;;;;;;;;;;;;;;GAmB5B,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAqB,GAAmC;CACtE,IAAI,EAAG,WAAW,CAAU,GAAG;EAC7B,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;EACnD,IAAI,EAAS,SAAS,YAAY,KAAK,EAAS,SAAS,cAAc,GACrE,OAAO;GAAE,QAAQ;GAAW,SAAS;EAAM;EAG7C,IAAI,uCAAuC,KAAK,CAAQ,GACtD,OAAO;GAAE,QAAQ;GAAU,SAAS;EAAa;CAErD;CAIA,OAFA,EAAG,UAAU,EAAK,QAAQ,CAAU,GAAG,EAAE,WAAW,GAAK,CAAC,GAC1D,EAAG,cAAc,GAAY,IAAe,IAAI,GACzC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
1
+ {"version":3,"file":"_layout-DqH4lA_r.js","names":[],"sources":["../../src/patterns/enable/i18n/modifies/+layout.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport const LOAD_SNIPPET = dedent`\n import { browser } from '$app/environment';\n import { loadLocale } from 'wuchale/load-utils';\n\n import { getLocale } from '$locales/main.url';\n import '$locales/main.loader.svelte';\n import '$locales/js.loader';\n\n export const load = async ({ url, data }) => {\n const locale = getLocale(url);\n\n if (browser) {\n await loadLocale(locale);\n }\n\n return data;\n };\n`;\n\nconst FAILURE_HINT = [\n \"Merge the wuchale loader into your existing load function in +layout.ts:\",\n \"\",\n LOAD_SNIPPET,\n].join(\"\\n\");\n\nexport function ensureRootLayoutI18n(layoutPath: string): ModifyOutcome {\n if (fs.existsSync(layoutPath)) {\n const existing = fs.readFileSync(layoutPath, \"utf8\");\n if (existing.includes(\"loadLocale\") || existing.includes(\"translateUrl\")) {\n return { status: \"success\", changed: false };\n }\n\n if (/\\bexport\\s+(const|function)\\s+load\\b/.test(existing)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n }\n\n fs.mkdirSync(path.dirname(layoutPath), { recursive: true });\n fs.writeFileSync(layoutPath, LOAD_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;AAKA,IAAa,IAAe,CAAM;;;;;;;;;;;;;;;;;GAmB5B,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAqB,GAAmC;CACtE,IAAI,EAAG,WAAW,CAAU,GAAG;EAC7B,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;EACnD,IAAI,EAAS,SAAS,YAAY,KAAK,EAAS,SAAS,cAAc,GACrE,OAAO;GAAE,QAAQ;GAAW,SAAS;EAAM;EAG7C,IAAI,uCAAuC,KAAK,CAAQ,GACtD,OAAO;GAAE,QAAQ;GAAU,SAAS;EAAa;CAErD;CAIA,OAFA,EAAG,UAAU,EAAK,QAAQ,CAAU,GAAG,EAAE,WAAW,GAAK,CAAC,GAC1D,EAAG,cAAc,GAAY,IAAe,IAAI,GACzC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
@@ -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-BerjVikJ.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-DDYlpDNO.js.map
192
+ //# sourceMappingURL=collections-CgdvZXmh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collections-DDYlpDNO.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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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,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAIF,OAAO;GAAE,YAAA,MAHgB,EAAG,YAAY,OACtC,MAAM,EAAuB,GAAI,CAAI,CACvC;GACqB,SAAS;EAAK;CACrC,SAAS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K,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"}
@@ -0,0 +1,322 @@
1
+ import { f as e, l as t, n, s as r } from "./modify-file-GQD6uNgI.js";
2
+ import { Node as i, SyntaxKind as a, ts as o } from "ts-morph";
3
+ //#region src/runtime/compose-handle.ts
4
+ var s = "@sveltejs/kit/hooks", c = "handleApp";
5
+ function l(e) {
6
+ let t = !1, n = !1;
7
+ for (let r of e.getExportDeclarations()) {
8
+ let e = r.getModuleSpecifier() !== void 0;
9
+ if (r.isNamespaceExport()) {
10
+ if (r.getNamespaceExport()?.getName() === "handle") return { unsupported: "re-export" };
11
+ e && (n = !0);
12
+ continue;
13
+ }
14
+ for (let n of r.getNamedExports()) if ((n.getAliasNode()?.getText() ?? n.getName()) === "handle") {
15
+ if (e || n.getName() !== "handle") return { unsupported: "re-export" };
16
+ t = !0;
17
+ }
18
+ }
19
+ let r = e.getFunctions().find((e) => e.getName() === "handle");
20
+ if (r) return r.isDefaultExport() ? { unsupported: "default-export" } : !r.hasExportKeyword() && !t ? { unsupported: "not-exported" } : {
21
+ site: {
22
+ kind: "function",
23
+ fn: r,
24
+ inlineExport: r.hasExportKeyword()
25
+ },
26
+ starExport: n
27
+ };
28
+ for (let r of e.getVariableStatements()) for (let e of r.getDeclarations()) {
29
+ let o = e.getNameNode();
30
+ if (!i.isIdentifier(o)) {
31
+ if (o.getDescendantsOfKind(a.BindingElement).some((e) => e.getNameNode().getText() === "handle")) return { unsupported: "destructured" };
32
+ continue;
33
+ }
34
+ if (o.getText() === "handle") return !r.hasExportKeyword() && !t ? { unsupported: "not-exported" } : e.getInitializer() ? {
35
+ site: {
36
+ kind: "variable",
37
+ decl: e,
38
+ statement: r,
39
+ inlineExport: r.hasExportKeyword()
40
+ },
41
+ starExport: n
42
+ } : { unsupported: "no-initializer" };
43
+ }
44
+ return t ? { unsupported: "re-export" } : {
45
+ site: null,
46
+ starExport: n
47
+ };
48
+ }
49
+ function u(e) {
50
+ let t = {
51
+ local: null,
52
+ namespace: null
53
+ };
54
+ for (let n of e.getImportDeclarations()) {
55
+ if (n.getModuleSpecifierValue() !== s || n.isTypeOnly()) continue;
56
+ let e = n.getNamespaceImport();
57
+ e && (t.namespace = e.getText());
58
+ for (let e of n.getNamedImports()) e.getName() !== "sequence" || e.isTypeOnly() || (t.local = e.getAliasNode()?.getText() ?? "sequence");
59
+ }
60
+ return t;
61
+ }
62
+ function d(e, t) {
63
+ for (let n of e.getImportDeclarations()) {
64
+ if (n.getDefaultImport()?.getText() === t || n.getNamespaceImport()?.getText() === t) return !0;
65
+ for (let e of n.getNamedImports()) if ((e.getAliasNode()?.getText() ?? e.getName()) === t) return !0;
66
+ }
67
+ return e.getFunction(t) || e.getClass(t) || e.getEnum(t) ? !0 : e.getVariableDeclarations().some((e) => {
68
+ let n = e.getNameNode();
69
+ return i.isIdentifier(n) ? n.getText() === t : n.getDescendantsOfKind(a.BindingElement).some((e) => e.getNameNode().getText() === t);
70
+ });
71
+ }
72
+ function f(e, t) {
73
+ return t.local ? t.local : t.namespace ? `${t.namespace}.sequence` : d(e, "sequence") ? null : "sequence";
74
+ }
75
+ function p(e, t) {
76
+ if (t.local || t.namespace) return;
77
+ let n = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === s && !e.isTypeOnly() && !e.getNamespaceImport());
78
+ n ? n.addNamedImport("sequence") : e.addImportDeclaration({
79
+ namedImports: ["sequence"],
80
+ moduleSpecifier: s
81
+ });
82
+ }
83
+ function m(e) {
84
+ let { wasRemoved: r } = t(e, s, "sequence");
85
+ r && n(e);
86
+ }
87
+ function h(e, t) {
88
+ if (!i.isCallExpression(e)) return !1;
89
+ let n = e.getExpression();
90
+ return i.isIdentifier(n) ? n.getText() === t.local : i.isPropertyAccessExpression(n) ? t.namespace !== null && n.getExpression().getText() === t.namespace && n.getName() === "sequence" : !1;
91
+ }
92
+ function g(e) {
93
+ for (;;) if (i.isParenthesizedExpression(e) || i.isSatisfiesExpression(e) || i.isAsExpression(e) || i.isTypeAssertion(e) || i.isNonNullExpression(e)) e = e.getExpression();
94
+ else return e;
95
+ }
96
+ function _(e, t) {
97
+ if (i.isIdentifier(e)) return e.getText() === t;
98
+ if (i.isCallExpression(e)) {
99
+ let n = e.getExpression();
100
+ return i.isIdentifier(n) && n.getText() === t;
101
+ }
102
+ return !1;
103
+ }
104
+ function v(e, t, n) {
105
+ if (!h(e, n)) return null;
106
+ let r = e.getArguments(), i = r.findIndex((e) => _(e, t));
107
+ if (i >= 0) return {
108
+ calls: [e],
109
+ index: i
110
+ };
111
+ for (let i of r) {
112
+ let r = v(i, t, n);
113
+ if (r) return {
114
+ calls: [e, ...r.calls],
115
+ index: r.index
116
+ };
117
+ }
118
+ return null;
119
+ }
120
+ function y(e, t) {
121
+ return i.isIdentifier(e) && e.getText() === t ? !0 : e.getDescendantsOfKind(a.Identifier).some((e) => e.getText() === t);
122
+ }
123
+ function b(e, t) {
124
+ return t.map((t) => e.slice(t.pos, t.end));
125
+ }
126
+ function x(e) {
127
+ let t = e.getSourceFile().getFullText(), n = e.getArguments(), r = e.getFirstChildByKindOrThrow(a.OpenParenToken), i = e.getLastChildByKindOrThrow(a.CloseParenToken), s = n.map((e, i) => {
128
+ let s = r.getEnd();
129
+ if (i > 0) {
130
+ s = n[i - 1].getNextSiblingIfKind(a.CommaToken)?.getEnd() ?? n[i - 1].getEnd();
131
+ let e = o.getTrailingCommentRanges(t, s);
132
+ e?.length && (s = e[e.length - 1].end);
133
+ }
134
+ let c = (o.getLeadingCommentRanges(t, s) ?? []).filter((t) => t.end <= e.getStart()), l = e.getNextSiblingIfKind(a.CommaToken), u = o.getTrailingCommentRanges(t, l?.getEnd() ?? e.getEnd()) ?? [];
135
+ return {
136
+ leading: b(t, c),
137
+ text: e.getText(),
138
+ trailing: b(t, u)
139
+ };
140
+ }), c = s[s.length - 1];
141
+ if (c) {
142
+ let e = n[n.length - 1], r = e.getNextSiblingIfKind(a.CommaToken)?.getEnd() ?? e.getEnd(), s = o.getTrailingCommentRanges(t, r);
143
+ s?.length && (r = s[s.length - 1].end);
144
+ let l = (o.getLeadingCommentRanges(t, r) ?? []).filter((e) => e.end <= i.getStart());
145
+ c.trailing.push(...b(t, l));
146
+ }
147
+ return s;
148
+ }
149
+ function S(e) {
150
+ return e.some((e) => e.leading.length > 0 || e.trailing.length > 0);
151
+ }
152
+ function C(e, t, n) {
153
+ return !n && !S(t) ? `${e}(${t.map((e) => e.text).join(", ")})` : `${e}(\n${t.map((e) => {
154
+ let t = e.leading.map((e) => `${e}\n`).join(""), n = e.trailing.length ? ` ${e.trailing.join(" ")}` : "";
155
+ return `${t}${e.text},${n}`;
156
+ }).join("\n")}\n)`;
157
+ }
158
+ function w(e) {
159
+ return [...e.leading, ...e.trailing].map((e) => `${e}\n`).join("") + e.text;
160
+ }
161
+ function T(e) {
162
+ return e.getArguments().some((e, t, n) => t !== 0 && e.getStartLineNumber() !== n[t - 1].getEndLineNumber());
163
+ }
164
+ function E(e, t) {
165
+ let n = T(e);
166
+ return e.replaceWithText(C(e.getExpression().getText(), t, n));
167
+ }
168
+ function D(e) {
169
+ return e.kind === "function" ? e.fn : e.statement;
170
+ }
171
+ function O(e) {
172
+ let t = l(e);
173
+ if (!("unsupported" in t || !t.site)) return D(t.site);
174
+ }
175
+ function k(e) {
176
+ return {
177
+ status: "changed",
178
+ statement: O(e)
179
+ };
180
+ }
181
+ function A(e) {
182
+ return {
183
+ status: "unchanged",
184
+ statement: e ? D(e) : void 0
185
+ };
186
+ }
187
+ function j(e) {
188
+ return {
189
+ status: "unsupported",
190
+ reason: e
191
+ };
192
+ }
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
+ }
200
+ }
201
+ function N(e, t, n, r, i) {
202
+ let a = (n.position ?? "first") === "first" ? [n.expression, c] : [c, n.expression], o = `${t.inlineExport ? "export " : ""}const handle = ${r}(${a.join(", ")});`;
203
+ if (t.kind === "function") {
204
+ t.inlineExport && t.fn.setIsExported(!1), e.getFunctionOrThrow("handle").getNameNode().replaceWithText(c);
205
+ let n = e.getFunctionOrThrow(c);
206
+ e.insertText(n.getEnd(), `\n\n${o}`);
207
+ } else {
208
+ t.inlineExport && t.statement.setIsExported(!1), e.getVariableDeclarationOrThrow("handle").getNameNode().replaceWithText(c);
209
+ let n = e.getVariableStatementOrThrow(c);
210
+ e.insertText(n.getEnd(), `\n\n${o}`);
211
+ }
212
+ return p(e, i), k(e);
213
+ }
214
+ function P(e) {
215
+ let t = l(e);
216
+ if ("unsupported" in t || t.site?.kind !== "variable") return;
217
+ let { decl: n, statement: r, inlineExport: o } = t.site, s = n.getInitializer();
218
+ if (!s || !i.isIdentifier(s) || s.getText() !== c || n.getTypeNode() || r.getDeclarations().length > 1 || e.getDescendantsOfKind(a.Identifier).filter((e) => e.getText() === c).length !== 2) return;
219
+ let u = e.getFunction(c), d = e.getVariableStatements().find((e) => {
220
+ let t = e.getDeclarations();
221
+ return t.length === 1 && t[0].getName() === c;
222
+ }), f = u ?? d;
223
+ f && !f.hasExportKeyword() && (r.remove(), u ? (e.getFunctionOrThrow(c).getNameNode().replaceWithText("handle"), o && e.getFunctionOrThrow("handle").setIsExported(!0)) : (e.getVariableDeclarationOrThrow(c).getNameNode().replaceWithText("handle"), o && e.getVariableStatementOrThrow("handle").setIsExported(!0)));
224
+ }
225
+ function F(e, t) {
226
+ let n = t.name ?? t.expression, r = t.position ?? "first", a = l(e);
227
+ if ("unsupported" in a) return j(a.unsupported);
228
+ let { site: o } = a, s = u(e);
229
+ if (!o) {
230
+ if (a.starExport) return j("re-export");
231
+ let n = e.getStatementsWithComments().length > 0 ? "\n" : "";
232
+ return e.addStatements(`${n}export const handle = ${t.expression};`), k(e);
233
+ }
234
+ if (o.kind === "function") return y(o.fn, n) ? j("ambiguous-reference") : I(e, o, t, s);
235
+ let c = g(o.decl.getInitializerOrThrow());
236
+ if (_(c, n) || v(c, n, s)) return A(o);
237
+ if (y(c, n)) return j("ambiguous-reference");
238
+ if (h(c, s)) {
239
+ let n = x(c), i = {
240
+ leading: [],
241
+ text: t.expression,
242
+ trailing: []
243
+ };
244
+ return r === "first" ? n.unshift(i) : n.push(i), E(c, n), k(e);
245
+ }
246
+ if (i.isArrowFunction(c) || i.isFunctionExpression(c)) return I(e, o, t, s);
247
+ let d = f(e, s);
248
+ if (!d) return j("foreign-sequence");
249
+ let m = c.getText(), b = r === "first" ? [t.expression, m] : [m, t.expression], S = b.some((e) => e.includes("\n"));
250
+ return c.replaceWithText(C(d, b.map((e) => ({
251
+ leading: [],
252
+ text: e,
253
+ trailing: []
254
+ })), S)), p(e, s), k(e);
255
+ }
256
+ function I(e, t, n, r) {
257
+ let i = f(e, r);
258
+ return i ? e.getDescendantsOfKind(a.Identifier).some((e) => e.getText() === c) ? j("name-collision") : t.kind === "variable" && t.statement.getDeclarations().length > 1 ? j("multi-declarator") : N(e, t, n, i, r) : j("foreign-sequence");
259
+ }
260
+ function L(e, t) {
261
+ let n = l(e);
262
+ if ("unsupported" in n) return j(n.unsupported);
263
+ let { site: r } = n;
264
+ if (!r) return A(null);
265
+ if (r.kind === "function") return y(r.fn, t) ? j("ambiguous-reference") : A(r);
266
+ let i = u(e), a = g(r.decl.getInitializerOrThrow());
267
+ if (_(a, t)) return M(e, r), m(e), k(e);
268
+ let o = v(a, t, i);
269
+ if (!o) return y(a, t) ? j("ambiguous-reference") : A(r);
270
+ let s = [...o.calls], c = o.index;
271
+ for (;;) {
272
+ let t = s.pop(), n = x(t);
273
+ n.splice(c, 1);
274
+ let i = s[s.length - 1];
275
+ if (n.length === 0) {
276
+ if (!i) {
277
+ M(e, r);
278
+ break;
279
+ }
280
+ c = i.getArguments().indexOf(t);
281
+ continue;
282
+ }
283
+ if (n.length === 1 && i) {
284
+ t.replaceWithText(w(n[0]));
285
+ break;
286
+ }
287
+ if (n.length === 1) {
288
+ let [r] = n, i = [...r.leading, ...r.trailing];
289
+ if (t.replaceWithText(r.text), i.length === 0) P(e);
290
+ else {
291
+ let t = O(e);
292
+ e.insertText(t.getStart(!0), i.map((e) => `${e}\n`).join(""));
293
+ }
294
+ break;
295
+ }
296
+ E(t, n);
297
+ break;
298
+ }
299
+ return m(e), k(e);
300
+ }
301
+ function R(e, t, n) {
302
+ let i = n.name ?? n.expression, a = l(e);
303
+ if ("unsupported" in a) return j(a.unsupported);
304
+ let { site: o } = a;
305
+ if (!o || o.kind === "function") return F(e, n);
306
+ let s = u(e), c = g(o.decl.getInitializerOrThrow());
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(n.expression), r(e, e.getVariableStatementOrThrow("handle")), k(e);
309
+ let d = v(c, t, s);
310
+ if (d) {
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
+ }
317
+ return y(c, t) ? j("ambiguous-reference") : F(e, n);
318
+ }
319
+ //#endregion
320
+ export { L as n, R as r, F as t };
321
+
322
+ //# sourceMappingURL=compose-handle-Cg9jnCsS.js.map