@velastack/patterns 0.12.0 → 0.13.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.
- package/README.md +21 -2
- package/dist/chunks/{collections-DzwWwFUQ.js → collections-zEoRuILr.js} +2 -2
- package/dist/chunks/{collections-DzwWwFUQ.js.map → collections-zEoRuILr.js.map} +1 -1
- package/dist/chunks/constants-CUv536Rj.js +87 -0
- package/dist/chunks/constants-CUv536Rj.js.map +1 -0
- package/dist/chunks/{currency.server-CzHS7Svd.js → currency.server-DygAf6a1.js} +2 -2
- package/dist/chunks/{currency.server-CzHS7Svd.js.map → currency.server-DygAf6a1.js.map} +1 -1
- package/dist/chunks/{env-vars-CNH-ItSY.js → env-vars-XvAeH6u5.js} +3 -3
- package/dist/chunks/{env-vars-CNH-ItSY.js.map → env-vars-XvAeH6u5.js.map} +1 -1
- package/dist/chunks/{generate-D21dCU-o.js → generate-BtWZCvuO.js} +3 -3
- package/dist/chunks/{generate-D21dCU-o.js.map → generate-BtWZCvuO.js.map} +1 -1
- package/dist/chunks/{generate-BEc_h7OI.js → generate-Cbg-Z3sA.js} +2 -2
- package/dist/chunks/{generate-BEc_h7OI.js.map → generate-Cbg-Z3sA.js.map} +1 -1
- package/dist/chunks/{generate-DiwvSC9c.js → generate-Crdzw45a.js} +2 -2
- package/dist/chunks/{generate-DiwvSC9c.js.map → generate-Crdzw45a.js.map} +1 -1
- package/dist/chunks/{generate-C3OaUggX.js → generate-DgZhFNjO.js} +22 -22
- package/dist/chunks/generate-DgZhFNjO.js.map +1 -0
- package/dist/chunks/{generate-CtQcmjPM.js → generate-DjuhSibA.js} +84 -84
- package/dist/chunks/generate-DjuhSibA.js.map +1 -0
- package/dist/chunks/{generate.runtime-CaOO0281.js → generate.runtime-2GD2E1NK.js} +6 -6
- package/dist/chunks/{generate.runtime-CaOO0281.js.map → generate.runtime-2GD2E1NK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CowdMKQs.js → generate.runtime-4TxcYKld.js} +3 -3
- package/dist/chunks/{generate.runtime-CowdMKQs.js.map → generate.runtime-4TxcYKld.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B3yuIjJD.js → generate.runtime-7sU7RzIA.js} +2 -2
- package/dist/chunks/{generate.runtime-B3yuIjJD.js.map → generate.runtime-7sU7RzIA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BBfiR_Le.js → generate.runtime-B-WOQsda.js} +3 -3
- package/dist/chunks/{generate.runtime-BBfiR_Le.js.map → generate.runtime-B-WOQsda.js.map} +1 -1
- package/dist/chunks/{generate.runtime-kEHEiLBL.js → generate.runtime-B2DI0x05.js} +2 -2
- package/dist/chunks/{generate.runtime-kEHEiLBL.js.map → generate.runtime-B2DI0x05.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BTHuPon9.js → generate.runtime-B8y_l-6N.js} +5 -5
- package/dist/chunks/{generate.runtime-BTHuPon9.js.map → generate.runtime-B8y_l-6N.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DbSRJF-C.js → generate.runtime-BEvi6bml.js} +3 -3
- package/dist/chunks/{generate.runtime-DbSRJF-C.js.map → generate.runtime-BEvi6bml.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CCE-9xQV.js → generate.runtime-BO1KyRcJ.js} +2 -2
- package/dist/chunks/{generate.runtime-CCE-9xQV.js.map → generate.runtime-BO1KyRcJ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D_HYO-mG.js → generate.runtime-BPVZsAL0.js} +4 -4
- package/dist/chunks/{generate.runtime-D_HYO-mG.js.map → generate.runtime-BPVZsAL0.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DVwha8lZ.js → generate.runtime-BfM3dX_R.js} +2 -2
- package/dist/chunks/{generate.runtime-DVwha8lZ.js.map → generate.runtime-BfM3dX_R.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CtFCayo8.js → generate.runtime-BfQlxsWK.js} +7 -7
- package/dist/chunks/{generate.runtime-CtFCayo8.js.map → generate.runtime-BfQlxsWK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Drpy9sWO.js → generate.runtime-BsjcGBme.js} +2 -2
- package/dist/chunks/{generate.runtime-Drpy9sWO.js.map → generate.runtime-BsjcGBme.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DOv-bhM6.js → generate.runtime-ByC9kOl2.js} +2 -2
- package/dist/chunks/{generate.runtime-DOv-bhM6.js.map → generate.runtime-ByC9kOl2.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dy9uuf7M.js → generate.runtime-C2pIioyZ.js} +6 -6
- package/dist/chunks/{generate.runtime-Dy9uuf7M.js.map → generate.runtime-C2pIioyZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime--VeSxyIm.js → generate.runtime-C4hyve9h.js} +3 -3
- package/dist/chunks/{generate.runtime--VeSxyIm.js.map → generate.runtime-C4hyve9h.js.map} +1 -1
- package/dist/chunks/{generate.runtime-r9Ouwr5B.js → generate.runtime-C9yduilW.js} +3 -3
- package/dist/chunks/{generate.runtime-r9Ouwr5B.js.map → generate.runtime-C9yduilW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-HkvT9gm6.js → generate.runtime-CEd3qCtW.js} +4 -4
- package/dist/chunks/{generate.runtime-HkvT9gm6.js.map → generate.runtime-CEd3qCtW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D34lCyet.js → generate.runtime-CHaE6Mm9.js} +3 -3
- package/dist/chunks/{generate.runtime-D34lCyet.js.map → generate.runtime-CHaE6Mm9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DbMDlglD.js → generate.runtime-CXGiQWDK.js} +4 -4
- package/dist/chunks/{generate.runtime-DbMDlglD.js.map → generate.runtime-CXGiQWDK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BK7x32md.js → generate.runtime-CvtSK0E1.js} +3 -3
- package/dist/chunks/{generate.runtime-BK7x32md.js.map → generate.runtime-CvtSK0E1.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CeoqgxiO.js → generate.runtime-DGmpjkRe.js} +4 -4
- package/dist/chunks/{generate.runtime-CeoqgxiO.js.map → generate.runtime-DGmpjkRe.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Brakd35X.js → generate.runtime-DI73x08q.js} +2 -2
- package/dist/chunks/{generate.runtime-Brakd35X.js.map → generate.runtime-DI73x08q.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bx_CaBZD.js → generate.runtime-DIkM5xIB.js} +2 -2
- package/dist/chunks/{generate.runtime-Bx_CaBZD.js.map → generate.runtime-DIkM5xIB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DlPeHx19.js → generate.runtime-DRZDjZqw.js} +2 -2
- package/dist/chunks/{generate.runtime-DlPeHx19.js.map → generate.runtime-DRZDjZqw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DUBOC6AA.js → generate.runtime-DVUj1LJK.js} +3 -3
- package/dist/chunks/{generate.runtime-DUBOC6AA.js.map → generate.runtime-DVUj1LJK.js.map} +1 -1
- package/dist/chunks/{generate.runtime--yCjGZ6-.js → generate.runtime-Deg1Tz9u.js} +3 -3
- package/dist/chunks/{generate.runtime--yCjGZ6-.js.map → generate.runtime-Deg1Tz9u.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DOWDoe6B.js → generate.runtime-DqYYJXAz.js} +2 -2
- package/dist/chunks/{generate.runtime-DOWDoe6B.js.map → generate.runtime-DqYYJXAz.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C8-mjcn8.js → generate.runtime-Du8puIJQ.js} +6 -6
- package/dist/chunks/{generate.runtime-C8-mjcn8.js.map → generate.runtime-Du8puIJQ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DRuPb-67.js → generate.runtime-DzCVGruq.js} +2 -2
- package/dist/chunks/{generate.runtime-DRuPb-67.js.map → generate.runtime-DzCVGruq.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CAO_SpsA.js → generate.runtime-TKR-qAJM.js} +2 -2
- package/dist/chunks/{generate.runtime-CAO_SpsA.js.map → generate.runtime-TKR-qAJM.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CGJ_4VS_.js → generate.runtime-USnFqTbU.js} +4 -4
- package/dist/chunks/{generate.runtime-CGJ_4VS_.js.map → generate.runtime-USnFqTbU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-sALBNh1T.js → generate.runtime-UrLaWKvN.js} +4 -4
- package/dist/chunks/{generate.runtime-sALBNh1T.js.map → generate.runtime-UrLaWKvN.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Ce2O5uWy.js → generate.runtime-bWGwyz2U.js} +3 -3
- package/dist/chunks/{generate.runtime-Ce2O5uWy.js.map → generate.runtime-bWGwyz2U.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BL62aRng.js → generate.runtime-g6qaIY3k.js} +6 -6
- package/dist/chunks/{generate.runtime-BL62aRng.js.map → generate.runtime-g6qaIY3k.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DroVnvQz.js → generate.runtime-s9ai7PxV.js} +4 -4
- package/dist/chunks/{generate.runtime-DroVnvQz.js.map → generate.runtime-s9ai7PxV.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CPDJolef.js → generate.runtime-taYl9Tg5.js} +4 -4
- package/dist/chunks/{generate.runtime-CPDJolef.js.map → generate.runtime-taYl9Tg5.js.map} +1 -1
- package/dist/chunks/{modify-file-DdXJCMHN.js → modify-file-D9U2LXEa.js} +2 -2
- package/dist/chunks/{modify-file-DdXJCMHN.js.map → modify-file-D9U2LXEa.js.map} +1 -1
- package/dist/chunks/{pocketbase-uOpghyT5.js → pocketbase-BTR3gI8o.js} +2 -2
- package/dist/chunks/{pocketbase-uOpghyT5.js.map → pocketbase-BTR3gI8o.js.map} +1 -1
- package/dist/chunks/{providers-ypCW70Mb.js → providers-CpRRQdMg.js} +2 -2
- package/dist/chunks/{providers-ypCW70Mb.js.map → providers-CpRRQdMg.js.map} +1 -1
- package/dist/chunks/{shared-DIDAkVts.js → shared-CAjLx_8Z.js} +2 -2
- package/dist/chunks/{shared-DIDAkVts.js.map → shared-CAjLx_8Z.js.map} +1 -1
- package/dist/chunks/{site-CVtsbO_S.js → site-D0IuWkAR.js} +2 -2
- package/dist/chunks/{site-CVtsbO_S.js.map → site-D0IuWkAR.js.map} +1 -1
- package/dist/chunks/table-core-BKBoEStB.js +127 -0
- package/dist/chunks/table-core-BKBoEStB.js.map +1 -0
- package/dist/chunks/{test-setup-B37g3TRn.js → test-setup-CbCXmPkE.js} +3 -3
- package/dist/chunks/{test-setup-B37g3TRn.js.map → test-setup-CbCXmPkE.js.map} +1 -1
- package/dist/chunks/{ui-Ct_9B91R.js → ui-B3Db8cQg.js} +3 -3
- package/dist/chunks/{ui-Ct_9B91R.js.map → ui-B3Db8cQg.js.map} +1 -1
- package/dist/chunks/{whatsapp-Dr29ohbb.js → whatsapp-Pya8Zi07.js} +2 -2
- package/dist/chunks/{whatsapp-Dr29ohbb.js.map → whatsapp-Pya8Zi07.js.map} +1 -1
- package/dist/chunks/{write-result-mtVbmDyQ.js → write-result-BWXq9RRn.js} +4 -4
- package/dist/chunks/{write-result-mtVbmDyQ.js.map → write-result-BWXq9RRn.js.map} +1 -1
- package/dist/index.d.ts +57 -17
- package/dist/index.js +1950 -1947
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
- package/dist/chunks/constants-8cLxGOB0.js +0 -6
- package/dist/chunks/constants-8cLxGOB0.js.map +0 -1
- package/dist/chunks/generate-C3OaUggX.js.map +0 -1
- package/dist/chunks/generate-CtQcmjPM.js.map +0 -1
- package/dist/chunks/table-core-CUGp4Rf2.js +0 -127
- package/dist/chunks/table-core-CUGp4Rf2.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@ The registry for VelaStack patterns.
|
|
|
4
4
|
|
|
5
5
|
## Requirements
|
|
6
6
|
|
|
7
|
-
Patterns write SvelteKit 3 code only, and the package needs Node 22.
|
|
8
|
-
SvelteKit 3. A project with a `svelte.config.*`, or with options still nested under `kit:`, is refused with
|
|
7
|
+
Patterns write SvelteKit 3 code only, and the package needs Node 22.22 or later (`engines`), the same floor as
|
|
8
|
+
a vela project (SvelteKit 3 itself starts at 22.17; `openworkflow` 0.11 needs 22.22). A project with a `svelte.config.*`, or with options still nested under `kit:`, is refused with
|
|
9
9
|
`npx vela@^0.15 migrate sveltekit-3`. Config edits go into the inline `sveltekit({...})` call in `vite.config.ts`.
|
|
10
10
|
|
|
11
11
|
- Imports from `src/lib` use `#lib` (the `"imports"` entries in `package.json`) with sv's extension rules:
|
|
@@ -206,6 +206,25 @@ lists in `components` is handed to `shadcn-svelte add`, which resolves it from t
|
|
|
206
206
|
the `shadcn-svelte` devDependency.
|
|
207
207
|
- `WriteResultRuntime.fetch` is the test seam for the registry, next to `executeCommand` for the spawns.
|
|
208
208
|
|
|
209
|
+
# Dependency versions
|
|
210
|
+
|
|
211
|
+
`src/core/versions.json` is the one list of dependency ranges every vela project starts from. Three things read it:
|
|
212
|
+
|
|
213
|
+
- the patterns here install from it: `spec("zod")` is `zod@^4.6.7`, and a test refuses a `name@range` written inline;
|
|
214
|
+
- the vela CLI's `minimal` and `static` templates list the same ranges, with a test that fails when they stop (`npm run sync-versions` there rewrites them from this package);
|
|
215
|
+
- the velastack-templates baselines are built on those templates and follow them.
|
|
216
|
+
|
|
217
|
+
So a version is changed here and nowhere else. The file has four parts:
|
|
218
|
+
|
|
219
|
+
- `packages`: the ranges.
|
|
220
|
+
- `node`: the oldest Node a project may run on. Projects set `engine-strict`, so a release whose own `engines.node` starts above it would fail the install there.
|
|
221
|
+
- `holds`: packages kept below their latest release on purpose, each with the reason and the date. Write a block down here instead of leaving it to be rediscovered.
|
|
222
|
+
- `tracks`: packages whose range follows another project's. `svelte` follows the floor `sv create`'s minimal template ships.
|
|
223
|
+
|
|
224
|
+
`npm run bump-versions` raises each floor to the newest release its range admits that is stable, at least three days old (`--cooldown N`) and installable on `node`; `-- --check` only reports. It never leaves a range: a new major or a new 0.x minor is listed as "outside the range" for someone to read the changelog, change `versions.json` by hand and run the integration suites against it.
|
|
225
|
+
|
|
226
|
+
The weekly **Bump versions** workflow runs the script, opens one pull request with what it raised, and keeps the "Dependencies outside their range" issue. The ranges reach users after a release of this package and the vela repository's **Sync versions** pull request; vela's daily **Canary** scaffolds, installs, builds and tests a new project, which is what catches a release upstream breaking one.
|
|
227
|
+
|
|
209
228
|
# Workflow for adding new patterns
|
|
210
229
|
|
|
211
230
|
- Develop the pattern in the `src/patterns` directory.
|
|
@@ -2,7 +2,7 @@ import { n as e } from "./rolldown-runtime-5HNE8Q1r.js";
|
|
|
2
2
|
import { t } from "./errors-DR3gF_7a.js";
|
|
3
3
|
import { a as n } from "./util-BLYliuUK.js";
|
|
4
4
|
import { n as r, t as i } from "./logger-CQONztPm.js";
|
|
5
|
-
import { i as a, n as o, t as s } from "./pocketbase-
|
|
5
|
+
import { i as a, n as o, t as s } from "./pocketbase-BTR3gI8o.js";
|
|
6
6
|
import { readFileSync as c } from "node:fs";
|
|
7
7
|
//#region src/runtime/collections.ts
|
|
8
8
|
var l = /* @__PURE__ */ e({
|
|
@@ -204,4 +204,4 @@ async function S(e, t) {
|
|
|
204
204
|
//#endregion
|
|
205
205
|
export { _ as i, l as n, f as r, m as t };
|
|
206
206
|
|
|
207
|
-
//# sourceMappingURL=collections-
|
|
207
|
+
//# sourceMappingURL=collections-zEoRuILr.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections-DzwWwFUQ.js","names":["__exportAll","languageFromPath","getLogger","NOOP_LOGGER","withPocketbase","migrationDelay","getMigrationFile","collections_exports","applyCollectionFieldsPatches","applyCollectionRulePatches","createCollectionIdempotent","createCollections","dropCollectionIdempotent","dropCollections","ensureCollectionFields","getCollectionStats","planCollectionDrops","isCollectionAlreadyExistsError","error","message","resolveRelationTargets","fields","spec","relations","field","existing","pb","ids","c","byName","id","name","logger","rulePayloadFromPatch","payload","patch","migrations","patches","escaped","col","options","migrationFile","readFileSync","applyFieldChanges","change","f","InvalidArgumentError","index","collection","newFields","have","missing","plans","names","stats","specs","dropped","collections","created"],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\n/**\n * Adds to an existing collection every field of `spec` it lacks, by name, so a\n * project that created it under an older spec gets the new fields. Fields are\n * only added, never changed or removed. Returns the migration files written.\n */\nexport async function ensureCollectionFields(\n pb: PocketBase,\n spec: CollectionSpec,\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const existing = await pb.collections.getOne(spec.name);\n const have = new Set(\n (existing.fields as { name: string }[]).map((field) => field.name),\n );\n const missing = spec.fields.filter((field) => !have.has(field.name));\n if (missing.length === 0) return [];\n logger.info(\n `Adding ${missing.map((field) => field.name).join(\", \")} to collection \"${spec.name}\"`,\n );\n return applyCollectionFieldsPatches(\n pb,\n [\n {\n collectionName: spec.name,\n changes: missing.map((field) => ({ op: \"add\" as const, field })),\n },\n ],\n options,\n logger,\n );\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,SAASiB,EACP,GACS;CACT,IACEC,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAMC,IAAUD,EAAM,SAAS,YAAY,KAAK;CAChD,OACEC,EAAQ,SAAS,gBAAgB,KAAKA,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAeC,EACb,GACA,GACgC;CAChC,IAAMC,IAAUC,EAA0C,QACpDC,KAAaF,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAUG,EAAM,SAAS,cAAcA,EAAM,YAChD;CACA,IAAID,EAAU,WAAW,GAAG,OAAOD;CAEnC,IAAMG,IAAW,MAAMC,EAAG,YAAY,YAAY,GAC5CC,IAAM,IAAI,IAAIF,EAAS,KAAK,MAAMG,EAAE,EAAE,CAAC,GACvCC,IAAS,IAAI,IAAIJ,EAAS,KAAK,MAAM,CAACG,EAAE,MAAMA,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFIL,EAAU,OAAO,MAAUI,EAAI,IAAIH,EAAM,YAAa,CAAC,IAAUF,IAE9D;EACL,GAAGA;EACH,QAAQD,EAAQ,KAAK,MAAU;GAC7B,IAAIG,EAAM,SAAS,cAAc,CAACA,EAAM,cAAc,OAAOA;GAC7D,IAAMM,IAAKD,EAAO,IAAIL,EAAM,YAAY;GACxC,OAAOM,KAAM,CAACH,EAAI,IAAIH,EAAM,YAAY,IACpC;IAAE,GAAGA;IAAO,cAAcM;GAAG,I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IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEML;AACT;AAEA,eAAsBzB,EACpB,GACA,GACiB;CACjB,IAAI8C,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAMrB,IAAqB,CAAC,GACtBJ,IAAS9B,EAAUsC,CAAO;CA+BhC,OA7BA,MAAMpC,EAAeoC,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAMQ,KAAcS,GAAa;GACpC,EAAO,KAAK,wBAAwBT,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAMtC,EACxBgB,GACAsB,GACAhB,CACF;GACA,IAAI,CAAC0B,GAAS;GACd,MAAMrD,EAAe;GAErB,IAAMoC,IAAgBnC,EACpB0C,EAAW,MACX,WACAR,CACF;GACA,AAAKC,KAILL,EAAW,KAAK;IACd,MAAMK;IACN,UAAUxC,EAAiBwC,CAAa;IACxC,SAASC,EAAaD,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEML;AACT"}
|
|
1
|
+
{"version":3,"file":"collections-zEoRuILr.js","names":["__exportAll","languageFromPath","getLogger","NOOP_LOGGER","withPocketbase","migrationDelay","getMigrationFile","collections_exports","applyCollectionFieldsPatches","applyCollectionRulePatches","createCollectionIdempotent","createCollections","dropCollectionIdempotent","dropCollections","ensureCollectionFields","getCollectionStats","planCollectionDrops","isCollectionAlreadyExistsError","error","message","resolveRelationTargets","fields","spec","relations","field","existing","pb","ids","c","byName","id","name","logger","rulePayloadFromPatch","payload","patch","migrations","patches","escaped","col","options","migrationFile","readFileSync","applyFieldChanges","change","f","InvalidArgumentError","index","collection","newFields","have","missing","plans","names","stats","specs","dropped","collections","created"],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\n/**\n * Adds to an existing collection every field of `spec` it lacks, by name, so a\n * project that created it under an older spec gets the new fields. Fields are\n * only added, never changed or removed. Returns the migration files written.\n */\nexport async function ensureCollectionFields(\n pb: PocketBase,\n spec: CollectionSpec,\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const existing = await pb.collections.getOne(spec.name);\n const have = new Set(\n (existing.fields as { name: string }[]).map((field) => field.name),\n );\n const missing = spec.fields.filter((field) => !have.has(field.name));\n if (missing.length === 0) return [];\n logger.info(\n `Adding ${missing.map((field) => field.name).join(\", \")} to collection \"${spec.name}\"`,\n );\n return applyCollectionFieldsPatches(\n pb,\n [\n {\n collectionName: spec.name,\n changes: missing.map((field) => ({ op: \"add\" as const, field })),\n },\n ],\n options,\n logger,\n );\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,SAASiB,EACP,GACS;CACT,IACEC,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAMC,IAAUD,EAAM,SAAS,YAAY,KAAK;CAChD,OACEC,EAAQ,SAAS,gBAAgB,KAAKA,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAeC,EACb,GACA,GACgC;CAChC,IAAMC,IAAUC,EAA0C,QACpDC,KAAaF,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAUG,EAAM,SAAS,cAAcA,EAAM,YAChD;CACA,IAAID,EAAU,WAAW,GAAG,OAAOD;CAEnC,IAAMG,IAAW,MAAMC,EAAG,YAAY,YAAY,GAC5CC,IAAM,IAAI,IAAIF,EAAS,KAAK,MAAMG,EAAE,EAAE,CAAC,GACvCC,IAAS,IAAI,IAAIJ,EAAS,KAAK,MAAM,CAACG,EAAE,MAAMA,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFIL,EAAU,OAAO,MAAUI,EAAI,IAAIH,EAAM,YAAa,CAAC,IAAUF,IAE9D;EACL,GAAGA;EACH,QAAQD,EAAQ,KAAK,MAAU;GAC7B,IAAIG,EAAM,SAAS,cAAc,CAACA,EAAM,cAAc,OAAOA;GAC7D,IAAMM,IAAKD,EAAO,IAAIL,EAAM,YAAY;GACxC,OAAOM,KAAM,CAACH,EAAI,IAAIH,EAAM,YAAY,IACpC;IAAE,GAAGA;IAAO,cAAcM;GAAG,IAC7BN;EACN,CAAC;CACH;AACF;AAaA,eAAsBd,EACpB,GACA,GACA,IAAiBP,GACgB;CACjC,IAAM4B,IAAQT,EAA0B;CACxC,IAAI;EAIF,OAAO;GAAE,YAAA,MAHgBI,EAAG,YAAY,OACtC,MAAMN,EAAuBM,GAAIJ,CAAI,CACvC;GACqB,SAAS;EAAK;CACrC,SAASJ,GAAO;EACd,IACE,CA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/C,KAAK,IAAMQ,KAAcS,GAAa;GACpC,EAAO,KAAK,wBAAwBT,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAMtC,EACxBgB,GACAsB,GACAhB,CACF;GACA,IAAI,CAAC0B,GAAS;GACd,MAAMrD,EAAe;GAErB,IAAMoC,IAAgBnC,EACpB0C,EAAW,MACX,WACAR,CACF;GACA,AAAKC,KAILL,EAAW,KAAK;IACd,MAAMK;IACN,UAAUxC,EAAiBwC,CAAa;IACxC,SAASC,EAAaD,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEML;AACT"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
var e = {
|
|
2
|
+
node: "22.22.0",
|
|
3
|
+
packages: {
|
|
4
|
+
"@ai-sdk/anthropic": "^4.0.99",
|
|
5
|
+
"@ai-sdk/openai": "^4.0.111",
|
|
6
|
+
"@ai-sdk/svelte": "^5.0.165",
|
|
7
|
+
"@internationalized/date": "^3.12.4",
|
|
8
|
+
"@lucide/svelte": "^1.70.0",
|
|
9
|
+
"@sveltejs/adapter-node": "^6.0.2",
|
|
10
|
+
"@sveltejs/adapter-static": "^4.0.1",
|
|
11
|
+
"@sveltejs/kit": "^3.2.0",
|
|
12
|
+
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
|
13
|
+
"@tailwindcss/forms": "^0.5.11",
|
|
14
|
+
"@tailwindcss/typography": "^0.5.20",
|
|
15
|
+
"@tailwindcss/vite": "^4.3.5",
|
|
16
|
+
"@takumi-rs/core": "^2.20.0",
|
|
17
|
+
"@tanstack/table-core": "^9.3.1",
|
|
18
|
+
"@types/node": "^26.6.6",
|
|
19
|
+
"@types/supertest": "^7.2.1",
|
|
20
|
+
"@velastack/cms": "^0.9.1",
|
|
21
|
+
"@velastack/kit": "^0.4.1",
|
|
22
|
+
"@velastack/pocketbase": "^0.4.3",
|
|
23
|
+
"@velastack/whatsapp": "^0.1.0",
|
|
24
|
+
"@wuchale/svelte": "^0.21.4",
|
|
25
|
+
ai: "^7.0.165",
|
|
26
|
+
"bits-ui": "^2.20.6",
|
|
27
|
+
clsx: "^2.1.1",
|
|
28
|
+
croner: "^10.0.1",
|
|
29
|
+
formsnap: "^2.1.0",
|
|
30
|
+
marked: "^18.1.3",
|
|
31
|
+
mdsvex: "^0.12.8",
|
|
32
|
+
"mode-watcher": "^1.1.0",
|
|
33
|
+
openworkflow: "^0.11.0",
|
|
34
|
+
"openworkflow-pocketbase": "^0.2.1",
|
|
35
|
+
"pocketbase-sveltekit": "^0.28.2",
|
|
36
|
+
prettier: "^3.9.10",
|
|
37
|
+
"prettier-plugin-svelte": "^4.1.1",
|
|
38
|
+
"shadcn-svelte": "^1.8.0",
|
|
39
|
+
supertest: "^7.3.2",
|
|
40
|
+
svelte: "^5.57.2",
|
|
41
|
+
"svelte-check": "^4.7.8",
|
|
42
|
+
"svelte-meta-tags": "^5.0.3",
|
|
43
|
+
"svelte-sonner": "^1.2.3",
|
|
44
|
+
"sveltekit-flash-message": "^3.0.0",
|
|
45
|
+
"sveltekit-negotiate": "^0.3.1",
|
|
46
|
+
"sveltekit-superforms": "^3.1.0",
|
|
47
|
+
"tailwind-merge": "^3.7.0",
|
|
48
|
+
"tailwind-variants": "^3.3.1",
|
|
49
|
+
tailwindcss: "^4.3.5",
|
|
50
|
+
"tw-animate-css": "^1.4.0",
|
|
51
|
+
typescript: "^6.0.3",
|
|
52
|
+
vite: "^8.3.6",
|
|
53
|
+
vitest: "^5.1.0",
|
|
54
|
+
wuchale: "^0.26.7",
|
|
55
|
+
zod: "^4.6.7"
|
|
56
|
+
},
|
|
57
|
+
tracks: { svelte: {
|
|
58
|
+
source: "sv-create",
|
|
59
|
+
reason: "The floor sv create's minimal template ships, so a vela project and a plain SvelteKit one start alike."
|
|
60
|
+
} },
|
|
61
|
+
holds: {
|
|
62
|
+
croner: {
|
|
63
|
+
reason: "11.0 is a major; the cron matching in the workflows runtime has not been checked against it.",
|
|
64
|
+
since: "2026-11-11"
|
|
65
|
+
},
|
|
66
|
+
"tailwind-variants": {
|
|
67
|
+
reason: "4.0 is a major; the shadcn-svelte components and the templates' own tv() calls have not been checked against it.",
|
|
68
|
+
since: "2026-11-11"
|
|
69
|
+
},
|
|
70
|
+
typescript: {
|
|
71
|
+
reason: "TypeScript 7 (the native port) is outside @sveltejs/kit's peer range (^6.0.0) and breaks the install. Blocked upstream: lift once Kit admits 7.",
|
|
72
|
+
since: "2026-11-11"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}, t = e.packages, n = e.holds, r = e.tracks, i = e.node;
|
|
76
|
+
function a(e) {
|
|
77
|
+
let n = t[e];
|
|
78
|
+
if (n === void 0) throw Error(`${e} is not in src/core/versions.json; add it there before installing it.`);
|
|
79
|
+
return `${e}@${n}`;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/core/constants.ts
|
|
83
|
+
var o = "data", s = "migrations", c = "(public)", l = "(app)", u = a("@tanstack/table-core"), d = Number(/\d+/.exec(t["@tanstack/table-core"])[0]), f = a("formsnap"), p = t["sveltekit-superforms"], m = a("sveltekit-superforms"), h = a("sveltekit-flash-message"), g = a("@sveltejs/adapter-node"), _ = a("@sveltejs/adapter-static"), v = a("@velastack/kit"), y = a("@velastack/pocketbase"), b = a("@velastack/cms"), x = a("@velastack/whatsapp"), S = a("sveltekit-negotiate"), C = a("zod"), w = a("@takumi-rs/core"), T = a("wuchale"), E = a("@wuchale/svelte");
|
|
84
|
+
//#endregion
|
|
85
|
+
export { t as C, a as E, i as S, r as T, y as _, h as a, E as b, S as c, p as d, w as f, v as g, b as h, o as i, c as l, d as m, _ as n, f as o, u as p, l as r, s, g as t, m as u, x as v, n as w, C as x, T as y };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=constants-CUv536Rj.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-CUv536Rj.js","names":["data","versions_default","\"ai\"","\"clsx\"","\"croner\"","\"formsnap\"","\"marked\"","\"mdsvex\"","\"openworkflow\"","\"prettier\"","\"supertest\"","\"svelte\"","\"tailwindcss\"","\"typescript\"","\"vite\"","\"vitest\"","\"wuchale\"","\"zod\"","\"source\"","\"reason\"","\"since\"","VERSIONS","VERSION_HOLDS","VERSION_TRACKS","NODE_FLOOR","spec","range","name","DATA_DIR","MIGRATIONS_DIR","PUBLIC_DIR","APP_DIR","TANSTACK_TABLE_CORE","TANSTACK_TABLE_CORE_MAJOR","FORMSNAP","SUPERFORMS_VERSION","SUPERFORMS","FLASH","ADAPTER_NODE","ADAPTER_STATIC","VELASTACK_KIT","VELASTACK_POCKETBASE","VELASTACK_CMS","VELASTACK_WHATSAPP","NEGOTIATE","ZOD","TAKUMI","WUCHALE","WUCHALE_SVELTE"],"sources":["../../src/core/versions.json","../../src/core/versions.ts","../../src/core/constants.ts"],"sourcesContent":["{\n \"node\": \"22.22.0\",\n \"packages\": {\n \"@ai-sdk/anthropic\": \"^4.0.99\",\n \"@ai-sdk/openai\": \"^4.0.111\",\n \"@ai-sdk/svelte\": \"^5.0.165\",\n \"@internationalized/date\": \"^3.12.4\",\n \"@lucide/svelte\": \"^1.70.0\",\n \"@sveltejs/adapter-node\": \"^6.0.2\",\n \"@sveltejs/adapter-static\": \"^4.0.1\",\n \"@sveltejs/kit\": \"^3.2.0\",\n \"@sveltejs/vite-plugin-svelte\": \"^7.3.1\",\n \"@tailwindcss/forms\": \"^0.5.11\",\n \"@tailwindcss/typography\": \"^0.5.20\",\n \"@tailwindcss/vite\": \"^4.3.5\",\n \"@takumi-rs/core\": \"^2.20.0\",\n \"@tanstack/table-core\": \"^9.3.1\",\n \"@types/node\": \"^26.6.6\",\n \"@types/supertest\": \"^7.2.1\",\n \"@velastack/cms\": \"^0.9.1\",\n \"@velastack/kit\": \"^0.4.1\",\n \"@velastack/pocketbase\": \"^0.4.3\",\n \"@velastack/whatsapp\": \"^0.1.0\",\n \"@wuchale/svelte\": \"^0.21.4\",\n \"ai\": \"^7.0.165\",\n \"bits-ui\": \"^2.20.6\",\n \"clsx\": \"^2.1.1\",\n \"croner\": \"^10.0.1\",\n \"formsnap\": \"^2.1.0\",\n \"marked\": \"^18.1.3\",\n \"mdsvex\": \"^0.12.8\",\n \"mode-watcher\": \"^1.1.0\",\n \"openworkflow\": \"^0.11.0\",\n \"openworkflow-pocketbase\": \"^0.2.1\",\n \"pocketbase-sveltekit\": \"^0.28.2\",\n \"prettier\": \"^3.9.10\",\n \"prettier-plugin-svelte\": \"^4.1.1\",\n \"shadcn-svelte\": \"^1.8.0\",\n \"supertest\": \"^7.3.2\",\n \"svelte\": \"^5.57.2\",\n \"svelte-check\": \"^4.7.8\",\n \"svelte-meta-tags\": \"^5.0.3\",\n \"svelte-sonner\": \"^1.2.3\",\n \"sveltekit-flash-message\": \"^3.0.0\",\n \"sveltekit-negotiate\": \"^0.3.1\",\n \"sveltekit-superforms\": \"^3.1.0\",\n \"tailwind-merge\": \"^3.7.0\",\n \"tailwind-variants\": \"^3.3.1\",\n \"tailwindcss\": \"^4.3.5\",\n \"tw-animate-css\": \"^1.4.0\",\n \"typescript\": \"^6.0.3\",\n \"vite\": \"^8.3.6\",\n \"vitest\": \"^5.1.0\",\n \"wuchale\": \"^0.26.7\",\n \"zod\": \"^4.6.7\"\n },\n \"tracks\": {\n \"svelte\": {\n \"source\": \"sv-create\",\n \"reason\": \"The floor sv create's minimal template ships, so a vela project and a plain SvelteKit one start alike.\"\n }\n },\n \"holds\": {\n \"croner\": {\n \"reason\": \"11.0 is a major; the cron matching in the workflows runtime has not been checked against it.\",\n \"since\": \"2026-11-11\"\n },\n \"tailwind-variants\": {\n \"reason\": \"4.0 is a major; the shadcn-svelte components and the templates' own tv() calls have not been checked against it.\",\n \"since\": \"2026-11-11\"\n },\n \"typescript\": {\n \"reason\": \"TypeScript 7 (the native port) is outside @sveltejs/kit's peer range (^6.0.0) and breaks the install. Blocked upstream: lift once Kit admits 7.\",\n \"since\": \"2026-11-11\"\n }\n }\n}\n","import data from \"./versions.json\";\n\n/**\n * The dependency ranges every vela project starts from, in one place:\n * `versions.json` beside this file.\n *\n * Three things read it. The patterns here install from it (`spec`). The vela\n * CLI's `minimal` and `static` templates, and the velastack-templates\n * baselines built on them, list the same ranges and each carry a test that\n * they still do. And `scripts/bump-versions.ts` keeps it current.\n *\n * So a version is changed here and nowhere else; the other copies follow it,\n * and their tests fail until they do.\n */\nexport const VERSIONS: Readonly<Record<string, string>> = data.packages;\n\n/** Packages kept below their latest release on purpose, and why. */\nexport const VERSION_HOLDS: Readonly<\n Record<string, { reason: string; since: string }>\n> = data.holds;\n\n/** Packages whose range follows another project's rather than npm's latest. */\nexport const VERSION_TRACKS: Readonly<\n Record<string, { source: string; reason: string }>\n> = data.tracks;\n\n/**\n * The oldest Node a vela project may run on: the floor of its `engines.node`.\n * Projects set `engine-strict`, so no listed package may require a later one.\n */\nexport const NODE_FLOOR: string = data.node;\n\n/** The install spec for a listed package: `spec(\"zod\")` is `zod@^4.6.7`. */\nexport function spec(name: string): string {\n const range = VERSIONS[name];\n if (range === undefined) {\n throw new Error(\n `${name} is not in src/core/versions.json; add it there before installing it.`,\n );\n }\n return `${name}@${range}`;\n}\n","import { VERSIONS, spec } from \"./versions\";\n\nexport const DATA_DIR = \"data\";\nexport const MIGRATIONS_DIR = \"migrations\";\nexport const FIXTURE_PREFIX = \"vela\";\nexport const PUBLIC_DIR = \"(public)\";\nexport const APP_DIR = \"(app)\";\nexport const AUTHED_REDIRECT_PATH = \"/dashboard\";\nexport const API_URL = \"http://localhost:5173\";\n\n/**\n * The table helpers this repo ships (`data-table`, `column-header`,\n * `faceted-filter`, `pagination`) and the pages the scaffold generators emit\n * target TanStack Table v9, whose API and types are incompatible with v8; see\n * `assertTableCoreV9` for projects that still have the v8 helpers.\n */\nexport const TANSTACK_TABLE_CORE = spec(\"@tanstack/table-core\");\n\n/** The major `TANSTACK_TABLE_CORE` pins. */\nexport const TANSTACK_TABLE_CORE_MAJOR = Number(\n /\\d+/.exec(VERSIONS[\"@tanstack/table-core\"]!)![0],\n);\n\n/**\n * `file-form` and `multiselect` build on formsnap's field context. 2.1.0 is\n * the first release whose superforms peer admits 3.x; 2.0 needed an npm\n * override, which `writeResult` now removes (`reconcileFormsnap`).\n */\nexport const FORMSNAP = spec(\"formsnap\");\n\n/**\n * The superforms range a project starts on: 3.x, the line that supports\n * SvelteKit 3. A caret like any other dependency, now that formsnap 2.1 peers\n * `^3.0.0`; it was an exact version while 3.0 was a `next` prerelease, because\n * a caret on a prerelease follows every later `next` build. `writeResult`,\n * `vela migrate` and `vela bless` still move a project off one of those\n * prerelease pins (`reconcileFormsnap`).\n *\n * The name is from the exact-pin days and is kept for the CLI, which imports\n * it; the value is a range.\n */\nexport const SUPERFORMS_VERSION = VERSIONS[\"sveltekit-superforms\"]!;\n\n/**\n * What a generated superforms page needs. Vela's templates already carry\n * both; a project vela did not create may have neither.\n */\nexport const SUPERFORMS = spec(\"sveltekit-superforms\");\n\n/** The flash-message line that supports SvelteKit 3. */\nexport const FLASH = spec(\"sveltekit-flash-message\");\n\n/** The adapter `vela enable backend` moves a project to. */\nexport const ADAPTER_NODE = spec(\"@sveltejs/adapter-node\");\n\n/** The adapter a static project builds with (`vela disable backend`). */\nexport const ADAPTER_STATIC = spec(\"@sveltejs/adapter-static\");\n\n/** The VelaStack libraries' SvelteKit 3 releases. */\nexport const VELASTACK_KIT = spec(\"@velastack/kit\");\n/** 0.4.2 or later: it proxies plugin webhooks (pocketbase-whatsapp) to PocketBase. */\nexport const VELASTACK_POCKETBASE = spec(\"@velastack/pocketbase\");\nexport const VELASTACK_CMS = spec(\"@velastack/cms\");\n/** wa.me links, order messages and hosted order recording, for payments on WhatsApp. */\nexport const VELASTACK_WHATSAPP = spec(\"@velastack/whatsapp\");\nexport const NEGOTIATE = spec(\"sveltekit-negotiate\");\nexport const ZOD = spec(\"zod\");\n/** Renders HTML and CSS to an image; a native module, so it must be a dependency. */\nexport const TAKUMI = spec(\"@takumi-rs/core\");\n\n/** What `vela enable i18n` installs: wuchale and its Svelte adapter. */\nexport const WUCHALE = spec(\"wuchale\");\nexport const WUCHALE_SVELTE = spec(\"@wuchale/svelte\");\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A,GCcaqB,IAA6CrB,EAAK,UAGlDsB,IAETtB,EAAK,OAGIuB,IAETvB,EAAK,QAMIwB,IAAqBxB,EAAK;AAGvC,SAAgByB,EAAK,GAAsB;CACzC,IAAMC,IAAQL,EAASM;CACvB,IAAID,MAAU,KAAA,GACZ,MAAU,MACR,GAAGC,EAAK,sEACV;CAEF,OAAO,GAAGA,EAAK,GAAGD;AACpB;;;ACvCA,IAAaE,IAAW,QACXC,IAAiB,cAEjBC,IAAa,YACbC,IAAU,SAUVC,IAAsBP,EAAK,sBAAsB,GAGjDQ,IAA4B,OACvC,MAAM,KAAKZ,EAAS,uBAAwB,CAAC,CAAE,EACjD,GAOaa,IAAWT,EAAK,UAAU,GAa1BU,IAAqBd,EAAS,yBAM9Be,IAAaX,EAAK,sBAAsB,GAGxCY,IAAQZ,EAAK,yBAAyB,GAGtCa,IAAeb,EAAK,wBAAwB,GAG5Cc,IAAiBd,EAAK,0BAA0B,GAGhDe,IAAgBf,EAAK,gBAAgB,GAErCgB,IAAuBhB,EAAK,uBAAuB,GACnDiB,IAAgBjB,EAAK,gBAAgB,GAErCkB,IAAqBlB,EAAK,qBAAqB,GAC/CmB,IAAYnB,EAAK,qBAAqB,GACtCoB,IAAMpB,EAAK,KAAK,GAEhBqB,IAASrB,EAAK,iBAAiB,GAG/BsB,IAAUtB,EAAK,SAAS,GACxBuB,IAAiBvB,EAAK,iBAAiB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as e } from "./errors-DR3gF_7a.js";
|
|
2
|
-
import {
|
|
2
|
+
import { v as t } from "./constants-CUv536Rj.js";
|
|
3
3
|
import { r as n } from "./util-BLYliuUK.js";
|
|
4
4
|
import { c as r, i, r as a } from "./providers-CL9kQ4hp.js";
|
|
5
5
|
import { t as o } from "./stripe-customer-B3tP8gtD.js";
|
|
@@ -177,4 +177,4 @@ var ae = "import { describe, expect, it } from 'vitest';\nimport { requestCountr
|
|
|
177
177
|
//#endregion
|
|
178
178
|
export { T as A, h as B, M as C, O as D, k as E, b as F, u as G, p as H, y as I, l as K, v as L, C as M, S as N, D as O, x as P, _ as R, N as S, A as T, f as U, m as V, d as W, R as _, Z as a, F as b, q as c, W as d, U as f, z as g, B as h, Y as i, w as j, E as k, K as l, V as m, ae as n, ie as o, H as p, X as r, J as s, oe as t, G as u, L as v, j as w, P as x, I as y, g as z };
|
|
179
179
|
|
|
180
|
-
//# sourceMappingURL=currency.server-
|
|
180
|
+
//# sourceMappingURL=currency.server-DygAf6a1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currency.server-CzHS7Svd.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__1_2_","__import_glob__1_3_","__import_glob__1_4_","__import_glob__1_5_","__import_glob__1_6_","__import_glob__1_7_","__import_glob__1_8_","__import_glob__1_9_","__import_glob__1_10_","__import_glob__1_11_","__import_glob__1_12_","__import_glob__1_13_","__import_glob__1_14_","__import_glob__1_15_","__import_glob__1_16_","__import_glob__1_17_","__import_glob__1_18_","__import_glob__1_19_","__import_glob__1_20_","__import_glob__1_21_","__import_glob__1_22_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","__import_glob__2_3_","__import_glob__2_4_","__import_glob__2_5_","__import_glob__2_6_","__import_glob__2_7_","__import_glob__2_8_","__import_glob__2_9_","__import_glob__2_10_","__import_glob__2_11_","__import_glob__2_12_","__import_glob__2_13_","__import_glob__2_14_","__import_glob__2_15_","__import_glob__2_16_","__import_glob__2_17_","InvalidArgumentError","VELASTACK_WHATSAPP","filesFromGlob","resolveProvider","providerCreates","stripe_customer_default","_page_server_default","_page_default","currency_select_default","currency_svelte_default","buy_button_default","shopify_default","confirm_dialog_default","payment_button_default","payment_dialog_default","stripe_constants_default","stripe_payment_form_default","use_payment_intent_svelte_default","use_stripe_svelte_default","stripe_default","stripe_event_default","sync_stripe_catalog_default","_server_default$3","server_test_default$6","_server_default$2","dispatch_default$1","server_test_default$5","succeeded_default$1","server_test_default$4","customer_fields_default","order_button_default","order_test_default","order_default","setup_button_default","setup_dialog_default","link_stripe_customer_default","sync_stripe_customers_default","_layout_server_default","README_default","_server_default$1","server_test_default$3","_server_default","server_test_default$2","dispatch_default","server_test_default$1","succeeded_default","attached_default","server_test_default","PROVIDERS","META","envEditsFor","providerEnvEdits","provider","supplied","COMPONENTS","PACKAGES","createsRaw","providersRaw","providersAppModeRaw","isUnitTest","path","generate","options","current","label","candidate","isAppMode","creates","unitTests","file","components","a","b","currency_server_test_default","currency_server_default"],"sources":["../../src/patterns/enable/payments/generate.ts"],"sourcesContent":["import type {\n Component,\n Options,\n Package,\n Provider,\n Result,\n} from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport {\n providerCreates,\n providerEnvEdits,\n resolveProvider,\n} from \"../../../core/providers\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport { VELASTACK_WHATSAPP } from \"../../../core/constants\";\nimport { filesFromGlob } from \"../../../core/util\";\n\n/**\n * The providers in prompt order. Each one's `env` keys are what the CLI asks\n * for, what `generate.runtime.ts` writes to `.env` (in this order, under a\n * `# <Label> credentials` heading) and declares in `src/env.ts`.\n */\nexport const PROVIDERS: Provider[] = [\n {\n id: \"stripe\",\n label: \"Stripe\",\n env: [\n {\n key: \"STRIPE_SECRET_KEY\",\n label: \"Stripe secret key\",\n placeholder: \"sk_...\",\n secret: true,\n required: true,\n description:\n \"Stripe secret key (`sk_...`) the server calls the Stripe API with.\",\n },\n {\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n label: \"Stripe publishable key\",\n placeholder: \"pk_...\",\n public: true,\n required: true,\n description:\n \"Stripe publishable key (`pk_...`) that Stripe.js loads in the browser.\",\n },\n {\n key: \"STRIPE_WEBHOOK_SECRET\",\n label: \"Stripe webhook signing secret\",\n placeholder: \"whsec_...\",\n secret: true,\n required: true,\n description:\n \"Signing secret (`whsec_...`) that `/webhooks/stripe` verifies events with.\",\n },\n ],\n // The webhook route predates the `src/env.ts` declarations, so a project\n // that enabled payments before them is still recognised.\n markers: [\n { env: \"STRIPE_SECRET_KEY\" },\n { path: \"src/routes/webhooks/stripe\" },\n ],\n // Products, prices and customers are synced into PocketBase by workflows.\n requires: { backend: true, workflows: true },\n },\n {\n id: \"shopify\",\n label: \"Shopify\",\n env: [\n {\n key: \"PUBLIC_SHOPIFY_STORE_DOMAIN\",\n label: \"Shopify store domain\",\n placeholder: \"your-store.myshopify.com\",\n public: true,\n required: true,\n description:\n \"The store's `*.myshopify.com` domain the Storefront API is called on.\",\n },\n {\n key: \"PUBLIC_SHOPIFY_STOREFRONT_TOKEN\",\n label: \"Shopify Storefront API public access token\",\n public: true,\n required: true,\n description:\n \"Public Storefront API access token, from the store's Headless channel.\",\n },\n ],\n },\n {\n id: \"whatsapp\",\n label: \"WhatsApp\",\n env: [\n {\n key: \"PUBLIC_WHATSAPP_NUMBER\",\n label: \"WhatsApp number orders are sent to\",\n placeholder: \"+353 1 555 0100\",\n public: true,\n required: true,\n description:\n \"The business's WhatsApp number, with country code, that orders open a chat with.\",\n },\n {\n key: \"PUBLIC_WHATSAPP_ORDER_FORM\",\n label: \"Hosted VelaStack form orders are recorded to\",\n placeholder: \"https://velastack.dev/v1/projects/<project>/forms/order\",\n public: true,\n description:\n \"The hosted VelaStack form each order is recorded to, so it is kept even if the chat is never sent. Empty records nothing.\",\n },\n ],\n },\n];\n\n/** What `resolveProvider` needs; `index.ts` spreads the rest of the metadata. */\nexport const META = { slug: \"enable-payments\", providers: PROVIDERS };\n\n/** The `.env` lines for a provider, under a `# <Label> credentials` heading. */\nexport function envEditsFor(\n provider: Provider,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return providerEnvEdits(provider, `${provider.label} credentials`, supplied);\n}\n\n// `select` is the currency select every provider gets.\nconst COMPONENTS: Record<string, Component[]> = {\n stripe: [\"dialog\", \"input\", \"label\", \"select\"],\n shopify: [\"button\", \"select\"],\n whatsapp: [\"button\", \"dialog\", \"input\", \"label\", \"textarea\", \"select\"],\n};\n\nconst PACKAGES: Record<string, Package[]> = {\n stripe: [\"stripe\", \"@stripe/stripe-js\"],\n shopify: [\"@shopify/storefront-api-client\"],\n whatsapp: [VELASTACK_WHATSAPP],\n};\n\n// Shared by every provider: the currency prices show in, and its select.\nconst createsRaw = import.meta.glob<string>(\"./creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersRaw = import.meta.glob<string>(\"./providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersAppModeRaw = import.meta.glob<string>(\n \"./providers-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nexport interface GenerateContext {\n /**\n * The project can run unit tests (vitest is installed), so a provider's\n * `*.test.ts` beside its code is written too. Server tests (`server.test.ts`)\n * always are: they run under `vela test:server`, which brings its own runner.\n */\n unitTests?: boolean;\n}\n\nconst isUnitTest = (path: string) =>\n path.endsWith(\".test.ts\") && !path.endsWith(\"server.test.ts\");\n\nexport async function generate(\n options: Options,\n { unitTests = false }: GenerateContext = {},\n) {\n const provider = resolveProvider(META, options);\n\n // A second provider would leave the project with both, and the patterns\n // built on payments could no longer tell which one it uses.\n const current = options.providers?.payments;\n if (current !== undefined && current !== provider.id) {\n const label =\n PROVIDERS.find((candidate) => candidate.id === current)?.label ?? current;\n throw new InvalidArgumentError(\n `This project already uses ${label} payments. To switch to ${provider.label}, ` +\n \"run `vela disable payments` first, then enable payments again.\",\n );\n }\n // Stripe keeps cards and customers for signed-in users; Shopify's checkout\n // owns its customers and WhatsApp has none, so neither has app-mode files.\n const isAppMode = options.features.auth;\n\n const creates = new Map(\n [\n ...Object.values(filesFromGlob(createsRaw, \"./creates/\")),\n ...providerCreates(providersRaw, provider.id),\n ]\n .filter((file) => unitTests || !isUnitTest(file.path))\n .map((file) => [file.path, file]),\n );\n if (isAppMode) {\n for (const file of providerCreates(\n providersAppModeRaw,\n provider.id,\n \"./providers-app-mode/\",\n )) {\n creates.set(file.path, file);\n }\n }\n\n const components = [...(COMPONENTS[provider.id] ?? [])];\n if (isAppMode && provider.id === \"stripe\") components.push(\"alert-dialog\");\n\n return {\n creates: [...creates.values()].sort((a, b) => a.path.localeCompare(b.path)),\n modifies: [],\n deletes: [],\n components,\n packages: PACKAGES[provider.id] ?? [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;A,ww2GAsBa2F,IAAwB;CACnC;EACE,IAAI;EACJ,OAAO;EACP,KAAK;GACH;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IACV,aACE;GACJ;GACA;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IACV,aACE;GACJ;GACA;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IACV,aACE;GACJ;EACF;EAGA,SAAS,CACP,EAAE,KAAK,oBAAoB,GAC3B,EAAE,MAAM,6BAA6B,CACvC;EAEA,UAAU;GAAE,SAAS;GAAM,WAAW;EAAK;CAC7C;CACA;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,QAAQ;GACR,UAAU;GACV,aACE;EACJ,GACA;GACE,KAAK;GACL,OAAO;GACP,QAAQ;GACR,UAAU;GACV,aACE;EACJ,CACF;CACF;CACA;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,QAAQ;GACR,UAAU;GACV,aACE;EACJ,GACA;GACE,KAAK;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"currency.server-DygAf6a1.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__1_2_","__import_glob__1_3_","__import_glob__1_4_","__import_glob__1_5_","__import_glob__1_6_","__import_glob__1_7_","__import_glob__1_8_","__import_glob__1_9_","__import_glob__1_10_","__import_glob__1_11_","__import_glob__1_12_","__import_glob__1_13_","__import_glob__1_14_","__import_glob__1_15_","__import_glob__1_16_","__import_glob__1_17_","__import_glob__1_18_","__import_glob__1_19_","__import_glob__1_20_","__import_glob__1_21_","__import_glob__1_22_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","__import_glob__2_3_","__import_glob__2_4_","__import_glob__2_5_","__import_glob__2_6_","__import_glob__2_7_","__import_glob__2_8_","__import_glob__2_9_","__import_glob__2_10_","__import_glob__2_11_","__import_glob__2_12_","__import_glob__2_13_","__import_glob__2_14_","__import_glob__2_15_","__import_glob__2_16_","__import_glob__2_17_","InvalidArgumentError","VELASTACK_WHATSAPP","filesFromGlob","resolveProvider","providerCreates","stripe_customer_default","_page_server_default","_page_default","currency_select_default","currency_svelte_default","buy_button_default","shopify_default","confirm_dialog_default","payment_button_default","payment_dialog_default","stripe_constants_default","stripe_payment_form_default","use_payment_intent_svelte_default","use_stripe_svelte_default","stripe_default","stripe_event_default","sync_stripe_catalog_default","_server_default$3","server_test_default$6","_server_default$2","dispatch_default$1","server_test_default$5","succeeded_default$1","server_test_default$4","customer_fields_default","order_button_default","order_test_default","order_default","setup_button_default","setup_dialog_default","link_stripe_customer_default","sync_stripe_customers_default","_layout_server_default","README_default","_server_default$1","server_test_default$3","_server_default","server_test_default$2","dispatch_default","server_test_default$1","succeeded_default","attached_default","server_test_default","PROVIDERS","META","envEditsFor","providerEnvEdits","provider","supplied","COMPONENTS","PACKAGES","createsRaw","providersRaw","providersAppModeRaw","isUnitTest","path","generate","options","current","label","candidate","isAppMode","creates","unitTests","file","components","a","b","currency_server_test_default","currency_server_default"],"sources":["../../src/patterns/enable/payments/generate.ts"],"sourcesContent":["import type {\n Component,\n Options,\n Package,\n Provider,\n Result,\n} from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport {\n providerCreates,\n providerEnvEdits,\n resolveProvider,\n} from \"../../../core/providers\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport { VELASTACK_WHATSAPP } from \"../../../core/constants\";\nimport { filesFromGlob } from \"../../../core/util\";\n\n/**\n * The providers in prompt order. Each one's `env` keys are what the CLI asks\n * for, what `generate.runtime.ts` writes to `.env` (in this order, under a\n * `# <Label> credentials` heading) and declares in `src/env.ts`.\n */\nexport const PROVIDERS: Provider[] = [\n {\n id: \"stripe\",\n label: \"Stripe\",\n env: [\n {\n key: \"STRIPE_SECRET_KEY\",\n label: \"Stripe secret key\",\n placeholder: \"sk_...\",\n secret: true,\n required: true,\n description:\n \"Stripe secret key (`sk_...`) the server calls the Stripe API with.\",\n },\n {\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n label: \"Stripe publishable key\",\n placeholder: \"pk_...\",\n public: true,\n required: true,\n description:\n \"Stripe publishable key (`pk_...`) that Stripe.js loads in the browser.\",\n },\n {\n key: \"STRIPE_WEBHOOK_SECRET\",\n label: \"Stripe webhook signing secret\",\n placeholder: \"whsec_...\",\n secret: true,\n required: true,\n description:\n \"Signing secret (`whsec_...`) that `/webhooks/stripe` verifies events with.\",\n },\n ],\n // The webhook route predates the `src/env.ts` declarations, so a project\n // that enabled payments before them is still recognised.\n markers: [\n { env: \"STRIPE_SECRET_KEY\" },\n { path: \"src/routes/webhooks/stripe\" },\n ],\n // Products, prices and customers are synced into PocketBase by workflows.\n requires: { backend: true, workflows: true },\n },\n {\n id: \"shopify\",\n label: \"Shopify\",\n env: [\n {\n key: \"PUBLIC_SHOPIFY_STORE_DOMAIN\",\n label: \"Shopify store domain\",\n placeholder: \"your-store.myshopify.com\",\n public: true,\n required: true,\n description:\n \"The store's `*.myshopify.com` domain the Storefront API is called on.\",\n },\n {\n key: \"PUBLIC_SHOPIFY_STOREFRONT_TOKEN\",\n label: \"Shopify Storefront API public access token\",\n public: true,\n required: true,\n description:\n \"Public Storefront API access token, from the store's Headless channel.\",\n },\n ],\n },\n {\n id: \"whatsapp\",\n label: \"WhatsApp\",\n env: [\n {\n key: \"PUBLIC_WHATSAPP_NUMBER\",\n label: \"WhatsApp number orders are sent to\",\n placeholder: \"+353 1 555 0100\",\n public: true,\n required: true,\n description:\n \"The business's WhatsApp number, with country code, that orders open a chat with.\",\n },\n {\n key: \"PUBLIC_WHATSAPP_ORDER_FORM\",\n label: \"Hosted VelaStack form orders are recorded to\",\n placeholder: \"https://velastack.dev/v1/projects/<project>/forms/order\",\n public: true,\n description:\n \"The hosted VelaStack form each order is recorded to, so it is kept even if the chat is never sent. Empty records nothing.\",\n },\n ],\n },\n];\n\n/** What `resolveProvider` needs; `index.ts` spreads the rest of the metadata. */\nexport const META = { slug: \"enable-payments\", providers: PROVIDERS };\n\n/** The `.env` lines for a provider, under a `# <Label> credentials` heading. */\nexport function envEditsFor(\n provider: Provider,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return providerEnvEdits(provider, `${provider.label} credentials`, supplied);\n}\n\n// `select` is the currency select every provider gets.\nconst COMPONENTS: Record<string, Component[]> = {\n stripe: [\"dialog\", \"input\", \"label\", \"select\"],\n shopify: [\"button\", \"select\"],\n whatsapp: [\"button\", \"dialog\", \"input\", \"label\", \"textarea\", \"select\"],\n};\n\nconst PACKAGES: Record<string, Package[]> = {\n stripe: [\"stripe\", \"@stripe/stripe-js\"],\n shopify: [\"@shopify/storefront-api-client\"],\n whatsapp: [VELASTACK_WHATSAPP],\n};\n\n// Shared by every provider: the currency prices show in, and its select.\nconst createsRaw = import.meta.glob<string>(\"./creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersRaw = import.meta.glob<string>(\"./providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersAppModeRaw = import.meta.glob<string>(\n \"./providers-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nexport interface GenerateContext {\n /**\n * The project can run unit tests (vitest is installed), so a provider's\n * `*.test.ts` beside its code is written too. Server tests (`server.test.ts`)\n * always are: they run under `vela test:server`, which brings its own runner.\n */\n unitTests?: boolean;\n}\n\nconst isUnitTest = (path: string) =>\n path.endsWith(\".test.ts\") && !path.endsWith(\"server.test.ts\");\n\nexport async function generate(\n options: Options,\n { unitTests = false }: GenerateContext = {},\n) {\n const provider = resolveProvider(META, options);\n\n // A second provider would leave the project with both, and the patterns\n // built on payments could no longer tell which one it uses.\n const current = options.providers?.payments;\n if (current !== undefined && current !== provider.id) {\n const label =\n PROVIDERS.find((candidate) => candidate.id === current)?.label ?? current;\n throw new InvalidArgumentError(\n `This project already uses ${label} payments. To switch to ${provider.label}, ` +\n \"run `vela disable payments` first, then enable payments again.\",\n );\n }\n // Stripe keeps cards and customers for signed-in users; Shopify's checkout\n // owns its customers and WhatsApp has none, so neither has app-mode files.\n const isAppMode = options.features.auth;\n\n const creates = new Map(\n [\n ...Object.values(filesFromGlob(createsRaw, \"./creates/\")),\n ...providerCreates(providersRaw, provider.id),\n ]\n .filter((file) => unitTests || !isUnitTest(file.path))\n .map((file) => [file.path, file]),\n );\n if (isAppMode) {\n for (const file of providerCreates(\n providersAppModeRaw,\n provider.id,\n \"./providers-app-mode/\",\n )) {\n creates.set(file.path, file);\n }\n }\n\n const components = [...(COMPONENTS[provider.id] ?? [])];\n if (isAppMode && provider.id === \"stripe\") components.push(\"alert-dialog\");\n\n return {\n creates: [...creates.values()].sort((a, b) => a.path.localeCompare(b.path)),\n modifies: [],\n deletes: [],\n components,\n packages: PACKAGES[provider.id] ?? [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;A,ww2GAsBa2F,IAAwB;CACnC;EACE,IAAI;EACJ,OAAO;EACP,KAAK;GACH;IACE,KAAK;IACL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9C,CAAC,CACE,QAAQ,MAASgB,KAAa,CAACT,GAAWU,EAAK,IAAI,CAAC,CAAC,CACrD,KAAK,MAAS,CAACA,EAAK,MAAMA,CAAI,CAAC,CACpC;CACA,IAAIH,GACF,KAAK,IAAMG,KAAQjE,EACjBsD,IACAN,EAAS,IACT,uBACF,GACE,EAAQ,IAAIiB,EAAK,MAAMA,CAAI;CAI/B,IAAMC,IAAa,CAAC,GAAIhB,EAAWF,EAAS,OAAO,CAAC,CAAE;CAGtD,OAFIc,KAAad,EAAS,OAAO,YAAUkB,EAAW,KAAK,cAAc,GAElE;EACL,SAAS,CAAC,GAAGH,EAAQ,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,MAAMI,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;EAC1E,UAAU,CAAC;EACX,SAAS,CAAC;EACV;EACA,UAAUjB,EAASH,EAAS,OAAO,CAAC;EACpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { i as e, n as t, r as n, t as r } from "./env-vars-file-B_6esJW3.js";
|
|
2
2
|
import { a as i } from "./util-BLYliuUK.js";
|
|
3
|
-
import { n as a } from "./shared-
|
|
3
|
+
import { n as a } from "./shared-CAjLx_8Z.js";
|
|
4
4
|
import { i as o, o as s } from "./ts-morph-helpers-CHI9wAil.js";
|
|
5
|
-
import { r as c } from "./modify-file-
|
|
5
|
+
import { r as c } from "./modify-file-D9U2LXEa.js";
|
|
6
6
|
import l from "node:fs";
|
|
7
7
|
import u from "node:path";
|
|
8
8
|
import { Node as d, Project as f, QuoteKind as p, SyntaxKind as m } from "ts-morph";
|
|
@@ -272,4 +272,4 @@ function R(e) {
|
|
|
272
272
|
//#endregion
|
|
273
273
|
export { P as modifyEnvVars, F as modifyEnvVarsFiles, k as readEnvVarNames, I as unmodifyEnvVars, L as unmodifyEnvVarsFiles };
|
|
274
274
|
|
|
275
|
-
//# sourceMappingURL=env-vars-
|
|
275
|
+
//# sourceMappingURL=env-vars-XvAeH6u5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env-vars-CNH-ItSY.js","names":["envVarsFile","ENV_MODULE","envVarEntry","ENV_DECL_CANDIDATES","languageFromPath","toDeleteEntry","ensureNamedImport","formatLikeSource","modifyOutcomeToFile","fs","path","VARIABLES","DEFINE","unwrap","current","expr","Node","exportedLocalName","decl","sf","spec","bindsName","name","ni","statement","nameNode","SyntaxKind","id","locateVariables","reExported","local","init","value","arg","object","propertyName","prop","inner","declaredNames","names","quoteOf","addEnvVars","located","quote","unique","dedupe","specs","entries","declared","missing","removeEnvVars","wanted","doomed","seen","newProject","Project","QuoteKind","findEnvDecl","rel","abs","root","readEnvVarNames","filePath","relative","REASONS","addHint","file","reason","removeHint","modifyEnvVars","existing","original","result","changed","modifyEnvVarsFiles","create","modify","unmodifyEnvVars","holdsNothing","unmodifyEnvVarsFiles","deleted","outcome"],"sources":["../../src/runtime/env-vars.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type Expression,\n type ObjectLiteralElementLike,\n type ObjectLiteralExpression,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { modifyOutcomeToFile } from \"./modify-file\";\nimport {\n ENV_DECL_CANDIDATES,\n envVarEntry,\n envVarsFile,\n ENV_MODULE,\n type EnvVarSpec,\n} from \"./env-vars-file\";\nimport { ensureNamedImport, formatLikeSource } from \"./ts-morph-helpers\";\n\nexport { ENV_DECL_CANDIDATES, envVarEntry, envVarsFile, type EnvVarSpec };\n\n/**\n * Declares environment variables in `src/env.ts`, where SvelteKit 3 reads\n * them: a variable it finds no declaration for is not exposed through\n * `$app/env/private` or `$app/env/public` at all.\n *\n * Three shapes of `variables` are edited:\n *\n * - `export const variables = defineEnvVars({ ... })`\n * - `const variables = defineEnvVars({ ... }); export { variables }`\n * - either of the above with a plain object literal in place of the call\n *\n * Entries are matched by property name, quoted or not, and an entry that is\n * already there is never touched: a project that declared `STRIPE_SECRET_KEY`\n * as required keeps it required.\n */\n\nconst VARIABLES = \"variables\";\nconst DEFINE = \"defineEnvVars\";\n\nexport type EnvVarsUnsupported =\n /** `variables` is exported some other way: a function, `export let variables;`, a re-export. */\n | \"not-variable\"\n /** `variables` is not an object literal or `defineEnvVars({ ... })`. */\n | \"not-object\"\n /** The object spreads another one in, which may already declare the names. */\n | \"spread\"\n /** A computed key (`[name]: ...`) whose name can't be read. */\n | \"computed-key\";\n\nexport type EnvVarsEditResult =\n | { status: \"changed\" | \"unchanged\" }\n | { status: \"unsupported\"; reason: EnvVarsUnsupported };\n\ntype Located =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"missing\" }\n | { kind: \"unsupported\"; reason: EnvVarsUnsupported };\n\nfunction unwrap(expr: Expression): Expression {\n let current = expr;\n for (;;) {\n if (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current)\n ) {\n current = current.getExpression();\n continue;\n }\n return current;\n }\n}\n\n/** The local name exported as `variables`: itself, or `x` in `export { x as variables }`. */\nfunction exportedLocalName(sf: SourceFile): string | null | \"re-export\" {\n for (const decl of sf.getExportDeclarations()) {\n for (const spec of decl.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== VARIABLES) continue;\n if (decl.getModuleSpecifier()) return \"re-export\";\n return spec.getName();\n }\n }\n return null;\n}\n\n/** A top-level import or destructuring pattern that binds `name`. */\nfunction bindsName(sf: SourceFile, name: string): boolean {\n const imported = sf\n .getImportDeclarations()\n .some(\n (decl) =>\n decl.getDefaultImport()?.getText() === name ||\n decl.getNamespaceImport()?.getText() === name ||\n decl\n .getNamedImports()\n .some(\n (ni) => (ni.getAliasNode()?.getText() ?? ni.getName()) === name,\n ),\n );\n if (imported) return true;\n return sf.getVariableStatements().some((statement) =>\n statement.getDeclarations().some((decl) => {\n const nameNode = decl.getNameNode();\n return (\n !Node.isIdentifier(nameNode) &&\n nameNode\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name &&\n (Node.isBindingElement(id.getParent()) ||\n Node.isShorthandPropertyAssignment(id.getParent())),\n )\n );\n }),\n );\n}\n\nfunction locateVariables(sf: SourceFile): Located {\n const reExported = exportedLocalName(sf);\n if (reExported === \"re-export\") {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const local = reExported ?? VARIABLES;\n\n const decl = sf.getVariableDeclaration(local);\n if (!decl) {\n // A function, class, import or destructured binding of that name,\n // exported or not, is not ours to replace.\n const taken =\n sf.getFunction(local) ?? sf.getClass(local) ?? sf.getEnum(local);\n if (taken || reExported || bindsName(sf, local)) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n return { kind: \"missing\" };\n }\n if (!reExported && !decl.isExported()) {\n // `const variables = ...` that SvelteKit can't see; exporting it is the\n // developer's call, not ours.\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n if (!Node.isIdentifier(decl.getNameNode())) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const init = decl.getInitializer();\n if (!init) return { kind: \"unsupported\", reason: \"not-variable\" };\n\n const value = unwrap(init);\n if (Node.isObjectLiteralExpression(value)) {\n return { kind: \"object\", object: value };\n }\n if (\n Node.isCallExpression(value) &&\n value.getExpression().getText() === DEFINE\n ) {\n const arg = value.getArguments()[0];\n const object = arg && unwrap(arg as Expression);\n if (object && Node.isObjectLiteralExpression(object)) {\n return { kind: \"object\", object };\n }\n }\n return { kind: \"unsupported\", reason: \"not-object\" };\n}\n\n/** A property's name as SvelteKit sees it, `null` for a spread or computed key. */\nfunction propertyName(prop: ObjectLiteralElementLike): string | null {\n if (Node.isSpreadAssignment(prop)) return null;\n const nameNode = prop.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) {\n const inner = nameNode.getExpression();\n return Node.isStringLiteral(inner) ||\n Node.isNoSubstitutionTemplateLiteral(inner)\n ? inner.getLiteralText()\n : null;\n }\n if (\n Node.isStringLiteral(nameNode) ||\n Node.isNoSubstitutionTemplateLiteral(nameNode)\n ) {\n return nameNode.getLiteralText();\n }\n return nameNode.getText();\n}\n\nfunction declaredNames(\n object: ObjectLiteralExpression,\n): Set<string> | EnvVarsUnsupported {\n const names = new Set<string>();\n for (const prop of object.getProperties()) {\n if (Node.isSpreadAssignment(prop)) return \"spread\";\n const name = propertyName(prop);\n if (name === null) return \"computed-key\";\n names.add(name);\n }\n return names;\n}\n\n/** The quote the file already writes its strings with. */\nfunction quoteOf(sf: SourceFile): \"'\" | '\"' {\n const first = sf.getFirstDescendantByKind(SyntaxKind.StringLiteral);\n return first?.getText().startsWith('\"') ? '\"' : \"'\";\n}\n\n/**\n * Add a declaration for every spec `sf` doesn't declare yet. Creates\n * `export const variables = defineEnvVars({ ... })`, and its import, when the\n * file has no `variables` at all. Neither formats nor saves.\n */\nexport function addEnvVars(\n sf: SourceFile,\n specs: EnvVarSpec[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const quote = quoteOf(sf);\n\n if (located.kind === \"missing\") {\n const unique = dedupe(specs);\n if (unique.length === 0) return { status: \"unchanged\" };\n ensureNamedImport(sf, ENV_MODULE, DEFINE);\n const entries = unique\n .map((spec) => `\\t${envVarEntry(spec, { quote })}`)\n .join(\",\\n\");\n sf.addStatements(\n `\\nexport const ${VARIABLES} = ${DEFINE}({\\n${entries}\\n});`,\n );\n return { status: \"changed\" };\n }\n\n const declared = declaredNames(located.object);\n if (typeof declared === \"string\") {\n return { status: \"unsupported\", reason: declared };\n }\n const missing = dedupe(specs).filter((spec) => !declared.has(spec.name));\n if (missing.length === 0) return { status: \"unchanged\" };\n for (const spec of missing) {\n located.object.addProperty(envVarEntry(spec, { quote }));\n }\n return { status: \"changed\" };\n}\n\n/**\n * Remove the declarations of `names` from `sf`. A file with no `variables`,\n * or none of the names, is unchanged. Neither formats nor saves.\n */\nexport function removeEnvVars(\n sf: SourceFile,\n names: string[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"missing\") return { status: \"unchanged\" };\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const wanted = new Set(names);\n const doomed = located.object.getProperties().filter((prop) => {\n const name = propertyName(prop);\n return name !== null && wanted.has(name);\n });\n if (doomed.length === 0) return { status: \"unchanged\" };\n for (const prop of doomed.reverse()) prop.remove();\n if (located.object.getProperties().length === 0) {\n located.object.replaceWithText(\"{}\");\n }\n return { status: \"changed\" };\n}\n\nfunction dedupe(specs: EnvVarSpec[]): EnvVarSpec[] {\n const seen = new Set<string>();\n return specs.filter((spec) => {\n if (seen.has(spec.name)) return false;\n seen.add(spec.name);\n return true;\n });\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/** The project's declaration file: `src/env.ts` or `src/env.js`, if either exists. */\nexport function findEnvDecl(root: string): string | null {\n for (const rel of ENV_DECL_CANDIDATES) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\n/**\n * The names `src/env.ts` (or `src/env.js`) declares. Spreads and computed\n * keys it can't read are skipped rather than failing the whole read, so a\n * declaration file this module couldn't edit still reports what it can. No\n * file, or no `variables` this can read, is an empty set.\n */\nexport function readEnvVarNames(root: string): Set<string> {\n const filePath = findEnvDecl(root);\n if (!filePath) return new Set();\n\n const sf = newProject().addSourceFileAtPath(filePath);\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return new Set();\n\n const names = new Set<string>();\n for (const prop of located.object.getProperties()) {\n const name = propertyName(prop);\n if (name !== null) names.add(name);\n }\n return names;\n}\n\nfunction relative(root: string, filePath: string): string {\n return path.relative(root, filePath).split(path.sep).join(\"/\");\n}\n\nconst REASONS: Record<EnvVarsUnsupported, string> = {\n \"not-variable\": \"its `variables` export is not a variable this can edit\",\n \"not-object\":\n \"`variables` is not an object literal or a `defineEnvVars({ ... })` call\",\n spread: \"`variables` spreads in another object\",\n \"computed-key\": \"`variables` has a computed key\",\n};\n\nfunction addHint(\n file: string,\n reason: EnvVarsUnsupported,\n specs: EnvVarSpec[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n \"Declare these in the object passed to defineEnvVars() (or exported as `variables`), skipping any already there:\",\n \"\",\n ...dedupe(specs).map((spec) => `${envVarEntry(spec)},`),\n ].join(\"\\n\");\n}\n\nfunction removeHint(\n file: string,\n reason: EnvVarsUnsupported,\n names: string[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n `Remove these declarations from \\`variables\\` by hand: ${names.join(\", \")}`,\n ].join(\"\\n\");\n}\n\nexport interface ModifyEnvVarsResult {\n /** `src/env.ts` to create, when the project has no declaration file. */\n create?: File;\n /** The existing declaration file, already saved when `outcome` changed it. */\n modify?: { filePath: string; outcome: ModifyOutcome };\n}\n\n/**\n * Declare `specs` in the project's `src/env.ts` (or `src/env.js`). Existing\n * entries are never touched.\n *\n * - No declaration file: `create` holds a new `src/env.ts` (always `.ts`,\n * written like the CLI templates' one); nothing is written yet.\n * - An existing file is edited and saved in place, and `modify` reports it\n * like every other runtime modifier: turn it into a File with\n * `modifyOutcomeToFile` (or use {@link modifyEnvVarsFiles}).\n * - A file whose `variables` can't be edited safely is left alone, and the\n * `failed` outcome's message lists the exact entries to paste.\n */\nexport function modifyEnvVars(\n root: string,\n specs: EnvVarSpec[],\n): ModifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n if (dedupe(specs).length === 0) return {};\n const filePath = path.join(root, ENV_DECL_CANDIDATES[0]);\n return {\n create: {\n path: filePath,\n language: languageFromPath(filePath),\n content: envVarsFile(specs),\n status: \"success\",\n },\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = addEnvVars(sf, specs);\n if (result.status === \"unsupported\") {\n return {\n modify: {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: addHint(relative(root, existing), result.reason, specs),\n },\n },\n };\n }\n if (result.status === \"unchanged\") {\n return {\n modify: {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n },\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n modify: { filePath: existing, outcome: { status: \"success\", changed } },\n };\n}\n\n/** {@link modifyEnvVars} as the File entries a pattern's Result carries. */\nexport function modifyEnvVarsFiles(\n root: string,\n specs: EnvVarSpec[],\n): { create: File | null; modify: File | null } {\n const { create, modify } = modifyEnvVars(root, specs);\n return {\n create: create ?? null,\n modify: modify\n ? modifyOutcomeToFile(modify.filePath, modify.outcome)\n : null,\n };\n}\n\nexport interface UnmodifyEnvVarsResult {\n filePath: string;\n outcome: ModifyOutcome;\n /**\n * The revert left nothing but the `defineEnvVars` import and an empty\n * `variables`. The emptied file has been saved; the caller reports it as a\n * delete (`toDeleteEntry(filePath)`) instead of a modify, as\n * {@link unmodifyEnvVarsFiles} does.\n */\n deleted: boolean;\n}\n\n/**\n * Remove the declarations of `names` from `src/env.ts` (or `.js`). A project\n * without the file, or without the names, is a no-op success.\n */\nexport function unmodifyEnvVars(\n root: string,\n names: string[],\n): UnmodifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n return {\n filePath: path.join(root, ENV_DECL_CANDIDATES[0]),\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = removeEnvVars(sf, names);\n if (result.status === \"unsupported\") {\n return {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: removeHint(relative(root, existing), result.reason, names),\n },\n deleted: false,\n };\n }\n if (result.status === \"unchanged\") {\n return {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n filePath: existing,\n outcome: { status: \"success\", changed },\n deleted: changed && holdsNothing(sf),\n };\n}\n\n/** {@link unmodifyEnvVars} as the File entries a pattern's Result carries. */\nexport function unmodifyEnvVarsFiles(\n root: string,\n names: string[],\n): { modify: File | null; delete: File | null } {\n const { filePath, outcome, deleted } = unmodifyEnvVars(root, names);\n if (deleted) return { modify: null, delete: toDeleteEntry(filePath) };\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * Only the `defineEnvVars` import, an empty `variables` and its\n * `export { variables }` are left. Comments don't count.\n */\nfunction holdsNothing(sf: SourceFile): boolean {\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return false;\n if (located.object.getProperties().length > 0) return false;\n const decl = located.object.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n return sf.getStatements().every((statement: Statement) => {\n if (statement === decl) return true;\n if (Node.isEmptyStatement(statement)) return true;\n if (Node.isImportDeclaration(statement)) {\n return (\n statement.getModuleSpecifierValue() === ENV_MODULE &&\n !statement.getDefaultImport() &&\n !statement.getNamespaceImport() &&\n statement.getNamedImports().every((ni) => ni.getName() === DEFINE)\n );\n }\n if (Node.isExportDeclaration(statement)) {\n return (\n !statement.getModuleSpecifier() &&\n statement\n .getNamedExports()\n .every(\n (spec) =>\n (spec.getAliasNode()?.getText() ?? spec.getName()) === VARIABLES,\n )\n );\n }\n return false;\n });\n}\n"],"mappings":";;;;;;;;;AA4CA,IAAMW,IAAY,aACZC,IAAS;AAqBf,SAASC,EAAO,GAA8B;CAC5C,IAAIC,IAAUC;CACd,SACE,IACEC,EAAK,0BAA0BF,CAAO,KACtCE,EAAK,eAAeF,CAAO,KAC3BE,EAAK,sBAAsBF,CAAO,GAElC,IAAUA,EAAQ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BAAgB,CAAC,CACjB,OACE,OACEJ,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAAOT,CAC3D,IAGC,EACR;AACH"}
|
|
1
|
+
{"version":3,"file":"env-vars-XvAeH6u5.js","names":["envVarsFile","ENV_MODULE","envVarEntry","ENV_DECL_CANDIDATES","languageFromPath","toDeleteEntry","ensureNamedImport","formatLikeSource","modifyOutcomeToFile","fs","path","VARIABLES","DEFINE","unwrap","current","expr","Node","exportedLocalName","decl","sf","spec","bindsName","name","ni","statement","nameNode","SyntaxKind","id","locateVariables","reExported","local","init","value","arg","object","propertyName","prop","inner","declaredNames","names","quoteOf","addEnvVars","located","quote","unique","dedupe","specs","entries","declared","missing","removeEnvVars","wanted","doomed","seen","newProject","Project","QuoteKind","findEnvDecl","rel","abs","root","readEnvVarNames","filePath","relative","REASONS","addHint","file","reason","removeHint","modifyEnvVars","existing","original","result","changed","modifyEnvVarsFiles","create","modify","unmodifyEnvVars","holdsNothing","unmodifyEnvVarsFiles","deleted","outcome"],"sources":["../../src/runtime/env-vars.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type Expression,\n type ObjectLiteralElementLike,\n type ObjectLiteralExpression,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { modifyOutcomeToFile } from \"./modify-file\";\nimport {\n ENV_DECL_CANDIDATES,\n envVarEntry,\n envVarsFile,\n ENV_MODULE,\n type EnvVarSpec,\n} from \"./env-vars-file\";\nimport { ensureNamedImport, formatLikeSource } from \"./ts-morph-helpers\";\n\nexport { ENV_DECL_CANDIDATES, envVarEntry, envVarsFile, type EnvVarSpec };\n\n/**\n * Declares environment variables in `src/env.ts`, where SvelteKit 3 reads\n * them: a variable it finds no declaration for is not exposed through\n * `$app/env/private` or `$app/env/public` at all.\n *\n * Three shapes of `variables` are edited:\n *\n * - `export const variables = defineEnvVars({ ... })`\n * - `const variables = defineEnvVars({ ... }); export { variables }`\n * - either of the above with a plain object literal in place of the call\n *\n * Entries are matched by property name, quoted or not, and an entry that is\n * already there is never touched: a project that declared `STRIPE_SECRET_KEY`\n * as required keeps it required.\n */\n\nconst VARIABLES = \"variables\";\nconst DEFINE = \"defineEnvVars\";\n\nexport type EnvVarsUnsupported =\n /** `variables` is exported some other way: a function, `export let variables;`, a re-export. */\n | \"not-variable\"\n /** `variables` is not an object literal or `defineEnvVars({ ... })`. */\n | \"not-object\"\n /** The object spreads another one in, which may already declare the names. */\n | \"spread\"\n /** A computed key (`[name]: ...`) whose name can't be read. */\n | \"computed-key\";\n\nexport type EnvVarsEditResult =\n | { status: \"changed\" | \"unchanged\" }\n | { status: \"unsupported\"; reason: EnvVarsUnsupported };\n\ntype Located =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"missing\" }\n | { kind: \"unsupported\"; reason: EnvVarsUnsupported };\n\nfunction unwrap(expr: Expression): Expression {\n let current = expr;\n for (;;) {\n if (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current)\n ) {\n current = current.getExpression();\n continue;\n }\n return current;\n }\n}\n\n/** The local name exported as `variables`: itself, or `x` in `export { x as variables }`. */\nfunction exportedLocalName(sf: SourceFile): string | null | \"re-export\" {\n for (const decl of sf.getExportDeclarations()) {\n for (const spec of decl.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== VARIABLES) continue;\n if (decl.getModuleSpecifier()) return \"re-export\";\n return spec.getName();\n }\n }\n return null;\n}\n\n/** A top-level import or destructuring pattern that binds `name`. */\nfunction bindsName(sf: SourceFile, name: string): boolean {\n const imported = sf\n .getImportDeclarations()\n .some(\n (decl) =>\n decl.getDefaultImport()?.getText() === name ||\n decl.getNamespaceImport()?.getText() === name ||\n decl\n .getNamedImports()\n .some(\n (ni) => (ni.getAliasNode()?.getText() ?? ni.getName()) === name,\n ),\n );\n if (imported) return true;\n return sf.getVariableStatements().some((statement) =>\n statement.getDeclarations().some((decl) => {\n const nameNode = decl.getNameNode();\n return (\n !Node.isIdentifier(nameNode) &&\n nameNode\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name &&\n (Node.isBindingElement(id.getParent()) ||\n Node.isShorthandPropertyAssignment(id.getParent())),\n )\n );\n }),\n );\n}\n\nfunction locateVariables(sf: SourceFile): Located {\n const reExported = exportedLocalName(sf);\n if (reExported === \"re-export\") {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const local = reExported ?? VARIABLES;\n\n const decl = sf.getVariableDeclaration(local);\n if (!decl) {\n // A function, class, import or destructured binding of that name,\n // exported or not, is not ours to replace.\n const taken =\n sf.getFunction(local) ?? sf.getClass(local) ?? sf.getEnum(local);\n if (taken || reExported || bindsName(sf, local)) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n return { kind: \"missing\" };\n }\n if (!reExported && !decl.isExported()) {\n // `const variables = ...` that SvelteKit can't see; exporting it is the\n // developer's call, not ours.\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n if (!Node.isIdentifier(decl.getNameNode())) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const init = decl.getInitializer();\n if (!init) return { kind: \"unsupported\", reason: \"not-variable\" };\n\n const value = unwrap(init);\n if (Node.isObjectLiteralExpression(value)) {\n return { kind: \"object\", object: value };\n }\n if (\n Node.isCallExpression(value) &&\n value.getExpression().getText() === DEFINE\n ) {\n const arg = value.getArguments()[0];\n const object = arg && unwrap(arg as Expression);\n if (object && Node.isObjectLiteralExpression(object)) {\n return { kind: \"object\", object };\n }\n }\n return { kind: \"unsupported\", reason: \"not-object\" };\n}\n\n/** A property's name as SvelteKit sees it, `null` for a spread or computed key. */\nfunction propertyName(prop: ObjectLiteralElementLike): string | null {\n if (Node.isSpreadAssignment(prop)) return null;\n const nameNode = prop.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) {\n const inner = nameNode.getExpression();\n return Node.isStringLiteral(inner) ||\n Node.isNoSubstitutionTemplateLiteral(inner)\n ? inner.getLiteralText()\n : null;\n }\n if (\n Node.isStringLiteral(nameNode) ||\n Node.isNoSubstitutionTemplateLiteral(nameNode)\n ) {\n return nameNode.getLiteralText();\n }\n return nameNode.getText();\n}\n\nfunction declaredNames(\n object: ObjectLiteralExpression,\n): Set<string> | EnvVarsUnsupported {\n const names = new Set<string>();\n for (const prop of object.getProperties()) {\n if (Node.isSpreadAssignment(prop)) return \"spread\";\n const name = propertyName(prop);\n if (name === null) return \"computed-key\";\n names.add(name);\n }\n return names;\n}\n\n/** The quote the file already writes its strings with. */\nfunction quoteOf(sf: SourceFile): \"'\" | '\"' {\n const first = sf.getFirstDescendantByKind(SyntaxKind.StringLiteral);\n return first?.getText().startsWith('\"') ? '\"' : \"'\";\n}\n\n/**\n * Add a declaration for every spec `sf` doesn't declare yet. Creates\n * `export const variables = defineEnvVars({ ... })`, and its import, when the\n * file has no `variables` at all. Neither formats nor saves.\n */\nexport function addEnvVars(\n sf: SourceFile,\n specs: EnvVarSpec[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const quote = quoteOf(sf);\n\n if (located.kind === \"missing\") {\n const unique = dedupe(specs);\n if (unique.length === 0) return { status: \"unchanged\" };\n ensureNamedImport(sf, ENV_MODULE, DEFINE);\n const entries = unique\n .map((spec) => `\\t${envVarEntry(spec, { quote })}`)\n .join(\",\\n\");\n sf.addStatements(\n `\\nexport const ${VARIABLES} = ${DEFINE}({\\n${entries}\\n});`,\n );\n return { status: \"changed\" };\n }\n\n const declared = declaredNames(located.object);\n if (typeof declared === \"string\") {\n return { status: \"unsupported\", reason: declared };\n }\n const missing = dedupe(specs).filter((spec) => !declared.has(spec.name));\n if (missing.length === 0) return { status: \"unchanged\" };\n for (const spec of missing) {\n located.object.addProperty(envVarEntry(spec, { quote }));\n }\n return { status: \"changed\" };\n}\n\n/**\n * Remove the declarations of `names` from `sf`. A file with no `variables`,\n * or none of the names, is unchanged. Neither formats nor saves.\n */\nexport function removeEnvVars(\n sf: SourceFile,\n names: string[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"missing\") return { status: \"unchanged\" };\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const wanted = new Set(names);\n const doomed = located.object.getProperties().filter((prop) => {\n const name = propertyName(prop);\n return name !== null && wanted.has(name);\n });\n if (doomed.length === 0) return { status: \"unchanged\" };\n for (const prop of doomed.reverse()) prop.remove();\n if (located.object.getProperties().length === 0) {\n located.object.replaceWithText(\"{}\");\n }\n return { status: \"changed\" };\n}\n\nfunction dedupe(specs: EnvVarSpec[]): EnvVarSpec[] {\n const seen = new Set<string>();\n return specs.filter((spec) => {\n if (seen.has(spec.name)) return false;\n seen.add(spec.name);\n return true;\n });\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/** The project's declaration file: `src/env.ts` or `src/env.js`, if either exists. */\nexport function findEnvDecl(root: string): string | null {\n for (const rel of ENV_DECL_CANDIDATES) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\n/**\n * The names `src/env.ts` (or `src/env.js`) declares. Spreads and computed\n * keys it can't read are skipped rather than failing the whole read, so a\n * declaration file this module couldn't edit still reports what it can. No\n * file, or no `variables` this can read, is an empty set.\n */\nexport function readEnvVarNames(root: string): Set<string> {\n const filePath = findEnvDecl(root);\n if (!filePath) return new Set();\n\n const sf = newProject().addSourceFileAtPath(filePath);\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return new Set();\n\n const names = new Set<string>();\n for (const prop of located.object.getProperties()) {\n const name = propertyName(prop);\n if (name !== null) names.add(name);\n }\n return names;\n}\n\nfunction relative(root: string, filePath: string): string {\n return path.relative(root, filePath).split(path.sep).join(\"/\");\n}\n\nconst REASONS: Record<EnvVarsUnsupported, string> = {\n \"not-variable\": \"its `variables` export is not a variable this can edit\",\n \"not-object\":\n \"`variables` is not an object literal or a `defineEnvVars({ ... })` call\",\n spread: \"`variables` spreads in another object\",\n \"computed-key\": \"`variables` has a computed key\",\n};\n\nfunction addHint(\n file: string,\n reason: EnvVarsUnsupported,\n specs: EnvVarSpec[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n \"Declare these in the object passed to defineEnvVars() (or exported as `variables`), skipping any already there:\",\n \"\",\n ...dedupe(specs).map((spec) => `${envVarEntry(spec)},`),\n ].join(\"\\n\");\n}\n\nfunction removeHint(\n file: string,\n reason: EnvVarsUnsupported,\n names: string[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n `Remove these declarations from \\`variables\\` by hand: ${names.join(\", \")}`,\n ].join(\"\\n\");\n}\n\nexport interface ModifyEnvVarsResult {\n /** `src/env.ts` to create, when the project has no declaration file. */\n create?: File;\n /** The existing declaration file, already saved when `outcome` changed it. */\n modify?: { filePath: string; outcome: ModifyOutcome };\n}\n\n/**\n * Declare `specs` in the project's `src/env.ts` (or `src/env.js`). Existing\n * entries are never touched.\n *\n * - No declaration file: `create` holds a new `src/env.ts` (always `.ts`,\n * written like the CLI templates' one); nothing is written yet.\n * - An existing file is edited and saved in place, and `modify` reports it\n * like every other runtime modifier: turn it into a File with\n * `modifyOutcomeToFile` (or use {@link modifyEnvVarsFiles}).\n * - A file whose `variables` can't be edited safely is left alone, and the\n * `failed` outcome's message lists the exact entries to paste.\n */\nexport function modifyEnvVars(\n root: string,\n specs: EnvVarSpec[],\n): ModifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n if (dedupe(specs).length === 0) return {};\n const filePath = path.join(root, ENV_DECL_CANDIDATES[0]);\n return {\n create: {\n path: filePath,\n language: languageFromPath(filePath),\n content: envVarsFile(specs),\n status: \"success\",\n },\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = addEnvVars(sf, specs);\n if (result.status === \"unsupported\") {\n return {\n modify: {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: addHint(relative(root, existing), result.reason, specs),\n },\n },\n };\n }\n if (result.status === \"unchanged\") {\n return {\n modify: {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n },\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n modify: { filePath: existing, outcome: { status: \"success\", changed } },\n };\n}\n\n/** {@link modifyEnvVars} as the File entries a pattern's Result carries. */\nexport function modifyEnvVarsFiles(\n root: string,\n specs: EnvVarSpec[],\n): { create: File | null; modify: File | null } {\n const { create, modify } = modifyEnvVars(root, specs);\n return {\n create: create ?? null,\n modify: modify\n ? modifyOutcomeToFile(modify.filePath, modify.outcome)\n : null,\n };\n}\n\nexport interface UnmodifyEnvVarsResult {\n filePath: string;\n outcome: ModifyOutcome;\n /**\n * The revert left nothing but the `defineEnvVars` import and an empty\n * `variables`. The emptied file has been saved; the caller reports it as a\n * delete (`toDeleteEntry(filePath)`) instead of a modify, as\n * {@link unmodifyEnvVarsFiles} does.\n */\n deleted: boolean;\n}\n\n/**\n * Remove the declarations of `names` from `src/env.ts` (or `.js`). A project\n * without the file, or without the names, is a no-op success.\n */\nexport function unmodifyEnvVars(\n root: string,\n names: string[],\n): UnmodifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n return {\n filePath: path.join(root, ENV_DECL_CANDIDATES[0]),\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = removeEnvVars(sf, names);\n if (result.status === \"unsupported\") {\n return {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: removeHint(relative(root, existing), result.reason, names),\n },\n deleted: false,\n };\n }\n if (result.status === \"unchanged\") {\n return {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n filePath: existing,\n outcome: { status: \"success\", changed },\n deleted: changed && holdsNothing(sf),\n };\n}\n\n/** {@link unmodifyEnvVars} as the File entries a pattern's Result carries. */\nexport function unmodifyEnvVarsFiles(\n root: string,\n names: string[],\n): { modify: File | null; delete: File | null } {\n const { filePath, outcome, deleted } = unmodifyEnvVars(root, names);\n if (deleted) return { modify: null, delete: toDeleteEntry(filePath) };\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * Only the `defineEnvVars` import, an empty `variables` and its\n * `export { variables }` are left. Comments don't count.\n */\nfunction holdsNothing(sf: SourceFile): boolean {\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return false;\n if (located.object.getProperties().length > 0) return false;\n const decl = located.object.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n return sf.getStatements().every((statement: Statement) => {\n if (statement === decl) return true;\n if (Node.isEmptyStatement(statement)) return true;\n if (Node.isImportDeclaration(statement)) {\n return (\n statement.getModuleSpecifierValue() === ENV_MODULE &&\n !statement.getDefaultImport() &&\n !statement.getNamespaceImport() &&\n statement.getNamedImports().every((ni) => ni.getName() === DEFINE)\n );\n }\n if (Node.isExportDeclaration(statement)) {\n return (\n !statement.getModuleSpecifier() &&\n statement\n .getNamedExports()\n .every(\n (spec) =>\n (spec.getAliasNode()?.getText() ?? spec.getName()) === VARIABLES,\n )\n );\n }\n return false;\n });\n}\n"],"mappings":";;;;;;;;;AA4CA,IAAMW,IAAY,aACZC,IAAS;AAqBf,SAASC,EAAO,GAA8B;CAC5C,IAAIC,IAAUC;CACd,SACE,IACEC,EAAK,0BAA0BF,CAAO,KACtCE,EAAK,eAAeF,CAAO,KAC3BE,EAAK,sBAAsB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AAU,mBAAmB,KAC9BA,EACG,gBAAgB,CAAC,CACjB,OACE,OACEJ,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAAOT,CAC3D,IAGC,EACR;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as e } from "./util-BLYliuUK.js";
|
|
2
2
|
import { t } from "./providers-CL9kQ4hp.js";
|
|
3
|
-
import { a as n, d as r, f as i, g as a, h as o, i as s, l as c, m as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./generate-
|
|
4
|
-
import { n as g } from "./shared-
|
|
3
|
+
import { a as n, d as r, f as i, g as a, h as o, i as s, l as c, m as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./generate-DjuhSibA.js";
|
|
4
|
+
import { n as g } from "./shared-CAjLx_8Z.js";
|
|
5
5
|
//#region src/patterns/disable/ai/generate.ts
|
|
6
6
|
var _ = /* #__PURE__ */ Object.assign({
|
|
7
7
|
"../../enable/ai/creates/src/routes/(public)/ai/+page.svelte": a,
|
|
@@ -55,4 +55,4 @@ async function T(e) {
|
|
|
55
55
|
//#endregion
|
|
56
56
|
export { T as i, w as n, b as r, C as t };
|
|
57
57
|
|
|
58
|
-
//# sourceMappingURL=generate-
|
|
58
|
+
//# sourceMappingURL=generate-BtWZCvuO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-
|
|
1
|
+
{"version":3,"file":"generate-BtWZCvuO.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","appRelativePath","PROVIDER_PACKAGES","ai_default","server_test_default$1","_page_default","_server_default","PROVIDERS","ai_default$2","server_test_default","demoDir","_server_default$1","PACKAGES","envEditsFor","DEMO_DIR","ai_default$1","toDeleteEntry","createsRaw","createsAppModeRaw","providersRaw","demoDirs","dirs","options","atDemoDir","path","dir","aiPaths","paths","allProviderPaths","raw","prefix","key","allEnvEdits","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/ai/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { appRelativePath } from \"../../../core/util\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport {\n DEMO_DIR,\n demoDir,\n envEditsFor,\n PACKAGES,\n PROVIDER_PACKAGES,\n PROVIDERS,\n} from \"../../enable/ai/generate\";\n\nconst createsRaw = import.meta.glob<string>(\"../../enable/ai/creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst createsAppModeRaw = import.meta.glob<string>(\n \"../../enable/ai/creates-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nconst providersRaw = import.meta.glob<string>(\"../../enable/ai/providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\ntype DemoOptions = Pick<Options, \"features\" | \"routeGroups\">;\n\n/**\n * Where enable-ai may have put the demo page in this project: the group it\n * picks with auth on and with it off. Auth enabled after AI leaves the page\n * in the public group, so both are candidates.\n */\nexport function demoDirs(options: DemoOptions): string[] {\n const dirs = [false, true].map((auth) =>\n demoDir({ ...options, features: { ...options.features, auth } }),\n );\n return [...new Set(dirs)];\n}\n\n/** A path enable-ai writes, with the stored demo directory moved to `dir`. */\nfunction atDemoDir(path: string, dir: string): string {\n return path.startsWith(DEMO_DIR)\n ? `${dir}/${path.slice(DEMO_DIR.length)}`\n : path;\n}\n\n/**\n * Every path enable-ai writes for this project: the model module, the\n * endpoint and its test, and the demo page in its current default group.\n * `generate.runtime.ts` adds the page in the other group when it exists.\n */\nexport function aiPaths(options: DemoOptions): string[] {\n const dir = demoDir(options);\n const paths = new Set<string>(allProviderPaths(providersRaw));\n for (const [raw, prefix] of [\n [createsRaw, \"../../enable/ai/creates/\"],\n [createsAppModeRaw, \"../../enable/ai/creates-app-mode/\"],\n ] as const) {\n for (const key of Object.keys(raw)) {\n paths.add(atDemoDir(appRelativePath(key, prefix), dir));\n }\n }\n return [...paths].sort();\n}\n\n/**\n * The `.env` lines every provider writes. Which provider was chosen is not\n * recorded, so all are removed; keys that are not there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(options: Options) {\n return {\n creates: [],\n modifies: [],\n // Missing ones are skipped, and emptied directories (api/chat, ai) go too.\n deletes: aiPaths(options).map(toDeleteEntry),\n components: [],\n packages: [],\n // zod and the shadcn button/textarea stay: other code uses them.\n uninstalls: [...PACKAGES, ...Object.values(PROVIDER_PACKAGES).flat()],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;AAcA,IAAMwB,IAAa,uBAAA,OAAA;CAAA,+DAAAxB;CAAA,0DAAAC;CAAA,8DAAAC;AAIlB,CAAA,GAEKuB,IAAoB,uBAAA,OAAA;CAAA,mEAAAtB;CAAA,uEAAAC;AAG1B,CAAA,GAEMsB,IAAe,uBAAA,OAAA;CAAA,4DAAArB;CAAA,0DAAAC;CAAA,yDAAAC;AAIpB,CAAA;AASD,SAAgBoB,EAAS,GAAgC;CACvD,IAAMC,IAAO,CAAC,IAAO,EAAI,CAAC,CAAC,KAAK,MAC9BX,EAAQ;EAAE,GAAGY;EAAS,UAAU;GAAE,GAAGA,EAAQ;GAAU;EAAK;CAAE,CAAC,CACjE;CACA,OAAO,CAAC,GAAG,IAAI,IAAID,CAAI,CAAC;AAC1B;AAGA,SAASE,EAAU,GAAc,GAAqB;CACpD,OAAOC,EAAK,WAAA,yBAAmB,IAC3B,GAAGC,EAAI,GAAGD,EAAK,MAAMV,EAAS,MAAM,MACpCU;AACN;AAOA,SAAgBE,EAAQ,GAAgC;CACtD,IAAMD,IAAMf,EAAQY,CAAO,GACrBK,IAAQ,IAAI,IAAYC,EAAiBT,CAAY,CAAC;CAC5D,KAAK,IAAM,CAACU,GAAKC,MAAW,CAC1B,CAACb,GAAY,0BAA0B,GACvC,CAACC,GAAmB,mCAAmC,CACzD,GACE,KAAK,IAAMa,KAAO,OAAO,KAAKF,CAAG,GAC/B,EAAM,IAAIN,EAAUtB,EAAgB8B,GAAKD,CAAM,GAAGL,CAAG,CAAC;CAG1D,OAAO,CAAC,GAAGE,CAAK,CAAC,CAAC,KAAK;AACzB;AAMA,SAAgBK,IAAyB;CACvC,OAAOzB,EAAU,SAAS,MAAaM,EAAYoB,CAAQ,CAAC;AAC9D;AAGA,SAAgBC,IAAwB;CACtC,OAAO3B,EAAU,SAAS,OACvB0B,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAaE,EAAS,GAAG,CACrD;AACF;AAEA,eAAsBC,EAAS,GAAkB;CAC/C,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAEX,SAASV,EAAQJ,CAAO,CAAC,CAAC,IAAIN,CAAa;EAC3C,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,GAAGJ,GAAU,GAAG,OAAO,OAAOV,CAAiB,CAAC,CAAC,KAAK,CAAC;EACpE,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as e, r as t } from "./util-BLYliuUK.js";
|
|
2
2
|
import { t as n } from "./providers-CL9kQ4hp.js";
|
|
3
|
-
import { A as r, B as i, C as a, D as o, E as s, F as c, G as l, H as u, I as d, K as f, L as p, M as m, N as h, O as g, P as _, R as v, S as y, T as b, U as x, V as S, W as C, _ as w, b as T, c as E, d as D, f as ee, g as O, h as k, i as A, j, k as M, l as N, m as P, n as F, p as I, s as L, t as R, u as z, v as B, w as V, x as H, y as U, z as W } from "./currency.server-
|
|
3
|
+
import { A as r, B as i, C as a, D as o, E as s, F as c, G as l, H as u, I as d, K as f, L as p, M as m, N as h, O as g, P as _, R as v, S as y, T as b, U as x, V as S, W as C, _ as w, b as T, c as E, d as D, f as ee, g as O, h as k, i as A, j, k as M, l as N, m as P, n as F, p as I, s as L, t as R, u as z, v as B, w as V, x as H, y as U, z as W } from "./currency.server-DygAf6a1.js";
|
|
4
4
|
import { t as G } from "./stripe-customer-B3tP8gtD.js";
|
|
5
5
|
import { n as K, t as q } from "./_page-DoPdZgZv.js";
|
|
6
6
|
//#region src/patterns/disable/payments/generate.ts
|
|
@@ -83,4 +83,4 @@ async function $(r) {
|
|
|
83
83
|
//#endregion
|
|
84
84
|
export { Q as n, $ as t };
|
|
85
85
|
|
|
86
|
-
//# sourceMappingURL=generate-
|
|
86
|
+
//# sourceMappingURL=generate-Cbg-Z3sA.js.map
|