@velastack/patterns 0.0.61 → 0.1.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 (63) hide show
  1. package/dist/chunks/{collections-DZOoJLVj.js → collections-DgZjDXef.js} +2 -2
  2. package/dist/chunks/{collections-DZOoJLVj.js.map → collections-DgZjDXef.js.map} +1 -1
  3. package/dist/chunks/{config-target-Co-ij8p3.js → config-target-DOi8kI_f.js} +9 -9
  4. package/dist/chunks/{config-target-Co-ij8p3.js.map → config-target-DOi8kI_f.js.map} +1 -1
  5. package/dist/chunks/{generate.runtime-6qpoLA04.js → generate.runtime--0bYEUP_.js} +19 -19
  6. package/dist/chunks/{generate.runtime-6qpoLA04.js.map → generate.runtime--0bYEUP_.js.map} +1 -1
  7. package/dist/chunks/{generate.runtime-DBG6kEKb.js → generate.runtime-677mL0-8.js} +17 -17
  8. package/dist/chunks/{generate.runtime-DBG6kEKb.js.map → generate.runtime-677mL0-8.js.map} +1 -1
  9. package/dist/chunks/{generate.runtime-CtzHFod-.js → generate.runtime-B4wtZqNB.js} +23 -23
  10. package/dist/chunks/{generate.runtime-CtzHFod-.js.map → generate.runtime-B4wtZqNB.js.map} +1 -1
  11. package/dist/chunks/{generate.runtime-DfqzMG8Z.js → generate.runtime-BgW9zLGZ.js} +2 -2
  12. package/dist/chunks/{generate.runtime-DfqzMG8Z.js.map → generate.runtime-BgW9zLGZ.js.map} +1 -1
  13. package/dist/chunks/{generate.runtime-CYmjlSQp.js → generate.runtime-C52G7ZnV.js} +15 -15
  14. package/dist/chunks/{generate.runtime-CYmjlSQp.js.map → generate.runtime-C52G7ZnV.js.map} +1 -1
  15. package/dist/chunks/{generate.runtime-a5PXS1Kd.js → generate.runtime-CDSkTWtx.js} +10 -10
  16. package/dist/chunks/{generate.runtime-a5PXS1Kd.js.map → generate.runtime-CDSkTWtx.js.map} +1 -1
  17. package/dist/chunks/{generate.runtime-AmiNbSR3.js → generate.runtime-CFKrhkAA.js} +12 -12
  18. package/dist/chunks/{generate.runtime-AmiNbSR3.js.map → generate.runtime-CFKrhkAA.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-BnnsaLsg.js → generate.runtime-CFwzS666.js} +12 -12
  20. package/dist/chunks/{generate.runtime-BnnsaLsg.js.map → generate.runtime-CFwzS666.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-CRS9C9xX.js → generate.runtime-CG0gMypH.js} +14 -14
  22. package/dist/chunks/{generate.runtime-CRS9C9xX.js.map → generate.runtime-CG0gMypH.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-rfNiROHo.js → generate.runtime-CNwy0UB2.js} +30 -30
  24. package/dist/chunks/{generate.runtime-rfNiROHo.js.map → generate.runtime-CNwy0UB2.js.map} +1 -1
  25. package/dist/chunks/{generate.runtime-D9t6eaQd.js → generate.runtime-Cc1SG-nN.js} +20 -20
  26. package/dist/chunks/{generate.runtime-D9t6eaQd.js.map → generate.runtime-Cc1SG-nN.js.map} +1 -1
  27. package/dist/chunks/{generate.runtime-Di0p-J8l.js → generate.runtime-CfclK4xT.js} +12 -12
  28. package/dist/chunks/{generate.runtime-Di0p-J8l.js.map → generate.runtime-CfclK4xT.js.map} +1 -1
  29. package/dist/chunks/{generate.runtime-CtS6qa_1.js → generate.runtime-Coi_Y6nm.js} +22 -22
  30. package/dist/chunks/generate.runtime-Coi_Y6nm.js.map +1 -0
  31. package/dist/chunks/{generate.runtime-EokncTLy.js → generate.runtime-Dad9oAKS.js} +27 -27
  32. package/dist/chunks/{generate.runtime-EokncTLy.js.map → generate.runtime-Dad9oAKS.js.map} +1 -1
  33. package/dist/chunks/{generate.runtime-CNxgU9v1.js → generate.runtime-Dbhctzy1.js} +17 -17
  34. package/dist/chunks/{generate.runtime-CNxgU9v1.js.map → generate.runtime-Dbhctzy1.js.map} +1 -1
  35. package/dist/chunks/{generate.runtime-P8IVwJLB.js → generate.runtime-DpV_oOT7.js} +23 -23
  36. package/dist/chunks/{generate.runtime-P8IVwJLB.js.map → generate.runtime-DpV_oOT7.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-CINxHRnJ.js → generate.runtime-PtDQdWNY.js} +11 -11
  38. package/dist/chunks/{generate.runtime-CINxHRnJ.js.map → generate.runtime-PtDQdWNY.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-qZhYdFI1.js → generate.runtime-WaqVbEPP.js} +19 -19
  40. package/dist/chunks/{generate.runtime-qZhYdFI1.js.map → generate.runtime-WaqVbEPP.js.map} +1 -1
  41. package/dist/chunks/{generate.runtime-DsLlDfIo.js → generate.runtime-lvraqNgB.js} +25 -25
  42. package/dist/chunks/{generate.runtime-DsLlDfIo.js.map → generate.runtime-lvraqNgB.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-CGtKTfYU.js → generate.runtime-qsPylve5.js} +2 -2
  44. package/dist/chunks/{generate.runtime-CGtKTfYU.js.map → generate.runtime-qsPylve5.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-6TJoTPg9.js → generate.runtime-yddwyo5X.js} +19 -19
  46. package/dist/chunks/{generate.runtime-6TJoTPg9.js.map → generate.runtime-yddwyo5X.js.map} +1 -1
  47. package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js → modify-svelte-config-remote-D3eBzcZc.js} +2 -2
  48. package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js.map → modify-svelte-config-remote-D3eBzcZc.js.map} +1 -1
  49. package/dist/chunks/{pocketbase-BbFvZ4HI.js → pocketbase-BPwW3TWr.js} +15 -15
  50. package/dist/chunks/{pocketbase-BbFvZ4HI.js.map → pocketbase-BPwW3TWr.js.map} +1 -1
  51. package/dist/chunks/{shared-C4-NNykV.js → shared-BGvy1V-z.js} +2 -2
  52. package/dist/chunks/{shared-C4-NNykV.js.map → shared-BGvy1V-z.js.map} +1 -1
  53. package/dist/chunks/{test-setup-CcD8wSRD.js → test-setup-BGhcb0Qm.js} +3 -3
  54. package/dist/chunks/{test-setup-CcD8wSRD.js.map → test-setup-BGhcb0Qm.js.map} +1 -1
  55. package/dist/chunks/{write-result-DtTqt0Cs.js → write-result-BhULcFGo.js} +45 -45
  56. package/dist/chunks/{write-result-DtTqt0Cs.js.map → write-result-BhULcFGo.js.map} +1 -1
  57. package/dist/index.d.ts +22 -0
  58. package/dist/index.js +74 -64
  59. package/dist/index.js.map +1 -1
  60. package/package.json +13 -3
  61. package/dist/chunks/env.runtime-BVage9Kk.js +0 -31
  62. package/dist/chunks/env.runtime-BVage9Kk.js.map +0 -1
  63. package/dist/chunks/generate.runtime-CtS6qa_1.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./errors-D3Zy3wCg.js";
