@velastack/patterns 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -1
- package/dist/chunks/{collections-DcnlHh80.js → collections-wIKcIKzY.js} +2 -2
- package/dist/chunks/{collections-DcnlHh80.js.map → collections-wIKcIKzY.js.map} +1 -1
- package/dist/chunks/errors-D6gyegUK.js +14 -0
- package/dist/chunks/errors-D6gyegUK.js.map +1 -0
- package/dist/chunks/{generate-3QOmCHGZ.js → generate-vRi-W3rL.js} +2 -2
- package/dist/chunks/{generate-3QOmCHGZ.js.map → generate-vRi-W3rL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CL7NYB3N.js → generate.runtime-BX0QcpGg.js} +2 -2
- package/dist/chunks/{generate.runtime-CL7NYB3N.js.map → generate.runtime-BX0QcpGg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CsGO0zuZ.js → generate.runtime-BlK7yHff.js} +2 -2
- package/dist/chunks/{generate.runtime-CsGO0zuZ.js.map → generate.runtime-BlK7yHff.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CsBQGP_O.js → generate.runtime-BmW0th7X.js} +2 -2
- package/dist/chunks/{generate.runtime-CsBQGP_O.js.map → generate.runtime-BmW0th7X.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bhr2eJg6.js → generate.runtime-C4wcEIc9.js} +2 -2
- package/dist/chunks/{generate.runtime-Bhr2eJg6.js.map → generate.runtime-C4wcEIc9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CVc_YHTk.js → generate.runtime-CNrtLDCf.js} +2 -2
- package/dist/chunks/{generate.runtime-CVc_YHTk.js.map → generate.runtime-CNrtLDCf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CAEeX7Pf.js → generate.runtime-CQ0Veyk4.js} +2 -2
- package/dist/chunks/{generate.runtime-CAEeX7Pf.js.map → generate.runtime-CQ0Veyk4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DURymKCu.js → generate.runtime-CQWygx-F.js} +2 -2
- package/dist/chunks/{generate.runtime-DURymKCu.js.map → generate.runtime-CQWygx-F.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D0D5jods.js → generate.runtime-DOBfTVW3.js} +2 -2
- package/dist/chunks/{generate.runtime-D0D5jods.js.map → generate.runtime-DOBfTVW3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B3IKmGyV.js → generate.runtime-DpgPAnEd.js} +2 -2
- package/dist/chunks/{generate.runtime-B3IKmGyV.js.map → generate.runtime-DpgPAnEd.js.map} +1 -1
- package/dist/chunks/{shared-ClWQZdMa.js → shared-BZlvCHX8.js} +2 -2
- package/dist/chunks/{shared-ClWQZdMa.js.map → shared-BZlvCHX8.js.map} +1 -1
- package/dist/chunks/ui-DZS2SAQg.js +173 -0
- package/dist/chunks/ui-DZS2SAQg.js.map +1 -0
- package/dist/chunks/write-result-Cb3r0sCO.js +445 -0
- package/dist/chunks/write-result-Cb3r0sCO.js.map +1 -0
- package/dist/index.d.ts +109 -1
- package/dist/index.js +1878 -1842
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
- package/dist/chunks/errors-D3Zy3wCg.js +0 -10
- package/dist/chunks/errors-D3Zy3wCg.js.map +0 -1
- package/dist/chunks/write-result-8JW_vky2.js +0 -355
- package/dist/chunks/write-result-8JW_vky2.js.map +0 -1
package/README.md
CHANGED
|
@@ -77,7 +77,16 @@ lists in `components` is handed to `shadcn-svelte add`, which resolves it from t
|
|
|
77
77
|
- `customDependencies` must list every `$lib/components/ui/<x>` a shipped component imports, and
|
|
78
78
|
`customNpmPackages` every npm package no shadcn item installs for it.
|
|
79
79
|
- `installComponents()` is also exported from the package; `vela ui add` calls it. It is node-only and is
|
|
80
|
-
loaded on the first call, the same rule as `generate.runtime.ts`.
|
|
80
|
+
loaded on the first call, the same rule as `generate.runtime.ts`. Before spawning `shadcn-svelte add` it
|
|
81
|
+
checks bare item names against the style's registry index (`src/runtime/registry.ts`) and rejects
|
|
82
|
+
unknown ones with an `InvalidArgumentError`; when the registry cannot be read the check is skipped.
|
|
83
|
+
- `listComponents()`, `switchStyle()`, `applyBaseColor()` and `applyTheme()` (`src/runtime/ui.ts`) back
|
|
84
|
+
`vela ui list`, `vela ui style`, `vela ui base` and `vela ui theme`. Palette and font changes go through
|
|
85
|
+
`shadcn-svelte apply --preset <code> --only theme|font`; the preset code is produced by the project's own
|
|
86
|
+
`shadcn-svelte/preset` (`src/runtime/shadcn-preset.ts`), so the value lists never drift from what `apply`
|
|
87
|
+
accepts. The one vendored table is `STYLE_FONTS` (each style's designed font), guarded by a test against
|
|
88
|
+
the `shadcn-svelte` devDependency.
|
|
89
|
+
- `WriteResultRuntime.fetch` is the test seam for the registry, next to `executeCommand` for the spawns.
|
|
81
90
|
|
|
82
91
|
# Workflow for adding new patterns
|
|
83
92
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as e } from "./errors-
|
|
1
|
+
import { t as e } from "./errors-D6gyegUK.js";
|
|
2
2
|
import { i as t } from "./util-Bk7aQQJR.js";
|
|
3
3
|
import { n, t as r } from "./logger-CQONztPm.js";
|
|
4
4
|
import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-fERkp8b8.js";
|
|
@@ -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-
|
|
176
|
+
//# sourceMappingURL=collections-wIKcIKzY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections-DcnlHh80.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: 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;CACjB,IAAM,IAAqB,CAAC;CAE5B,KAAK,IAAM,KAAS,GAAS;EAC3B,IAAM,IAAU,EAAM,eAAe,QAAQ,MAAM,IAAI,GACjD,IAAM,MAAM,EAAG,YAAY,iB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AAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
|
|
1
|
+
{"version":3,"file":"collections-wIKcIKzY.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: 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,eA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EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/core/errors.ts
|
|
2
|
+
var e = class extends Error {
|
|
3
|
+
constructor(e) {
|
|
4
|
+
super(e), this.name = "InvalidArgumentError";
|
|
5
|
+
}
|
|
6
|
+
}, t = class extends Error {
|
|
7
|
+
constructor(e, t) {
|
|
8
|
+
super(`Could not read the shadcn-svelte registry at ${e}: ${t}`), this.name = "RegistryUnavailableError", this.url = e;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { t as n, e as t };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=errors-D6gyegUK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-D6gyegUK.js","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["export class InvalidArgumentError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidArgumentError\";\n }\n}\n\n/**\n * The shadcn-svelte registry could not be read (offline, a proxy, an outage).\n * Callers that only need the registry for a nicety, such as name checks or a\n * listing, catch this and degrade; callers that cannot proceed without it let\n * it surface as-is.\n */\nexport class RegistryUnavailableError extends Error {\n readonly url: string;\n\n constructor(url: string, reason: string) {\n super(`Could not read the shadcn-svelte registry at ${url}: ${reason}`);\n this.name = \"RegistryUnavailableError\";\n this.url = url;\n }\n}\n"],"mappings":";AAAA,IAAa,IAAb,cAA0C,MAAM;CAC9C,YAAY,GAAiB;EAE3B,AADA,MAAM,CAAO,GACb,KAAK,OAAO;CACd;AACF,GAQa,IAAb,cAA8C,MAAM;CAGlD,YAAY,GAAa,GAAgB;EAGvC,AAFA,MAAM,gDAAgD,EAAI,IAAI,GAAQ,GACtE,KAAK,OAAO,4BACZ,KAAK,MAAM;CACb;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as e } from "./errors-
|
|
1
|
+
import { t as e } from "./errors-D6gyegUK.js";
|
|
2
2
|
import { r as t } from "./util-Bk7aQQJR.js";
|
|
3
3
|
//#endregion
|
|
4
4
|
//#region src/patterns/enable/cms/generate.ts
|
|
@@ -87,4 +87,4 @@ async function l(e) {
|
|
|
87
87
|
//#endregion
|
|
88
88
|
export { s as n, l as t };
|
|
89
89
|
|
|
90
|
-
//# sourceMappingURL=generate-
|
|
90
|
+
//# sourceMappingURL=generate-vRi-W3rL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-
|
|
1
|
+
{"version":3,"file":"generate-vRi-W3rL.js","names":[],"sources":["../../src/patterns/enable/cms/generate.ts"],"sourcesContent":["import type { File, Options, Result } from \"../../../core/types\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport { filesFromGlob } from \"../../../core/util\";\n\n// The backend, for an app that hosts the CMS itself: the SQLite-backed HTTP\n// API and the two routes that mount it and serve uploads.\nconst backendRaw = import.meta.glob<string>(\"./creates-backend/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst BACKEND_PREFIX = \"./creates-backend/\";\n\n/** Where an app that hosts the backend itself mounts it. Also the admin bar's default. */\nexport const LOCAL_ENDPOINT = \"/api/cms\";\n\nexport const ENDPOINT_EXAMPLE =\n \"https://velastack.dev/v1/projects/<project>/cms\";\n\nexport interface CmsMode {\n /** What the read path and the admin bar talk to. */\n endpoint: string;\n /** Whether this app hosts the backend at `endpoint` itself. */\n local: boolean;\n}\n\n/** `--endpoint <url>` or `--endpoint=<url>`, for callers that hand flags through in argv. */\nfunction endpointFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--endpoint\") return argv[i + 1];\n if (arg.startsWith(\"--endpoint=\")) return arg.slice(\"--endpoint=\".length);\n }\n return undefined;\n}\n\n/**\n * Which of the two shapes to produce.\n *\n * An explicit `--endpoint` means a hosted CMS: the app only reads from it and\n * the admin bar signs in there, so no backend is installed. Without one, an\n * app with a server hosts the backend itself at `/api/cms`. A static site has\n * no server to host it, so there the endpoint is required.\n */\nexport function resolveMode(options: Options): CmsMode {\n const raw =\n typeof options.input.endpoint === \"string\"\n ? options.input.endpoint\n : endpointFromArgv(options.argv);\n const endpoint = raw?.trim().replace(/\\/+$/, \"\");\n\n if (endpoint) {\n if (!/^https?:\\/\\/\\S+$/.test(endpoint)) {\n throw new InvalidArgumentError(\n `--endpoint must be the absolute URL of a hosted CMS, like ${ENDPOINT_EXAMPLE}; got ${endpoint}`,\n );\n }\n return { endpoint, local: false };\n }\n\n if (!options.features.backend) {\n throw new InvalidArgumentError(\n \"This site has no server to host the CMS backend. \" +\n `Point it at a hosted CMS instead: vela enable cms --endpoint ${ENDPOINT_EXAMPLE}`,\n );\n }\n\n return { endpoint: LOCAL_ENDPOINT, local: true };\n}\n\n/** `$lib/cms.ts`: the read path, with the endpoint and locales bound. */\nfunction cmsLibSource(mode: CmsMode, i18n: boolean): string {\n const imports = [\n \"import { apiAdapter, createCms } from '@velastack/cms/server';\",\n ];\n if (i18n) imports.push(\"import { locales } from '$locales/data';\");\n\n const where = mode.local\n ? [\n \" * `/api/cms` is where `src/routes/api/cms/[...path]/+server.ts` mounts the\",\n \" * backend. It is also the admin bar's default, so the endpoint is named here\",\n \" * and nowhere else.\",\n ]\n : [\n \" * The CMS is hosted at this endpoint: the app reads published content from\",\n \" * it and the admin bar signs in there. The same URL is given to the `cms()`\",\n \" * plugin in vite.config.ts, which downloads media into the build.\",\n ];\n\n const which = i18n\n ? [\n \" * The locales are the site's own, from wuchale, so the CMS supports exactly\",\n \" * the languages the UI does; the first is the default that a missing\",\n \" * translation falls back to.\",\n ]\n : [\n \" * `locales` lists every locale the site supports; the first is the default\",\n \" * that a missing translation falls back to.\",\n ];\n\n return [\n ...imports,\n \"\",\n \"/**\",\n \" * The CMS read path, called from the root `+layout.server.ts`.\",\n \" *\",\n ...where,\n \" *\",\n ...which,\n \" */\",\n \"export const { load: loadCms, generateEntries } = createCms({\",\n `\\tadapter: apiAdapter({ endpoint: '${mode.endpoint}' }),`,\n `\\tlocales: ${i18n ? \"[...locales]\" : \"['en']\"}`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function generate(options: Options) {\n const mode = resolveMode(options);\n const creates: Record<string, File> = {};\n\n if (mode.local) {\n Object.assign(creates, filesFromGlob(backendRaw, BACKEND_PREFIX));\n }\n\n creates[\"src/lib/cms.ts\"] = {\n path: \"src/lib/cms.ts\",\n language: \"ts\",\n content: cmsLibSource(mode, options.features.i18n),\n status: \"success\",\n };\n\n const sortedCreates = Object.values(creates).sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n\n // better-sqlite3 and marked are the package's optional peers, which npm\n // skips on install precisely because they are optional — so they have to be\n // named here. The backend needs the first; the root entry imports the\n // second statically, so <AdminBar /> cannot render without it.\n // 0.2.2 is the first release whose Vite plugin imports from the package\n // name rather than its own source tree; 0.2.1 breaks every consumer route.\n const packages = mode.local\n ? [\"@velastack/cms@^0.2.2\", \"better-sqlite3\", \"marked\"]\n : [\"@velastack/cms@^0.2.2\", \"marked\"];\n\n return {\n creates: sortedCreates,\n modifies: [],\n deletes: [],\n components: [],\n packages,\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAM,IAAa,uBAAA,OAAA;CAAA,2CAAA;CAAA,6DAAA;CAAA,8DAAA;AAIlB,CAAA,GAEK,IAAiB,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,CAAc,CAAC,GAGlE,EAAQ,oBAAoB;EAC1B,MAAM;EACN,UAAU;EACV,SAAS,EAAa,GAAM,EAAQ,SAAS,IAAI;EACjD,QAAQ;CACV,GAgBO;EACL,SAfoB,OAAO,OAAO,CAAO,CAAC,CAAC,MAAM,GAAG,MACpD,EAAE,KAAK,cAAc,EAAE,IAAI,CAclB;EACT,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UATe,EAAK,QAClB;GAAC;GAAyB;GAAkB;EAAQ,IACpD,CAAC,yBAAyB,QAAQ;EAQpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-CQONztPm.js";
|
|
2
|
-
import { t } from "./shared-
|
|
2
|
+
import { t } from "./shared-BZlvCHX8.js";
|
|
3
3
|
import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
|
|
4
4
|
import { a as r, o as i, r as a } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
5
5
|
import o from "node:path";
|
|
@@ -104,4 +104,4 @@ async function p(r) {
|
|
|
104
104
|
//#endregion
|
|
105
105
|
export { p as generate };
|
|
106
106
|
|
|
107
|
-
//# sourceMappingURL=generate.runtime-
|
|
107
|
+
//# sourceMappingURL=generate.runtime-BX0QcpGg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BX0QcpGg.js","names":[],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\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 unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.removeElement(\"AuthMenu.Root\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/components/ui/auth-menu\");\n removeImportByModuleSpecifier(sf, \"$lib/components/ui/avatar\");\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\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 fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\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 +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\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":";;;;;;;;AAIA,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM;CACzD,IAAI,CAAC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAM,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAEnD,IAAW,EAAW,qBAC1B,EAAW,uBACb;CACA,KAAK,IAAM,KAAO,GAAU;EAC1B,IAAM,IAAW,EAAI,YAAY,MAAM;EACnC,CAAC,KAAY,EAAS,QAAQ,MAAM,EAAW,sBAGpC,EACZ,eAAe,CAAC,EACf,QAAQ,MACE,gCACZ,EAAS,OAAO;CAEpB;CAKA,OAHA,EAAW,WAAW,GACtB,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAAS,EAAW,YAAY,MAAM;CACxC;AACF;;;AChCA,SAAgB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
|
|
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";
|
|
@@ -113,4 +113,4 @@ async function p(r) {
|
|
|
113
113
|
//#endregion
|
|
114
114
|
export { p as generate };
|
|
115
115
|
|
|
116
|
-
//# sourceMappingURL=generate.runtime-
|
|
116
|
+
//# sourceMappingURL=generate.runtime-BlK7yHff.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BlK7yHff.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,M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} from "./shared-
|
|
2
|
+
import { t } from "./shared-BZlvCHX8.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 a from "node:path";
|
|
@@ -90,4 +90,4 @@ async function d(r) {
|
|
|
90
90
|
//#endregion
|
|
91
91
|
export { d as generate };
|
|
92
92
|
|
|
93
|
-
//# sourceMappingURL=generate.runtime-
|
|
93
|
+
//# sourceMappingURL=generate.runtime-BmW0th7X.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BmW0th7X.js","names":[],"sources":["../../src/patterns/disable/api-keys/modifies/hooks.server.ts","../../src/patterns/disable/api-keys/modifies/nav-user.svelte.ts","../../src/patterns/disable/api-keys/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp || apiProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { status: \"success\", changed: false };\n }\n\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!apiInit || apiInit.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const apiKeysProp = apiObj.getProperty(\"apiKeys\");\n if (!apiKeysProp) {\n return { status: \"success\", changed: false };\n }\n\n apiKeysProp.remove();\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","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(\"/api-keys\")) {\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 \"API Keys\",\n \"@lucide/svelte/icons/key-round\",\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 path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { unmodifyNavUser } from \"./modifies/nav-user.svelte\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\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(hooksServerPath, unmodifyHooksServer(hooksServerPath)),\n );\n\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 const collectionDrops = await planDropsForCollections([\"api_keys\"], options);\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,SAAgB,EAAoB,GAAwC;CAC1E,IAAI,CAAC,EAAG,WAAW,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAiB,MAAM,GAExD,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAe,GAExD,IAAW,EACd,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CACnE,IAAI,CAAC,GAAU,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE1D,IAAM,CAAC,KAAY,EAAS,aAAa;CACzC,IAAI,CAAC,KAAY,EAAS,QAAQ,MAAM,EAAW,yBACjD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAM,IADa,EAAS,cAAc,EAAW,uBACrC,CAAA,CAAW,YAAY,KAAK;CAC5C,IAAI,CAAC,KAAW,EAAQ,QAAQ,MAAM,EAAW,oBAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,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B,GAAiB,EAAoB,CAAe,CAAC,CAC3E,GAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAKA,OAJA,EAAW,EAAoB,GAAa,EAAgB,CAAW,CAAC,CAAC,GAIlE;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAV4B,EAAwB,CAAC,UAAU,GAAG,CAAO;CAW3E;AACF"}
|
|
@@ -6,7 +6,7 @@ import { modifyOutcomeToFile as i } from "./modify-file-PVKmDJHk.js";
|
|
|
6
6
|
import { a, n as o, o as s } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
7
7
|
import { t as c } from "./modify-utils-Cw-on_cL.js";
|
|
8
8
|
import { getMigrationFile as l, migrationDelay as u, withPocketbase as d } from "./pocketbase-fERkp8b8.js";
|
|
9
|
-
import { applyCollectionRulePatches as f, createCollectionIdempotent as p } from "./collections-
|
|
9
|
+
import { applyCollectionRulePatches as f, createCollectionIdempotent as p } from "./collections-wIKcIKzY.js";
|
|
10
10
|
import m from "node:path";
|
|
11
11
|
import h from "node:fs";
|
|
12
12
|
import { Project as g, SyntaxKind as _ } from "ts-morph";
|
|
@@ -288,4 +288,4 @@ async function O(e) {
|
|
|
288
288
|
//#endregion
|
|
289
289
|
export { O as generate };
|
|
290
290
|
|
|
291
|
-
//# sourceMappingURL=generate.runtime-
|
|
291
|
+
//# sourceMappingURL=generate.runtime-C4wcEIc9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-Bhr2eJg6.js","names":[],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '$lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"$lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n if (vs?.hasExportKeyword()) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\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":";;;;;;;;;;;;;AASA,IAAM,IAAe,2EAMf,IAAiB,CAAM;;GAIvB,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAgB,GAAmC;CACjE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAsB3C,OArBK,EAAK,WAAW,QAAQ,IAGzB,EAAK,WAAW,mBAAmB,IAC9B;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;GACzD,EAAc,GAAI,CAChB;IACE,eAAe;IACf,iBAAiB;GACnB,CACF,CAAC;EACH,CAAC;EACD,OAAO;CACT,CAAC,GAED,EAAK,uBAAuB,UAAU,CAAY,GAClD,EAAK,QAAQ,CAAU,GAChB;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ime-C4wcEIc9.js","names":[],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '$lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"$lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n if (vs?.hasExportKeyword()) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\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":";;;;;;;;;;;;;AASA,IAAM,IAAe,2EAMf,IAAiB,CAAM;;GAIvB,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAgB,GAAmC;CACjE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAsB3C,OArBK,EAAK,WAAW,QAAQ,IAGzB,EAAK,WAAW,mBAAmB,IAC9B;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAA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AS,CAAC,CAAC,GAE1D;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-CQONztPm.js";
|
|
2
|
-
import { t } from "./shared-
|
|
2
|
+
import { t } from "./shared-BZlvCHX8.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 a from "node:path";
|
|
@@ -57,4 +57,4 @@ async function l(r) {
|
|
|
57
57
|
//#endregion
|
|
58
58
|
export { l as generate };
|
|
59
59
|
|
|
60
|
-
//# sourceMappingURL=generate.runtime-
|
|
60
|
+
//# sourceMappingURL=generate.runtime-CNrtLDCf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-CNrtLDCf.js","names":[],"sources":["../../src/patterns/disable/teams/modifies/modify-nav-user.ts","../../src/patterns/disable/teams/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(\"/teams\")) {\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 \"Teams\",\n \"@lucide/svelte/icons/users\",\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 path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nconst MANUAL_REMEDIATION = [\n \"app-sidebar, +layout.server.ts (teams loader), and app-layout.svelte (AppSidebar team props) must be reverted manually.\",\n \"These edits are substantial and are not safely reversed by tooling.\",\n].join(\" \");\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 nav-user.svelte\");\n const navUserCandidates = [\n path.join(options.root, \"src\", \"lib\", \"components\", \"nav-user.svelte\"),\n ];\n const navUserPath =\n navUserCandidates.find((p) => fs.existsSync(p)) ?? navUserCandidates[0];\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(MANUAL_REMEDIATION);\n\n const collectionDrops = await planDropsForCollections(\n [\"team_invite_links\", \"team_invites\", \"team_memberships\", \"teams\"],\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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Hk.js";
|
|
|
6
6
|
import { o as a, t as o } from "./ts-morph-helpers-Bk82Z2n7.js";
|
|
7
7
|
import { t as s } from "./env-BPfk1VAw.js";
|
|
8
8
|
import { getMigrationFile as c, migrationDelay as l, withPocketbase as u } from "./pocketbase-fERkp8b8.js";
|
|
9
|
-
import { createCollectionIdempotent as d } from "./collections-
|
|
9
|
+
import { createCollectionIdempotent as d } from "./collections-wIKcIKzY.js";
|
|
10
10
|
import f from "node:path";
|
|
11
11
|
import p from "node:fs";
|
|
12
12
|
import { Project as m, QuoteKind as h, SyntaxKind as g } from "ts-morph";
|
|
@@ -662,4 +662,4 @@ async function P(e) {
|
|
|
662
662
|
//#endregion
|
|
663
663
|
export { P as generate };
|
|
664
664
|
|
|
665
|
-
//# sourceMappingURL=generate.runtime-
|
|
665
|
+
//# sourceMappingURL=generate.runtime-CQ0Veyk4.js.map
|