2
2
  import { i as t } from "./util-Bk7aQQJR.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-BbFvZ4HI.js";
4
+ import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-BPwW3TWr.js";
5
5
  import { readFileSync as s } from "node:fs";
6
6
  //#region src/runtime/collections.ts
7
7
  function c(e) {
@@ -173,4 +173,4 @@ async function v(e, r) {
173
173
  //#endregion
174
174
  export { p as applyCollectionFieldsPatches, d as applyCollectionRulePatches, l as createCollectionIdempotent, v as createCollections, _ as dropCollections, g as planCollectionDrops };
175
175
 
176
- //# sourceMappingURL=collections-DZOoJLVj.js.map
176
+ //# sourceMappingURL=collections-DgZjDXef.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collections-DZOoJLVj.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\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(spec);\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: readFile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","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\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(spec);\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,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAEF,OAAO;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B,SAAS;EAAK;CACrC,SAAS,GAAO;EACd,IACE,CAAC,EAA+B,CAAwC,GAExE,MAAM;EAIR,OAFA,EAAO,KAAK,eAAe,EAAK,2BAA2B,GAEpD;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B,SAAS;EAAM;CACtC;AACF;AAEA,SAAS,EACP,GACyB;CACzB,IAAM,IAAmC,CAAC;CAM1C,OALI,EAAM,aAAa,KAAA,MAAW,EAAQ,WAAW,EAAM,WACvD,EAAM,aAAa,KAAA,MAAW,EAAQ,WAAW,EAAM,WACvD,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aAC3D,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aAC3D,EAAM,eAAe,KAAA,MAAW,EAAQ,aAAa,EAAM,aACxD;AACT;AAMA,eAAsB,EACpB,GAMA,GACA,GACA,IAAiB,GACA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,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,5 +1,5 @@
1
- import e from "node:fs";
2
- import t from "node:path";
1
+ import e from "node:path";
2
+ import t from "node:fs";
3
3
  import { Project as n, QuoteKind as r, SyntaxKind as i } from "ts-morph";
4
4
  //#region src/runtime/config-target.ts
5
5
  var a = [
@@ -15,8 +15,8 @@ var a = [
15
15
  ];
16
16
  function s(n, r) {
17
17
  for (let i of r) {
18
- let r = t.join(n, i);
19
- if (e.existsSync(r)) return r;
18
+ let r = e.join(n, i);
19
+ if (t.existsSync(r)) return r;
20
20
  }
21
21
  return null;
22
22
  }
@@ -87,8 +87,8 @@ function m(e, t, n, r) {
87
87
  kitContainer: () => u(n, "kit", "{}")
88
88
  };
89
89
  }
90
- function h(e, n) {
91
- let r = n?.notFound ?? "Could not find a Svelte or Vite config to modify.", u = n?.failed ?? "Could not modify the Svelte or Vite config.", d = s(e, a), h = null, g = "", _ = null, v = null, y = !1;
90
+ function h(t, n) {
91
+ let r = n?.notFound ?? "Could not find a Svelte or Vite config to modify.", u = n?.failed ?? "Could not modify the Svelte or Vite config.", d = s(t, a), h = null, g = "", _ = null, v = null, y = !1;
92
92
  if (d) {
93
93
  h = c().addSourceFileAtPath(d), g = h.getFullText(), _ = f(h);
94
94
  let e = _?.getArguments()[0];
@@ -98,7 +98,7 @@ function h(e, n) {
98
98
  status: "resolved",
99
99
  target: p(h, d, v, g)
100
100
  };
101
- let b = s(e, o), x = null, S = "", C = null;
101
+ let b = s(t, o), x = null, S = "", C = null;
102
102
  if (b && (x = c().addSourceFileAtPath(b), S = x.getFullText(), C = l(x)), x && b && C) return {
103
103
  status: "resolved",
104
104
  target: m(x, b, C, S)
@@ -126,7 +126,7 @@ function h(e, n) {
126
126
  } : {
127
127
  status: "not-found",
128
128
  message: r,
129
- filePath: d ?? b ?? t.join(e, a[0])
129
+ filePath: d ?? b ?? e.join(t, a[0])
130
130
  };
131
131
  }
132
132
  function g(e) {
@@ -160,4 +160,4 @@ function _(e, t, n) {
160
160
  //#endregion
161
161
  export { s as a, _ as i, d as n, h as o, u as r, g as s, a as t };
162
162
 
163
- //# sourceMappingURL=config-target-Co-ij8p3.js.map
163
+ //# sourceMappingURL=config-target-DOi8kI_f.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-target-Co-ij8p3.js","names":[],"sources":["../../src/runtime/config-target.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type CallExpression,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport const VITE_CONFIG_CANDIDATES = [\n \"vite.config.ts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.cjs\",\n];\n\nexport const SVELTE_CONFIG_CANDIDATES = [\n \"svelte.config.ts\",\n \"svelte.config.js\",\n \"svelte.config.mjs\",\n \"svelte.config.cjs\",\n];\n\nexport type ConfigKind = \"svelte-config\" | \"vite-inline\";\n\n/**\n * A resolved place to read/write SvelteKit configuration. Either the default\n * export object of a `svelte.config.*` file, or the inline argument object of\n * the `sveltekit()` call inside a `vite.config.*` file.\n *\n * The only structural difference between the two is where kit-namespaced\n * settings (adapter, alias, experimental) live: under `config.kit` in\n * svelte.config, but flattened onto the `sveltekit()` arg in vite-inline.\n * `kitContainer()` papers over that; everything else (`compilerOptions`,\n * `preprocess`, `extensions`) sits at the root of `configObject` in both.\n */\nexport interface ConfigTarget {\n kind: ConfigKind;\n /** The file to add imports to and save. */\n sourceFile: SourceFile;\n /** Absolute path of the resolved file. */\n filePath: string;\n /** svelte.config default-export object OR the `sveltekit()` arg object. */\n configObject: ObjectLiteralExpression;\n /** Full text captured before any mutation, for change detection. */\n originalText: string;\n /** Object that owns kit-namespaced settings (adapter, alias, experimental). */\n kitContainer(): ObjectLiteralExpression | null;\n}\n\nexport type ResolveResult =\n | { status: \"resolved\"; target: ConfigTarget }\n | { status: \"not-found\"; message: string; filePath: string }\n | { status: \"failed\"; message: string; filePath: string };\n\n/** Result shape returned by every config modifier so call sites can build a File. */\nexport interface ConfigModifyResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(\n root: string,\n candidates: string[],\n): string | null {\n for (const rel of candidates) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * Resolve the config object exported as default — handles both\n * `export default { ... }` and `const config = { ... }; export default config`.\n */\nexport function getDefaultExportObject(\n sourceFile: SourceFile,\n): ObjectLiteralExpression | null {\n const defaultExport = sourceFile.getExportAssignment(\n (ea) => !ea.isExportEquals(),\n );\n const exportedExpr = defaultExport?.getExpression();\n if (exportedExpr?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return exportedExpr as ObjectLiteralExpression;\n }\n if (exportedExpr?.getKind() === SyntaxKind.Identifier) {\n const ident = exportedExpr.getText();\n const varDecl = sourceFile.getVariableDeclaration(ident);\n const init = varDecl?.getInitializer();\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return init as ObjectLiteralExpression;\n }\n }\n return null;\n}\n\n/**\n * Get the object-literal value of property `name` on `obj`, creating it as an\n * empty object if missing (or replacing a non-object initializer). Returns null\n * if the property can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n obj: ObjectLiteralExpression,\n name: string,\n initializer: string,\n): ObjectLiteralExpression | null {\n const prop = obj.getProperty(name);\n if (!prop) {\n obj.addPropertyAssignment({ name, initializer });\n const added = obj.getProperty(name);\n if (!added || added.getKind() !== SyntaxKind.PropertyAssignment)\n return null;\n const init = (\n added as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ObjectLiteralExpression)\n return null;\n return init as ObjectLiteralExpression;\n }\n\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n const init = (prop as import(\"ts-morph\").PropertyAssignment).getInitializer();\n if (!init) return null;\n if (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n (prop as import(\"ts-morph\").PropertyAssignment).setInitializer(initializer);\n const init2 = (\n prop as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n return init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (init2 as ObjectLiteralExpression)\n : null;\n }\n\n return init as ObjectLiteralExpression;\n}\n\n/** Ensure `obj[name] === true`. Returns whether a change was made. */\nexport function ensureBooleanTrue(\n obj: ObjectLiteralExpression,\n name: string,\n): boolean {\n const existing = obj.getProperty(name);\n if (!existing) {\n obj.addPropertyAssignment({ name, initializer: \"true\" });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (init?.getText() === \"true\") return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\"true\");\n return true;\n}\n\nfunction findSveltekitCall(sourceFile: SourceFile): CallExpression | null {\n return (\n sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"sveltekit\") ?? null\n );\n}\n\nfunction makeViteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"vite-inline\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n // kit-namespaced settings are flattened onto the sveltekit() arg.\n kitContainer: () => configObject,\n };\n}\n\nfunction makeSvelteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"svelte-config\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n kitContainer: () =>\n getOrCreateObjectLiteralProperty(configObject, \"kit\", \"{}\"),\n };\n}\n\n/**\n * Resolve where SvelteKit config should be read/written, mirroring SvelteKit's\n * own resolution order:\n * 1. `vite.config.*` has a `sveltekit(<object>)` call with an inline arg → use it\n * (svelte.config is ignored by Kit when this exists).\n * 2. else a `svelte.config.*` with a parseable default-export object → use it.\n * 3. else a bare `sveltekit()` in vite.config → create `{}` and use it (the new default).\n */\nexport function resolveConfigTarget(\n root: string,\n hints?: { notFound?: string; failed?: string },\n): ResolveResult {\n const notFound =\n hints?.notFound ?? \"Could not find a Svelte or Vite config to modify.\";\n const failed = hints?.failed ?? \"Could not modify the Svelte or Vite config.\";\n\n // --- Inspect vite.config.* ---\n const vitePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n let viteSourceFile: SourceFile | null = null;\n let viteOriginal = \"\";\n let sveltekitCall: CallExpression | null = null;\n let viteInlineArg: ObjectLiteralExpression | null = null;\n let viteNonObjectArg = false;\n\n if (vitePath) {\n viteSourceFile = newProject().addSourceFileAtPath(vitePath);\n viteOriginal = viteSourceFile.getFullText();\n sveltekitCall = findSveltekitCall(viteSourceFile);\n const arg = sveltekitCall?.getArguments()[0];\n if (arg) {\n if (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n viteInlineArg = arg as ObjectLiteralExpression;\n } else {\n viteNonObjectArg = true;\n }\n }\n }\n\n // Rule 1: vite.config carries an inline object arg → target it.\n if (viteSourceFile && vitePath && viteInlineArg) {\n return {\n status: \"resolved\",\n target: makeViteTarget(\n viteSourceFile,\n vitePath,\n viteInlineArg,\n viteOriginal,\n ),\n };\n }\n\n // --- Inspect svelte.config.* ---\n const sveltePath = probeFirstExisting(root, SVELTE_CONFIG_CANDIDATES);\n let svelteSourceFile: SourceFile | null = null;\n let svelteOriginal = \"\";\n let svelteConfigObj: ObjectLiteralExpression | null = null;\n if (sveltePath) {\n svelteSourceFile = newProject().addSourceFileAtPath(sveltePath);\n svelteOriginal = svelteSourceFile.getFullText();\n svelteConfigObj = getDefaultExportObject(svelteSourceFile);\n }\n\n // Rule 2: svelte.config with a parseable config object → target it.\n if (svelteSourceFile && sveltePath && svelteConfigObj) {\n return {\n status: \"resolved\",\n target: makeSvelteTarget(\n svelteSourceFile,\n sveltePath,\n svelteConfigObj,\n svelteOriginal,\n ),\n };\n }\n\n // Rule 3: bare `sveltekit()` in vite.config → create `{}` arg and target it.\n if (viteSourceFile && vitePath && sveltekitCall) {\n if (viteNonObjectArg) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n const created = sveltekitCall\n .addArgument(\"{}\")\n .asKind(SyntaxKind.ObjectLiteralExpression);\n if (!created) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n return {\n status: \"resolved\",\n target: makeViteTarget(viteSourceFile, vitePath, created, viteOriginal),\n };\n }\n\n // svelte.config exists but its shape is unparseable.\n if (sveltePath && !svelteConfigObj) {\n return { status: \"failed\", message: failed, filePath: sveltePath };\n }\n\n const reportPath =\n vitePath ?? sveltePath ?? path.join(root, VITE_CONFIG_CANDIDATES[0]);\n return { status: \"not-found\", message: notFound, filePath: reportPath };\n}\n\n/** Format, compare against the captured original, and save only if changed. */\nexport function saveTarget(target: ConfigTarget): ModifyOutcome {\n target.sourceFile.formatText();\n const newText = target.sourceFile.getFullText();\n if (newText === target.originalText) {\n return { status: \"success\", changed: false };\n }\n target.sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n\n/**\n * Resolve a config target and run `mutate` against it. Handles the\n * not-found/failed branches and change detection uniformly. `mutate` returns\n * `false` when the config shape can't be safely edited (→ failed).\n */\nexport function modifyConfig(\n root: string,\n hints: { notFound: string; failed: string },\n mutate: (target: ConfigTarget) => boolean,\n): ConfigModifyResult {\n const res = resolveConfigTarget(root, hints);\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const ok = mutate(res.target);\n if (!ok) {\n return {\n filePath: res.target.filePath,\n outcome: { status: \"failed\", message: hints.failed },\n };\n }\n return { filePath: res.target.filePath, outcome: saveTarget(res.target) };\n}\n"],"mappings":";;;;AAYA,IAAa,IAAyB;CACpC;CACA;CACA;CACA;AACF,GAEa,IAA2B;CACtC;CACA;CACA;CACA;AACF;AAyCA,SAAgB,EACd,GACA,GACe;CACf,KAAK,IAAM,KAAO,GAAY;EAC5B,IAAM,IAAM,EAAK,KAAK,GAAM,CAAG;EAC/B,IAAI,EAAG,WAAW,CAAG,GAAG,OAAO;CACjC;CACA,OAAO;AACT;AAEA,SAAS,IAAsB;CAC7B,OAAO,IAAI,EAAQ;EACjB,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CAAC;AACH;AAMA,SAAgB,EACd,GACgC;CAIhC,IAAM,IAHgB,EAAW,qBAC9B,MAAO,CAAC,EAAG,eAAe,CAER,CAAA,EAAe,cAAc;CAClD,IAAI,GAAc,QAAQ,MAAM,EAAW,yBACzC,OAAO;CAET,IAAI,GAAc,QAAQ,MAAM,EAAW,YAAY;EACrD,IAAM,IAAQ,EAAa,QAAQ,GAE7B,IADU,EAAW,uBAAuB,CACrC,CAAA,EAAS,eAAe;EACrC,IAAI,GAAM,QAAQ,MAAM,EAAW,yBACjC,OAAO;CAEX;CACA,OAAO;AACT;AAOA,SAAgB,EACd,GACA,GACA,GACgC;CAChC,IAAM,IAAO,EAAI,YAAY,CAAI;CACjC,IAAI,CAAC,GAAM;EACT,EAAI,sBAAsB;GAAE;GAAM;EAAY,CAAC;EAC/C,IAAM,IAAQ,EAAI,YAAY,CAAI;EAClC,IAAI,CAAC,KAAS,EAAM,QAAQ,MAAM,EAAW,oBAC3C,OAAO;EACT,IAAM,IACJ,EACA,eAAe;EAGjB,OAFI,CAAC,KAA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;CACpB,IAAM,IAAM,EAAoB,GAAM,CAAK;CAc3C,OAbI,EAAI,WAAW,aAMR,EAAO,EAAI,MACjB,IAME;EAAE,UAAU,EAAI,OAAO;EAAU,SAAS,EAAW,EAAI,MAAM;CAAE,IAL/D;EACL,UAAU,EAAI,OAAO;EACrB,SAAS;GAAE,QAAQ;GAAU,SAAS,EAAM;EAAO;CACrD,IAVO;EACL,UAAU,EAAI;EACd,SAAS;GAAE,QAAQ,EAAI;GAAQ,SAAS,EAAI;EAAQ;CACtD;AAUJ"}
1
+ {"version":3,"file":"config-target-DOi8kI_f.js","names":[],"sources":["../../src/runtime/config-target.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type CallExpression,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport const VITE_CONFIG_CANDIDATES = [\n \"vite.config.ts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.cjs\",\n];\n\nexport const SVELTE_CONFIG_CANDIDATES = [\n \"svelte.config.ts\",\n \"svelte.config.js\",\n \"svelte.config.mjs\",\n \"svelte.config.cjs\",\n];\n\nexport type ConfigKind = \"svelte-config\" | \"vite-inline\";\n\n/**\n * A resolved place to read/write SvelteKit configuration. Either the default\n * export object of a `svelte.config.*` file, or the inline argument object of\n * the `sveltekit()` call inside a `vite.config.*` file.\n *\n * The only structural difference between the two is where kit-namespaced\n * settings (adapter, alias, experimental) live: under `config.kit` in\n * svelte.config, but flattened onto the `sveltekit()` arg in vite-inline.\n * `kitContainer()` papers over that; everything else (`compilerOptions`,\n * `preprocess`, `extensions`) sits at the root of `configObject` in both.\n */\nexport interface ConfigTarget {\n kind: ConfigKind;\n /** The file to add imports to and save. */\n sourceFile: SourceFile;\n /** Absolute path of the resolved file. */\n filePath: string;\n /** svelte.config default-export object OR the `sveltekit()` arg object. */\n configObject: ObjectLiteralExpression;\n /** Full text captured before any mutation, for change detection. */\n originalText: string;\n /** Object that owns kit-namespaced settings (adapter, alias, experimental). */\n kitContainer(): ObjectLiteralExpression | null;\n}\n\nexport type ResolveResult =\n | { status: \"resolved\"; target: ConfigTarget }\n | { status: \"not-found\"; message: string; filePath: string }\n | { status: \"failed\"; message: string; filePath: string };\n\n/** Result shape returned by every config modifier so call sites can build a File. */\nexport interface ConfigModifyResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(\n root: string,\n candidates: string[],\n): string | null {\n for (const rel of candidates) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * Resolve the config object exported as default — handles both\n * `export default { ... }` and `const config = { ... }; export default config`.\n */\nexport function getDefaultExportObject(\n sourceFile: SourceFile,\n): ObjectLiteralExpression | null {\n const defaultExport = sourceFile.getExportAssignment(\n (ea) => !ea.isExportEquals(),\n );\n const exportedExpr = defaultExport?.getExpression();\n if (exportedExpr?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return exportedExpr as ObjectLiteralExpression;\n }\n if (exportedExpr?.getKind() === SyntaxKind.Identifier) {\n const ident = exportedExpr.getText();\n const varDecl = sourceFile.getVariableDeclaration(ident);\n const init = varDecl?.getInitializer();\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return init as ObjectLiteralExpression;\n }\n }\n return null;\n}\n\n/**\n * Get the object-literal value of property `name` on `obj`, creating it as an\n * empty object if missing (or replacing a non-object initializer). Returns null\n * if the property can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n obj: ObjectLiteralExpression,\n name: string,\n initializer: string,\n): ObjectLiteralExpression | null {\n const prop = obj.getProperty(name);\n if (!prop) {\n obj.addPropertyAssignment({ name, initializer });\n const added = obj.getProperty(name);\n if (!added || added.getKind() !== SyntaxKind.PropertyAssignment)\n return null;\n const init = (\n added as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ObjectLiteralExpression)\n return null;\n return init as ObjectLiteralExpression;\n }\n\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n const init = (prop as import(\"ts-morph\").PropertyAssignment).getInitializer();\n if (!init) return null;\n if (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n (prop as import(\"ts-morph\").PropertyAssignment).setInitializer(initializer);\n const init2 = (\n prop as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n return init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (init2 as ObjectLiteralExpression)\n : null;\n }\n\n return init as ObjectLiteralExpression;\n}\n\n/** Ensure `obj[name] === true`. Returns whether a change was made. */\nexport function ensureBooleanTrue(\n obj: ObjectLiteralExpression,\n name: string,\n): boolean {\n const existing = obj.getProperty(name);\n if (!existing) {\n obj.addPropertyAssignment({ name, initializer: \"true\" });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (init?.getText() === \"true\") return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\"true\");\n return true;\n}\n\nfunction findSveltekitCall(sourceFile: SourceFile): CallExpression | null {\n return (\n sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"sveltekit\") ?? null\n );\n}\n\nfunction makeViteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"vite-inline\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n // kit-namespaced settings are flattened onto the sveltekit() arg.\n kitContainer: () => configObject,\n };\n}\n\nfunction makeSvelteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"svelte-config\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n kitContainer: () =>\n getOrCreateObjectLiteralProperty(configObject, \"kit\", \"{}\"),\n };\n}\n\n/**\n * Resolve where SvelteKit config should be read/written, mirroring SvelteKit's\n * own resolution order:\n * 1. `vite.config.*` has a `sveltekit(<object>)` call with an inline arg → use it\n * (svelte.config is ignored by Kit when this exists).\n * 2. else a `svelte.config.*` with a parseable default-export object → use it.\n * 3. else a bare `sveltekit()` in vite.config → create `{}` and use it (the new default).\n */\nexport function resolveConfigTarget(\n root: string,\n hints?: { notFound?: string; failed?: string },\n): ResolveResult {\n const notFound =\n hints?.notFound ?? \"Could not find a Svelte or Vite config to modify.\";\n const failed = hints?.failed ?? \"Could not modify the Svelte or Vite config.\";\n\n // --- Inspect vite.config.* ---\n const vitePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n let viteSourceFile: SourceFile | null = null;\n let viteOriginal = \"\";\n let sveltekitCall: CallExpression | null = null;\n let viteInlineArg: ObjectLiteralExpression | null = null;\n let viteNonObjectArg = false;\n\n if (vitePath) {\n viteSourceFile = newProject().addSourceFileAtPath(vitePath);\n viteOriginal = viteSourceFile.getFullText();\n sveltekitCall = findSveltekitCall(viteSourceFile);\n const arg = sveltekitCall?.getArguments()[0];\n if (arg) {\n if (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n viteInlineArg = arg as ObjectLiteralExpression;\n } else {\n viteNonObjectArg = true;\n }\n }\n }\n\n // Rule 1: vite.config carries an inline object arg → target it.\n if (viteSourceFile && vitePath && viteInlineArg) {\n return {\n status: \"resolved\",\n target: makeViteTarget(\n viteSourceFile,\n vitePath,\n viteInlineArg,\n viteOriginal,\n ),\n };\n }\n\n // --- Inspect svelte.config.* ---\n const sveltePath = probeFirstExisting(root, SVELTE_CONFIG_CANDIDATES);\n let svelteSourceFile: SourceFile | null = null;\n let svelteOriginal = \"\";\n let svelteConfigObj: ObjectLiteralExpression | null = null;\n if (sveltePath) {\n svelteSourceFile = newProject().addSourceFileAtPath(sveltePath);\n svelteOriginal = svelteSourceFile.getFullText();\n svelteConfigObj = getDefaultExportObject(svelteSourceFile);\n }\n\n // Rule 2: svelte.config with a parseable config object → target it.\n if (svelteSourceFile && sveltePath && svelteConfigObj) {\n return {\n status: \"resolved\",\n target: makeSvelteTarget(\n svelteSourceFile,\n sveltePath,\n svelteConfigObj,\n svelteOriginal,\n ),\n };\n }\n\n // Rule 3: bare `sveltekit()` in vite.config → create `{}` arg and target it.\n if (viteSourceFile && vitePath && sveltekitCall) {\n if (viteNonObjectArg) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n const created = sveltekitCall\n .addArgument(\"{}\")\n .asKind(SyntaxKind.ObjectLiteralExpression);\n if (!created) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n return {\n status: \"resolved\",\n target: makeViteTarget(viteSourceFile, vitePath, created, viteOriginal),\n };\n }\n\n // svelte.config exists but its shape is unparseable.\n if (sveltePath && !svelteConfigObj) {\n return { status: \"failed\", message: failed, filePath: sveltePath };\n }\n\n const reportPath =\n vitePath ?? sveltePath ?? path.join(root, VITE_CONFIG_CANDIDATES[0]);\n return { status: \"not-found\", message: notFound, filePath: reportPath };\n}\n\n/** Format, compare against the captured original, and save only if changed. */\nexport function saveTarget(target: ConfigTarget): ModifyOutcome {\n target.sourceFile.formatText();\n const newText = target.sourceFile.getFullText();\n if (newText === target.originalText) {\n return { status: \"success\", changed: false };\n }\n target.sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n\n/**\n * Resolve a config target and run `mutate` against it. Handles the\n * not-found/failed branches and change detection uniformly. `mutate` returns\n * `false` when the config shape can't be safely edited (→ failed).\n */\nexport function modifyConfig(\n root: string,\n hints: { notFound: string; failed: string },\n mutate: (target: ConfigTarget) => boolean,\n): ConfigModifyResult {\n const res = resolveConfigTarget(root, hints);\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const ok = mutate(res.target);\n if (!ok) {\n return {\n filePath: res.target.filePath,\n outcome: { status: \"failed\", message: hints.failed },\n };\n }\n return { filePath: res.target.filePath, outcome: saveTarget(res.target) };\n}\n"],"mappings":";;;;AAYA,IAAa,IAAyB;CACpC;CACA;CACA;CACA;AACF,GAEa,IAA2B;CACtC;CACA;CACA;CACA;AACF;AAyCA,SAAgB,EACd,GACA,GACe;CACf,KAAK,IAAM,KAAO,GAAY;EAC5B,IAAM,IAAM,EAAK,KAAK,GAAM,CAAG;EAC/B,IAAI,EAAG,WAAW,CAAG,GAAG,OAAO;CACjC;CACA,OAAO;AACT;AAEA,SAAS,IAAsB;CAC7B,OAAO,IAAI,EAAQ;EACjB,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CAAC;AACH;AAMA,SAAgB,EACd,GACgC;CAIhC,IAAM,IAHgB,EAAW,qBAC9B,MAAO,CAAC,EAAG,eAAe,CAER,CAAA,EAAe,cAAc;CAClD,IAAI,GAAc,QAAQ,MAAM,EAAW,yBACzC,OAAO;CAET,IAAI,GAAc,QAAQ,MAAM,EAAW,YAAY;EACrD,IAAM,IAAQ,EAAa,QAAQ,GAE7B,IADU,EAAW,uBAAuB,CACrC,CAAA,EAAS,eAAe;EACrC,IAAI,GAAM,QAAQ,MAAM,EAAW,yBACjC,OAAO;CAEX;CACA,OAAO;AACT;AAOA,SAAgB,EACd,GACA,GACA,GACgC;CAChC,IAAM,IAAO,EAAI,YAAY,CAAI;CACjC,IAAI,CAAC,GAAM;EACT,EAAI,sBAAsB;GAAE;GAAM;EAAY,CAAC;EAC/C,IAAM,IAAQ,EAAI,YAAY,CAAI;EAClC,IAAI,CAAC,KAAS,EAAM,QAAQ,MAAM,EAAW,oBAC3C,OAAO;EACT,IAAM,IACJ,EACA,eAAe;EAGjB,OAFI,CAAC,KAAQ,EAAK,QAAQ,MAAM,EAAW,0BAClC,OACF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Ac3C,OAbI,EAAI,WAAW,aAMR,EAAO,EAAI,MACjB,IAME;EAAE,UAAU,EAAI,OAAO;EAAU,SAAS,EAAW,EAAI,MAAM;CAAE,IAL/D;EACL,UAAU,EAAI,OAAO;EACrB,SAAS;GAAE,QAAQ;GAAU,SAAS,EAAM;EAAO;CACrD,IAVO;EACL,UAAU,EAAI;EACd,SAAS;GAAE,QAAQ,EAAI;GAAQ,SAAS,EAAI;EAAQ;CACtD;AAUJ"}
@@ -1,8 +1,8 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
2
  import { modifyOutcomeToFile as t } from "./modify-file-PVKmDJHk.js";
3
3
  import { a as n, o as r, r as i } from "./ts-morph-helpers-Bk82Z2n7.js";
4
- import a from "node:fs";
5
- import o from "node:path";
4
+ import a from "node:path";
5
+ import o from "node:fs";
6
6
  import { Project as s, QuoteKind as c, SyntaxKind as l } from "ts-morph";
7
7
  //#region src/patterns/disable/content-negotiation/modifies/hooks.server.ts
8
8
  function u(e) {
@@ -22,11 +22,11 @@ function d(e) {
22
22
  n && (t.getNamedImports().length === 1 && !t.getDefaultImport() ? t.remove() : n.remove());
23
23
  }
24
24
  function f(e) {
25
- if (!a.existsSync(e)) return {
25
+ if (!o.existsSync(e)) return {
26
26
  status: "success",
27
27
  changed: !1
28
28
  };
29
- let t = a.readFileSync(e, "utf8");
29
+ let t = o.readFileSync(e, "utf8");
30
30
  if (!t.includes("handleNegotiate")) return {
31
31
  status: "success",
32
32
  changed: !1
@@ -69,11 +69,11 @@ function m(e) {
69
69
  return e.getStatements().every((e) => e.getKind() === l.EmptyStatement);
70
70
  }
71
71
  function h(e) {
72
- if (!a.existsSync(e)) return {
72
+ if (!o.existsSync(e)) return {
73
73
  status: "success",
74
74
  changed: !1
75
75
  };
76
- let t = a.readFileSync(e, "utf8");
76
+ let t = o.readFileSync(e, "utf8");
77
77
  if (!t.includes("negotiateReroute")) return {
78
78
  status: "success",
79
79
  changed: !1
@@ -81,8 +81,8 @@ function h(e) {
81
81
  let n = new s({
82
82
  compilerOptions: { allowJs: !0 },
83
83
  manipulationSettings: { quoteKind: c.Single }
84
- }).addSourceFileAtPath(e), r = n.getVariableDeclaration("reroute"), i = (r?.getInitializer())?.getText() ?? "", o = n.getVariableDeclarations().some((e) => e.getName() === "rerouteDeLocalize");
85
- return r && o && i.includes("rerouteDeLocalize") && i.includes("negotiateReroute") ? r.setInitializer("({ url }) => rerouteDeLocalize(url.pathname)") : r && i.includes("negotiateReroute") && r.getFirstAncestorByKind(l.VariableStatement)?.remove(), p(n), m(n) ? (a.rmSync(e, { force: !0 }), {
84
+ }).addSourceFileAtPath(e), r = n.getVariableDeclaration("reroute"), i = (r?.getInitializer())?.getText() ?? "", a = n.getVariableDeclarations().some((e) => e.getName() === "rerouteDeLocalize");
85
+ return r && a && i.includes("rerouteDeLocalize") && i.includes("negotiateReroute") ? r.setInitializer("({ url }) => rerouteDeLocalize(url.pathname)") : r && i.includes("negotiateReroute") && r.getFirstAncestorByKind(l.VariableStatement)?.remove(), p(n), m(n) ? (o.rmSync(e, { force: !0 }), {
86
86
  status: "success",
87
87
  changed: !0
88
88
  }) : (n.formatText(), n.saveSync(), {
@@ -93,17 +93,17 @@ function h(e) {
93
93
  //#endregion
94
94
  //#region src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts
95
95
  function g(e) {
96
- if (!a.existsSync(e)) return {
96
+ if (!o.existsSync(e)) return {
97
97
  status: "success",
98
98
  changed: !1
99
99
  };
100
- let t = r.fromPath(e), o = t.hasElement("Negotiate");
100
+ let t = r.fromPath(e), a = t.hasElement("Negotiate");
101
101
  return t.modifyScript((e) => {
102
102
  let { source: t } = n(e, (e) => {
103
103
  i(e, "$lib/negotiate");
104
104
  });
105
105
  return t;
106
- }), o && t.removeElement("Negotiate"), t.writeTo(e), {
106
+ }), a && t.removeElement("Negotiate"), t.writeTo(e), {
107
107
  status: "success",
108
108
  changed: t.hasChanged()
109
109
  };
@@ -111,16 +111,16 @@ function g(e) {
111
111
  //#endregion
112
112
  //#region src/patterns/disable/content-negotiation/generate.runtime.ts
113
113
  async function _(n) {
114
- let r = e(n), i = [], a = (e) => {
114
+ let r = e(n), i = [], o = (e) => {
115
115
  e && i.push(e);
116
116
  };
117
117
  r.info("Reverting hooks.server.ts");
118
- let s = o.join(n.root, "src", "hooks.server.ts");
119
- a(t(s, f(s))), r.info("Reverting hooks.ts");
120
- let c = o.join(n.root, "src", "hooks.ts");
121
- a(t(c, h(c))), r.info("Reverting src/routes/+layout.svelte");
122
- let l = o.join(n.root, "src", "routes", "+layout.svelte");
123
- return a(t(l, g(l))), {
118
+ let s = a.join(n.root, "src", "hooks.server.ts");
119
+ o(t(s, f(s))), r.info("Reverting hooks.ts");
120
+ let c = a.join(n.root, "src", "hooks.ts");
121
+ o(t(c, h(c))), r.info("Reverting src/routes/+layout.svelte");
122
+ let l = a.join(n.root, "src", "routes", "+layout.svelte");
123
+ return o(t(l, g(l))), {
124
124
  creates: [],
125
125
  modifies: i,
126
126
  deletes: [],
@@ -134,4 +134,4 @@ async function _(n) {
134
134
  //#endregion
135
135
  export { _ as generate };
136
136
 
137
- //# sourceMappingURL=generate.runtime-6qpoLA04.js.map
137
+ //# sourceMappingURL=generate.runtime--0bYEUP_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-6qpoLA04.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n fs.rmSync(hooksPath, { force: true });\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, unmodifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAIA,SAAS,EAAsB,GAAiC;CAC9D,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,gBAAgB;CAC/D,IAAI,CAAC,GAAM,OAAO;CAElB,IAAM,IAAQ,EAAK,gBAAgB,CAAC,CAAC,MAAM,MAEvC,EAAG,QAAQ,MAAM,YACjB,EAAG,aAAa,CAAC,EAAE,QAAQ,MAAM,iBAEpC;CASD,OAPK,KAED,EAAK,gBAAgB,CAAC,CAAC,WAAW,KAAK,CAAC,EAAK,iBAAiB,IAChE,EAAK,OAAO,IAEZ,EAAM,OAAO,GAER,MAPY;AAQrB;AAEA,SAAS,EAA6B,GAA8B;CAClE,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAAqB;CAcpE,IAbI,CAAC,KAEmB,EACrB,qBAAqB,EAAW,UAAU,CAAC,CAC3C,MA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K,oBAAoB;CAChC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU;CAG3D,AAFA,EAAW,EAAoB,GAAW,EAAuB,CAAS,CAAC,CAAC,GAE5E,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPA,EACE,EACE,GACA,EAA4B,CAAc,CAC5C,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime--0bYEUP_.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n fs.rmSync(hooksPath, { force: true });\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, unmodifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAIA,SAAS,EAAsB,GAAiC;CAC9D,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,gBAAgB;CAC/D,IAAI,CAAC,GAAM,OAAO;CAElB,IAAM,IAAQ,EAAK,gBAAgB,CAAC,CAAC,MAAM,MAEvC,EAAG,QAAQ,MAAM,YACjB,EAAG,aAAa,CAAC,EAAE,QAAQ,MAAM,iBAEpC;CASD,OAPK,KAED,EAAK,gBAAgB,CAAC,CAAC,WAAW,KAAK,CAAC,EAAK,iBAAiB,IAChE,EAAK,OAAO,IAEZ,EAAM,OAAO,GAER,MAPY;AAQrB;AAEA,SAAS,EAA6B,GAA8B;CAClE,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAAqB;CAcpE,IAbI,CAAC,KAEmB,EACrB,qBAAqB,EAAW,UAAU,CAAC,CAC3C,MAAM,MAAO;EACZ,IAAI,EAAG,QAAQ,MAAM,YAAY,OAAO;EAExC,IAAM,IADS,EAAG,UACL,CAAA,EAAQ,QAAQ;EAC7B,OACE,MAAS,EAAW,mBAAmB,MAAS,EAAW;CAE/D,CAEE,GAAiB;CAErB,IAAM,IAAQ,EACX,gBAAgB,CAAC,CACjB,MAAM,MAAO,EAAG,QAAQ,MAAM,UAAU;CACtC,MAED,EAAK,gBAAgB,CAAC,CAAC,WAAW,KAAK,CAAC,EAAK,iBAAiB,IAChE,EAAK,OAAO,IAEZ,EAAM,OAAO;AAEjB;AAEA,SAAg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AAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,29 +1,29 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
- import { t } from "./shared-C4-NNykV.js";
2
+ import { t } from "./shared-BGvy1V-z.js";
3
3
  import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
4
4
  import { i as r, o as i } from "./ts-morph-helpers-Bk82Z2n7.js";
5
5
  import { n as a } from "./env-BPfk1VAw.js";
6
- import o from "node:fs";
7
- import s from "node:path";
6
+ import o from "node:path";
7
+ import s from "node:fs";
8
8
  import { Project as c, QuoteKind as l, SyntaxKind as u } from "ts-morph";
9
9
  //#region src/patterns/disable/payments/modifies/modify-nav-user.ts
10
10
  function d(e) {
11
- if (!o.existsSync(e)) return {
11
+ if (!s.existsSync(e)) return {
12
12
  status: "success",
13
13
  changed: !1
14
14
  };
15
- let t = o.readFileSync(e, "utf8");
15
+ let t = s.readFileSync(e, "utf8");
16
16
  if (!t.includes("/billing")) return {
17
17
  status: "success",
18
18
  changed: !1
19
19
  };
20
- let n = new i(t), a = !1, s = (e) => {
20
+ let n = new i(t), a = !1, o = (e) => {
21
21
  a || e((e) => {
22
22
  let t = r(e, "Billing", "@lucide/svelte/icons/credit-card");
23
23
  return t.wasRemoved && (a = !0), t.source;
24
24
  });
25
25
  };
26
- return s((e) => n.modifyModuleScript(e)), a || s((e) => n.modifyScript(e)), a ? (o.writeFileSync(e, n.toString(), "utf8"), {
26
+ return o((e) => n.modifyModuleScript(e)), a || o((e) => n.modifyScript(e)), a ? (s.writeFileSync(e, n.toString(), "utf8"), {
27
27
  status: "success",
28
28
  changed: !0
29
29
  }) : {
@@ -34,11 +34,11 @@ function d(e) {
34
34
  //#endregion
35
35
  //#region src/patterns/disable/payments/modifies/modify-user-signup.ts
36
36
  function f(e) {
37
- if (!o.existsSync(e)) return {
37
+ if (!s.existsSync(e)) return {
38
38
  status: "success",
39
39
  changed: !1
40
40
  };
41
- let t = o.readFileSync(e, "utf8");
41
+ let t = s.readFileSync(e, "utf8");
42
42
  if (!t.includes("linkStripeCustomer")) return {
43
43
  status: "success",
44
44
  changed: !1
@@ -60,10 +60,10 @@ function f(e) {
60
60
  //#endregion
61
61
  //#region src/patterns/disable/payments/generate.runtime.ts
62
62
  async function p(r) {
63
- let i = r.features.auth, o = e(r), c = [], l = (e) => {
63
+ let i = r.features.auth, s = e(r), c = [], l = (e) => {
64
64
  e && c.push(e);
65
65
  };
66
- o.info("Stripping Stripe credentials from .env");
66
+ s.info("Stripping Stripe credentials from .env");
67
67
  let u = [
68
68
  {
69
69
  type: "comment",
@@ -85,12 +85,12 @@ async function p(r) {
85
85
  type: "var",
86
86
  key: "INTERNAL_JOB_SECRET"
87
87
  }
88
- ], p = s.join(r.root, ".env");
88
+ ], p = o.join(r.root, ".env");
89
89
  if (l(n(p, a(p, u))), i) {
90
- o.info("Reverting nav-user.svelte");
91
- let e = s.join(r.root, "src", "lib", "components", "nav-user.svelte");
92
- l(n(e, d(e))), o.info("Reverting signup +page.server.ts");
93
- let t = s.join(r.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
90
+ s.info("Reverting nav-user.svelte");
91
+ let e = o.join(r.root, "src", "lib", "components", "nav-user.svelte");
92
+ l(n(e, d(e))), s.info("Reverting signup +page.server.ts");
93
+ let t = o.join(r.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
94
94
  l(n(t, f(t)));
95
95
  }
96
96
  return {
@@ -113,4 +113,4 @@ async function p(r) {
113
113
  //#endregion
114
114
  export { p as generate };
115
115
 
116
- //# sourceMappingURL=generate.runtime-DBG6kEKb.js.map
116
+ //# sourceMappingURL=generate.runtime-677mL0-8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DBG6kEKb.js","names":[],"sources":["../../src/patterns/disable/payments/modifies/modify-nav-user.ts","../../src/patterns/disable/payments/modifies/modify-user-signup.ts","../../src/patterns/disable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"Billing\",\n \"@lucide/svelte/icons/credit-card\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (!originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const stripeImport = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/stripe\");\n if (stripeImport) stripeImport.remove();\n\n const linkFn = sourceFile.getVariableStatement((s) =>\n s.getDeclarations().some((d) => d.getName() === \"linkStripeCustomer\"),\n );\n if (linkFn) linkFn.remove();\n\n const callStatements = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"linkStripeCustomer\");\n for (const call of callStatements) {\n const stmt = call.getFirstAncestorByKind(SyntaxKind.ExpressionStatement);\n if (stmt) stmt.remove();\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvRemove, type EnvEdit } from \"../../../runtime/env\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Stripping Stripe credentials from .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\" },\n { type: \"var\", key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\" },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\" },\n { type: \"var\", key: \"INTERNAL_JOB_SECRET\" },\n ];\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnvRemove(envPath, envEdits)));\n\n if (isAppMode) {\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, unmodifyUserSignup(userSignupPath)),\n );\n }\n\n const collectionNames = [\n \"transactions\",\n \"stripe_customers\",\n \"stripe_payment_methods\",\n \"stripe_prices\",\n \"stripe_products\",\n ];\n const collectionDrops = await planDropsForCollections(\n isAppMode ? collectionNames : [\"stripe_prices\", \"stripe_products\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;AAKA,SAAgB,EAAgB,GAAoC;CAClE,IAAI,CAAC,EAAG,WAAW,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAS,EAAG,aAAa,GAAa,MAAM;CAClD,IAAI,CAAC,EAAO,SAAS,UAAU,GAC7B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAO,IAAI,EAAW,CAAM,GAC9B,IAAa,IAEX,KAAa,MAAgD;EAC7D,KACJ,GAAK,MAAQ;GACX,IAAM,IAAS,EACb,GACA,WACA,kCACF;GAEA,OADI,EAAO,eAAY,IAAa,KAC7B,EAAO;EAChB,CAAC;CACH;CAUA,OARA,GAAW,MAAO,EAAK,mBAAmB,CAAE,CAAC,GACxC,KAAY,GAAW,MAAO,EAAK,aAAa,CAAE,CAAC,GAEnD,KAIL,EAAG,cAAc,GAAa,EAAK,SAAS,GAAG,MAAM,GAC9C;EAAE,QAAQ;EAAW,SAAS;CAAK,KAJjC;EAAE,QAAQ;EAAW,SAAS;CAAM;AAK/C;;;ACpCA,SAAgB,EAAmB,GAAuC;CACxE,IAAI,CAAC,EAAG,WAAW,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAgB,MAAM;CAC7D,IAAI,CAAC,EAAe,SAAS,oBAAoB,G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AAgB,GAAS,CAAQ,CAAC,CAAC,GAEvE,GAAW;EACb,EAAO,KAAK,2BAA2B;EACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFA,EAAW,EAAoB,GAAa,EAAgB,CAAW,CAAC,CAAC,GAEzE,EAAO,KAAK,kCAAkC;EAC9C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACE,EAAoB,GAAgB,EAAmB,CAAc,CAAC,CACxE;CACF;CAcA,OAAO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4B,EAC5B,IAAY;GAPZ;GACA;GACA;GACA;GACA;EAGY,IAAkB,CAAC,iBAAiB,iBAAiB,GACjE,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-677mL0-8.js","names":[],"sources":["../../src/patterns/disable/payments/modifies/modify-nav-user.ts","../../src/patterns/disable/payments/modifies/modify-user-signup.ts","../../src/patterns/disable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"Billing\",\n \"@lucide/svelte/icons/credit-card\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (!originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const stripeImport = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/stripe\");\n if (stripeImport) stripeImport.remove();\n\n const linkFn = sourceFile.getVariableStatement((s) =>\n s.getDeclarations().some((d) => d.getName() === \"linkStripeCustomer\"),\n );\n if (linkFn) linkFn.remove();\n\n const callStatements = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"linkStripeCustomer\");\n for (const call of callStatements) {\n const stmt = call.getFirstAncestorByKind(SyntaxKind.ExpressionStatement);\n if (stmt) stmt.remove();\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvRemove, type EnvEdit } from \"../../../runtime/env\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Stripping Stripe credentials from .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\" },\n { type: \"var\", key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\" },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\" },\n { type: \"var\", key: \"INTERNAL_JOB_SECRET\" },\n ];\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnvRemove(envPath, envEdits)));\n\n if (isAppMode) {\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, unmodifyUserSignup(userSignupPath)),\n );\n }\n\n const collectionNames = [\n \"transactions\",\n \"stripe_customers\",\n \"stripe_payment_methods\",\n \"stripe_prices\",\n \"stripe_products\",\n ];\n const collectionDrops = await planDropsForCollections(\n isAppMode ? collectionNames : [\"stripe_prices\", \"stripe_products\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;AAKA,SAAgB,EAAgB,GAAoC;CAClE,IAAI,CAAC,EAAG,WAAW,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,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