@stacksjs/stx 0.2.286 → 0.2.288
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/dist/builtins/index.d.ts +4 -3
- package/dist/builtins/index.js +11 -11
- package/dist/{chunk-3bv8h4r6.js → chunk-02af607x.js} +1 -1
- package/dist/chunk-06706a9a.js +2 -0
- package/dist/chunk-0896td83.js +2 -0
- package/dist/chunk-08yja60e.js +2 -0
- package/dist/{chunk-e2w23g2r.js → chunk-13tawjw8.js} +10 -10
- package/dist/{chunk-zn5jgmqw.js → chunk-1e83cj7k.js} +1 -1
- package/dist/chunk-1g6pvs7k.js +11 -0
- package/dist/chunk-1gvebxh4.js +2 -0
- package/dist/{chunk-jbfpc4z7.js → chunk-1t9g3mhg.js} +2 -2
- package/dist/{chunk-0f1kz0x2.js → chunk-2e6xafcm.js} +1 -1
- package/dist/chunk-2rfxs7zm.js +2 -0
- package/dist/{chunk-sskbegsz.js → chunk-2vza9m2x.js} +1 -1
- package/dist/{chunk-pbk8jxe2.js → chunk-2wtn443n.js} +1 -1
- package/dist/{chunk-6cye5m9f.js → chunk-34qkshwh.js} +2 -2
- package/dist/{chunk-2g9jwgs7.js → chunk-3br3pt6k.js} +1 -1
- package/dist/{chunk-kmhr1z0m.js → chunk-3p0n9ryv.js} +1 -1
- package/dist/chunk-437n7hyx.js +2 -0
- package/dist/{chunk-ayrjwkyw.js → chunk-461br5nn.js} +1 -1
- package/dist/chunk-4tr92e0v.js +2 -0
- package/dist/{chunk-t6nseeb9.js → chunk-4vpsvh6x.js} +1 -1
- package/dist/{chunk-nh21517m.js → chunk-5j9tvhpq.js} +2 -2
- package/dist/{chunk-mb518a4n.js → chunk-5yp3vt00.js} +1 -1
- package/dist/{chunk-e4hhz9j3.js → chunk-5zcg61j9.js} +2 -2
- package/dist/{chunk-snknv47x.js → chunk-6085vha7.js} +1 -1
- package/dist/{chunk-9th1wd1d.js → chunk-72c7gyqc.js} +3 -3
- package/dist/chunk-811cxzn4.js +2 -0
- package/dist/{chunk-bz2gytfs.js → chunk-8883pgj8.js} +1 -1
- package/dist/{chunk-vqxmxgaj.js → chunk-8bxtvsgm.js} +1 -1
- package/dist/{chunk-a63y3aa0.js → chunk-8daczchh.js} +1 -1
- package/dist/chunk-91ffbzmh.js +2 -0
- package/dist/chunk-96cqevhm.js +2 -0
- package/dist/chunk-978faewt.js +2 -0
- package/dist/{chunk-g3fy0tw8.js → chunk-9veqmqb6.js} +154 -48
- package/dist/{chunk-7q9mwh4v.js → chunk-a668m28h.js} +1 -1
- package/dist/{chunk-xg57nax9.js → chunk-a9fxxwrv.js} +2 -2
- package/dist/chunk-adkjxvy6.js +2 -0
- package/dist/{chunk-a2qghr2x.js → chunk-agx0620p.js} +1 -1
- package/dist/chunk-ak06mywr.js +2 -0
- package/dist/chunk-ayaz0wcj.js +2 -0
- package/dist/{chunk-ah4e6e09.js → chunk-bphx7ngb.js} +2 -2
- package/dist/chunk-bw48gj8j.js +2 -0
- package/dist/{chunk-7rxtra1g.js → chunk-byq2xpgb.js} +1 -1
- package/dist/chunk-bzsjhyet.js +2 -0
- package/dist/{chunk-rhs51nmz.js → chunk-ch31zddx.js} +2 -2
- package/dist/chunk-cqzqfm7m.js +2 -0
- package/dist/{chunk-9zndrzb3.js → chunk-d0f60jrg.js} +2 -2
- package/dist/{chunk-c0an64km.js → chunk-dcxtrqfy.js} +1 -1
- package/dist/{chunk-bf8wf3r2.js → chunk-drbbt69f.js} +35 -10
- package/dist/chunk-e0aybavh.js +2 -0
- package/dist/chunk-e63a220e.js +28 -0
- package/dist/chunk-e67w1bge.js +2 -0
- package/dist/chunk-e7kd0ny8.js +2 -0
- package/dist/{chunk-y8n174xq.js → chunk-ee2tfpec.js} +2 -2
- package/dist/{chunk-9n0gvfrg.js → chunk-efr3ejqt.js} +1 -1
- package/dist/chunk-evfct6hb.js +2 -0
- package/dist/{chunk-kzyhvrp8.js → chunk-favq46aa.js} +1 -1
- package/dist/{chunk-0fgcnv6y.js → chunk-fcfphfpw.js} +2 -2
- package/dist/{chunk-w95sp0k9.js → chunk-fed3xsp9.js} +2 -2
- package/dist/{chunk-e7jfpyqy.js → chunk-ffmtamm2.js} +1 -1
- package/dist/{chunk-39f40yc4.js → chunk-fv923f7g.js} +1 -1
- package/dist/{chunk-jr3jp3ev.js → chunk-fvh9ca47.js} +1 -1
- package/dist/chunk-fxk9j0rm.js +2 -0
- package/dist/{chunk-fskfes13.js → chunk-gy933rct.js} +1 -1
- package/dist/{chunk-f3hfk78e.js → chunk-h61qt916.js} +1 -1
- package/dist/{chunk-c6fw33zh.js → chunk-h7v70dbp.js} +2 -2
- package/dist/{chunk-bz820epz.js → chunk-hmf9z4jx.js} +1 -1
- package/dist/{chunk-j9g11dzx.js → chunk-hqh7x9h5.js} +2 -2
- package/dist/{chunk-hs0387tm.js → chunk-hv5v6vc2.js} +2 -2
- package/dist/{chunk-xttsqmkm.js → chunk-jem20v5k.js} +1 -1
- package/dist/{chunk-t1k5dpbr.js → chunk-jj6yp7gm.js} +1 -1
- package/dist/{chunk-90qr4f9m.js → chunk-jv91rkhx.js} +1 -1
- package/dist/{chunk-qbeffw17.js → chunk-jyc9eha6.js} +1 -1
- package/dist/{chunk-w3ycm4na.js → chunk-k0y7ta0d.js} +1 -1
- package/dist/chunk-k4jt9t4p.js +2 -0
- package/dist/{chunk-9y0g8kzt.js → chunk-k70fgb2f.js} +1 -1
- package/dist/{chunk-74cv4ta1.js → chunk-k78gvm0g.js} +1 -1
- package/dist/{chunk-jn6m8zf7.js → chunk-kb5j08tq.js} +1 -1
- package/dist/{chunk-a54n1r1q.js → chunk-kf8t2wq7.js} +1 -1
- package/dist/chunk-kfy1jh6p.js +2 -0
- package/dist/chunk-kws4rewx.js +17 -0
- package/dist/{chunk-s67mgegv.js → chunk-mc58fhgm.js} +1 -1
- package/dist/{chunk-n3ggrhb3.js → chunk-mjpqz66q.js} +1 -1
- package/dist/{chunk-mjkfc2v6.js → chunk-mmnqd035.js} +1 -1
- package/dist/{chunk-54st8g2j.js → chunk-mywp77gt.js} +1 -1
- package/dist/{chunk-p396xrew.js → chunk-n0j85038.js} +1 -1
- package/dist/{chunk-gjemavhx.js → chunk-n5y9gh1q.js} +1 -1
- package/dist/{chunk-qd8ggjdx.js → chunk-n9kk3jz1.js} +1 -1
- package/dist/{chunk-49kk0s96.js → chunk-nmkra8q5.js} +2 -2
- package/dist/{chunk-s2284nbk.js → chunk-np5dc1q1.js} +1 -1
- package/dist/chunk-nygtwffe.js +5 -0
- package/dist/{chunk-y6kw0wb7.js → chunk-p0zq5ckb.js} +1 -1
- package/dist/chunk-pb16azfa.js +4 -0
- package/dist/{chunk-nx5qkm8k.js → chunk-ps20v1ah.js} +1 -1
- package/dist/chunk-pv9apyrr.js +2 -0
- package/dist/chunk-qj2s3r1w.js +3756 -0
- package/dist/chunk-qjkzpd68.js +11 -0
- package/dist/chunk-qww39be9.js +2 -0
- package/dist/chunk-r90w3x6h.js +2 -0
- package/dist/chunk-rb87b7kr.js +2 -0
- package/dist/{chunk-an2539bs.js → chunk-rjqfa3g8.js} +2 -2
- package/dist/{chunk-2q630fj4.js → chunk-sag55qv7.js} +1 -1
- package/dist/chunk-srcbkg7g.js +2 -0
- package/dist/chunk-sxderfaa.js +12 -0
- package/dist/{chunk-ysnk7x79.js → chunk-t5c7rk0h.js} +1 -1
- package/dist/chunk-v2z3creg.js +2 -0
- package/dist/chunk-vtjfv7kg.js +2 -0
- package/dist/{chunk-5aq35j2e.js → chunk-vvqe2gaz.js} +2 -2
- package/dist/{chunk-s7pc68jf.js → chunk-vwzqg4fh.js} +2 -2
- package/dist/{chunk-7p9ns60j.js → chunk-vxxxczmn.js} +1 -1
- package/dist/chunk-vzzkhjw7.js +2 -0
- package/dist/{chunk-wcm80anz.js → chunk-wvq1g6gr.js} +1 -1
- package/dist/{chunk-y7m2dpd3.js → chunk-wyxw61az.js} +1 -1
- package/dist/{chunk-kdrpx9ft.js → chunk-xpct12p7.js} +1 -1
- package/dist/chunk-xvndd7h6.js +2 -0
- package/dist/{chunk-d0c3v7ax.js → chunk-y5jjrnfa.js} +1 -1
- package/dist/{chunk-vbdca0k1.js → chunk-ym4ggcpy.js} +1 -1
- package/dist/{chunk-q68xmak4.js → chunk-ymc99r5x.js} +18 -18
- package/dist/{chunk-refwkt87.js → chunk-ynt7y2n5.js} +1 -1
- package/dist/chunk-z6azwfb4.js +2 -0
- package/dist/chunk-zfnabevq.js +2 -0
- package/dist/{chunk-cvnh7dma.js → chunk-zqwmy0av.js} +1 -1
- package/dist/{chunk-phhzfeh9.js → chunk-zvw2qgwt.js} +1 -1
- package/dist/cli.js +14 -14
- package/dist/client-module-registry.d.ts +36 -0
- package/dist/client-module-registry.js +55 -0
- package/dist/client-script-bundler.d.ts +39 -0
- package/dist/client-script-bundler.js +89 -12
- package/dist/client-script.js +15 -8
- package/dist/component-client-factories.js +10 -5
- package/dist/component-processing.d.ts +13 -0
- package/dist/component-processing.js +37 -1
- package/dist/component-renderer.js +34 -15
- package/dist/conditionals.js +14 -3
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/database.js +1 -1
- package/dist/document-shell.d.ts +1 -34
- package/dist/document-shell.js +19 -11
- package/dist/html-masking.d.ts +65 -9
- package/dist/html-masking.js +103 -15
- package/dist/misc-directives.d.ts +1 -1
- package/dist/misc-directives.js +48 -13
- package/dist/process.js +38 -7
- package/dist/pwa.js +2 -2
- package/dist/reactive-bindings.js +2 -0
- package/dist/runtime-globals.d.ts +7 -20
- package/dist/runtime-globals.js +28 -3
- package/dist/safe-evaluator.d.ts +15 -0
- package/dist/safe-evaluator.js +16 -12
- package/dist/server-bindings.js +21 -5
- package/dist/signal-processing.d.ts +17 -7
- package/dist/signal-processing.js +116 -46
- package/dist/signals-api.js +5 -2
- package/dist/signals.js +153 -47
- package/dist/ssg.js +2 -2
- package/dist/store-loader.js +1 -1
- package/dist/strip-literals.d.ts +20 -0
- package/dist/strip-literals.js +16 -0
- package/dist/utils.js +24 -7
- package/dist/variable-extractor.js +17 -47
- package/dist/visual-testing.js +1 -1
- package/package.json +5 -5
- package/dist/chunk-3ehv1by2.js +0 -2
- package/dist/chunk-4cqgbcy7.js +0 -3756
- package/dist/chunk-52mh63sp.js +0 -11
- package/dist/chunk-56ywtaff.js +0 -2
- package/dist/chunk-61sj52qh.js +0 -2
- package/dist/chunk-7ej1d910.js +0 -2
- package/dist/chunk-829pcte9.js +0 -2
- package/dist/chunk-8emkx9ja.js +0 -2
- package/dist/chunk-ajbfeey7.js +0 -2
- package/dist/chunk-areethga.js +0 -2
- package/dist/chunk-b29wbjs5.js +0 -2
- package/dist/chunk-b7tjq91c.js +0 -2
- package/dist/chunk-ba6tthsm.js +0 -2
- package/dist/chunk-e4akvata.js +0 -2
- package/dist/chunk-f4k2a7vs.js +0 -2
- package/dist/chunk-f80wwn5x.js +0 -2
- package/dist/chunk-fjkstnz3.js +0 -2
- package/dist/chunk-j03bare5.js +0 -2
- package/dist/chunk-jg0axas8.js +0 -2
- package/dist/chunk-jrk8rhwt.js +0 -28
- package/dist/chunk-kawk5ve9.js +0 -2
- package/dist/chunk-m3yaa0v5.js +0 -15
- package/dist/chunk-m7xnzt2t.js +0 -2
- package/dist/chunk-mkn6qqc7.js +0 -2
- package/dist/chunk-n3jyv9z6.js +0 -2
- package/dist/chunk-nvgxjvnb.js +0 -2
- package/dist/chunk-qk8tbcwk.js +0 -2
- package/dist/chunk-qp97dx7x.js +0 -2
- package/dist/chunk-qsr3bqav.js +0 -12
- package/dist/chunk-vb10qph4.js +0 -2
- package/dist/chunk-vrvehb01.js +0 -2
- package/dist/chunk-vy8v5xdb.js +0 -2
- package/dist/chunk-w0sqz3cb.js +0 -11
- package/dist/chunk-w8smn72c.js +0 -2
- package/dist/chunk-wxk2pbrh.js +0 -2
- package/dist/chunk-x1nw1p8z.js +0 -2
- package/dist/chunk-xz55q3gr.js +0 -2
- package/dist/chunk-yq1d9hb3.js +0 -2
- package/dist/chunk-ytgnzeeb.js +0 -2
- package/dist/chunk-zfr4d08r.js +0 -2
|
@@ -5,7 +5,8 @@ import { stateDir } from "./state-dir.js";
|
|
|
5
5
|
import { describeBuildFailure, formatBuildFailure } from "./build-message.js";
|
|
6
6
|
import { config } from "./config.js";
|
|
7
7
|
import { depsUnchanged, renderMemo } from "./render-memo.js";
|
|
8
|
-
|
|
8
|
+
import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
|
|
9
|
+
const BUNDLE_CACHE_VERSION = 6, BUNDLE_CACHE_METADATA_VERSION = 1, bundleInputs = new Map, CACHE_ENTRY_LIMIT = 600, SWEEP_EVERY = 100, writesSinceSweep = new Map;
|
|
9
10
|
async function pruneBundleCache(cacheDir) {
|
|
10
11
|
const since = writesSinceSweep.get(cacheDir) ?? 0;
|
|
11
12
|
if (since > 0 && since < SWEEP_EVERY) {
|
|
@@ -100,6 +101,50 @@ export function hasUserImports(code) {
|
|
|
100
101
|
}
|
|
101
102
|
return !1;
|
|
102
103
|
}
|
|
104
|
+
export const MODULE_SPECIFIER_PREFIX = "stx-module:";
|
|
105
|
+
const REGISTRY_MODULE_EXTENSION = /\.(?:[cm]?[jt]sx?|json)$/i;
|
|
106
|
+
export function registryIdForPath(projectRoot, resolved) {
|
|
107
|
+
return path.relative(projectRoot, resolved).split(path.sep).join("/");
|
|
108
|
+
}
|
|
109
|
+
export function rewriteRegistryImports(code, reads) {
|
|
110
|
+
let counter = 0;
|
|
111
|
+
const moduleVar = (id) => {
|
|
112
|
+
const name = `__stxMod${counter++}`, key = JSON.stringify(id);
|
|
113
|
+
reads.push(`var ${name} = globalThis.__stxModules && globalThis.__stxModules[${key}];`, `if (${name} === undefined) throw new Error("[stx] module " + ${JSON.stringify(key)} + " is not registered on this page (#1957)");`);
|
|
114
|
+
return name;
|
|
115
|
+
}, bindNamed = (list, mod) => {
|
|
116
|
+
for (const raw of list.split(",")) {
|
|
117
|
+
const part = raw.trim();
|
|
118
|
+
if (!part)
|
|
119
|
+
continue;
|
|
120
|
+
const match = part.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);
|
|
121
|
+
if (!match)
|
|
122
|
+
continue;
|
|
123
|
+
const imported = match[1].startsWith('"') ? JSON.parse(match[1]) : match[1], local = match[2] ?? imported;
|
|
124
|
+
reads.push(`var ${local} = ${mod}[${JSON.stringify(imported)}];`);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
code = code.replace(/^[ \t]*import\s+([^;"']*?)\s+from\s+["'](stx-module:[^"']+)["'];?[ \t]*$/gm, (_all, rawClause, spec) => {
|
|
128
|
+
const id = spec.slice(MODULE_SPECIFIER_PREFIX.length), mod = moduleVar(id);
|
|
129
|
+
let clause = rawClause.trim();
|
|
130
|
+
const leadingDefault = clause.match(/^([\w$]+)\s*(?:,\s*|$)/);
|
|
131
|
+
if (leadingDefault && !clause.startsWith("{") && !clause.startsWith("*")) {
|
|
132
|
+
reads.push(`var ${leadingDefault[1]} = ${mod}.default;`);
|
|
133
|
+
clause = clause.slice(leadingDefault[0].length).trim();
|
|
134
|
+
}
|
|
135
|
+
const namespace = clause.match(/^\*\s*as\s+([\w$]+)$/);
|
|
136
|
+
if (namespace)
|
|
137
|
+
reads.push(`var ${namespace[1]} = ${mod};`);
|
|
138
|
+
else if (clause.startsWith("{"))
|
|
139
|
+
bindNamed(clause.replace(/^\{|\}$/g, ""), mod);
|
|
140
|
+
return "";
|
|
141
|
+
});
|
|
142
|
+
code = code.replace(/^[ \t]*import\s+["'](stx-module:[^"']+)["'];?[ \t]*$/gm, (_all, spec) => {
|
|
143
|
+
moduleVar(spec.slice(MODULE_SPECIFIER_PREFIX.length));
|
|
144
|
+
return "";
|
|
145
|
+
});
|
|
146
|
+
return code;
|
|
147
|
+
}
|
|
103
148
|
function probeModuleFile(basePath) {
|
|
104
149
|
const candidates = [
|
|
105
150
|
basePath,
|
|
@@ -120,8 +165,19 @@ function probeModuleFile(basePath) {
|
|
|
120
165
|
} catch {}
|
|
121
166
|
return;
|
|
122
167
|
}
|
|
123
|
-
function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
|
|
124
|
-
const
|
|
168
|
+
function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles, externalizeUserModules) {
|
|
169
|
+
const toRegistry = (importer, resolved) => {
|
|
170
|
+
if (!externalizeUserModules || importer !== tmpEntry || !REGISTRY_MODULE_EXTENSION.test(resolved))
|
|
171
|
+
return null;
|
|
172
|
+
try {
|
|
173
|
+
if (!fs.statSync(resolved, { throwIfNoEntry: !1 })?.isFile())
|
|
174
|
+
return null;
|
|
175
|
+
} catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
inputFiles.add(resolved);
|
|
179
|
+
return { path: `${MODULE_SPECIFIER_PREFIX}${registryIdForPath(process.cwd(), resolved)}`, external: !0 };
|
|
180
|
+
}, resolveRelative = (importer, request) => {
|
|
125
181
|
const fromDir = importer === tmpEntry ? templateDir : path.dirname(importer), resolved = path.resolve(fromDir, request);
|
|
126
182
|
return probeModuleFile(resolved) ?? resolved;
|
|
127
183
|
};
|
|
@@ -139,6 +195,9 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
|
|
|
139
195
|
build.onResolve({ filter: /^\// }, (args) => {
|
|
140
196
|
const resolved = probeModuleFile(args.path);
|
|
141
197
|
if (resolved) {
|
|
198
|
+
const registered = toRegistry(args.importer, resolved);
|
|
199
|
+
if (registered)
|
|
200
|
+
return registered;
|
|
142
201
|
if (resolved !== tmpEntry)
|
|
143
202
|
inputFiles.add(resolved);
|
|
144
203
|
return { path: resolved };
|
|
@@ -149,7 +208,9 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
|
|
|
149
208
|
};
|
|
150
209
|
});
|
|
151
210
|
build.onResolve({ filter: /^\.\.?\// }, (args) => {
|
|
152
|
-
const resolved = resolveRelative(args.importer, args.path);
|
|
211
|
+
const resolved = resolveRelative(args.importer, args.path), registered = toRegistry(args.importer, resolved);
|
|
212
|
+
if (registered)
|
|
213
|
+
return registered;
|
|
153
214
|
inputFiles.add(resolved);
|
|
154
215
|
return { path: resolved };
|
|
155
216
|
});
|
|
@@ -168,6 +229,9 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
|
|
|
168
229
|
];
|
|
169
230
|
for (const candidate of candidates)
|
|
170
231
|
if (fs.existsSync(candidate) && fs.statSync(candidate, { throwIfNoEntry: !1 })?.isFile()) {
|
|
232
|
+
const registered = toRegistry(args.importer, candidate);
|
|
233
|
+
if (registered)
|
|
234
|
+
return registered;
|
|
171
235
|
logBundlerDiagnostic(`resolved ${args.path[0]}/ import:`, args.path, "\u2192", candidate);
|
|
172
236
|
inputFiles.add(candidate);
|
|
173
237
|
return { path: candidate };
|
|
@@ -175,6 +239,11 @@ function createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles) {
|
|
|
175
239
|
console.warn(`[stx:bundler] could not resolve ${args.path[0]}/ import:`, args.path);
|
|
176
240
|
return { path: resolved };
|
|
177
241
|
});
|
|
242
|
+
build.onResolve({ filter: /^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/ }, (args) => {
|
|
243
|
+
if (!externalizeUserModules || args.importer !== tmpEntry)
|
|
244
|
+
return;
|
|
245
|
+
return { path: `${MODULE_SPECIFIER_PREFIX}npm:${args.path}`, external: !0 };
|
|
246
|
+
});
|
|
178
247
|
build.onLoad({ filter: /\.(?:[cm]?[jt]sx?|json)$/ }, (args) => {
|
|
179
248
|
const extension = path.extname(args.path).toLowerCase(), loader = extension === ".json" ? "json" : extension === ".tsx" ? "tsx" : extension === ".jsx" ? "jsx" : extension === ".ts" || extension === ".mts" || extension === ".cts" ? "ts" : "js";
|
|
180
249
|
if (args.path !== tmpEntry)
|
|
@@ -198,8 +267,8 @@ export function queueClientBundleBuild(task) {
|
|
|
198
267
|
return result;
|
|
199
268
|
}
|
|
200
269
|
export async function bundleClientScript(code, filePath, options = {}) {
|
|
201
|
-
const projectRoot = options.projectRoot || process.cwd(), minify = options.minify ?? !1, cacheDir = options.cacheDir || stateDir(projectRoot, "bundle-cache"), hasher = new Bun.CryptoHasher("md5");
|
|
202
|
-
hasher.update(`${BUNDLE_CACHE_VERSION}\x00${code}\x00${filePath}`);
|
|
270
|
+
const projectRoot = options.projectRoot || process.cwd(), minify = options.minify ?? !1, externalizeUserModules = options.externalizeUserModules ?? !0, cacheDir = options.cacheDir || stateDir(projectRoot, "bundle-cache"), hasher = new Bun.CryptoHasher("md5");
|
|
271
|
+
hasher.update(`${BUNDLE_CACHE_VERSION}\x00${externalizeUserModules ? "registry" : "inline"}\x00${code}\x00${filePath}`);
|
|
203
272
|
const hash = hasher.digest("hex").slice(0, 12), cachePath = path.join(cacheDir, `${hash}.js`), remembered = bundleMemo.get(cachePath);
|
|
204
273
|
if (remembered) {
|
|
205
274
|
if (depsUnchanged(remembered.files)) {
|
|
@@ -248,7 +317,7 @@ export async function bundleClientScript(code, filePath, options = {}) {
|
|
|
248
317
|
options.collectInputs.push(...(bundleMemo.get(cachePath)?.files ?? []).map((dep) => dep.path));
|
|
249
318
|
return shared;
|
|
250
319
|
}
|
|
251
|
-
const build = queueClientBundleBuild(() => buildBundle(code, filePath, { projectRoot, minify, cacheDir, hash, cachePath, depsPath, collectInputs: options.collectInputs }));
|
|
320
|
+
const build = queueClientBundleBuild(() => buildBundle(code, filePath, { projectRoot, minify, cacheDir, hash, cachePath, depsPath, collectInputs: options.collectInputs, externalizeUserModules }));
|
|
252
321
|
inFlightBundles.set(hash, build);
|
|
253
322
|
try {
|
|
254
323
|
return await build;
|
|
@@ -257,14 +326,16 @@ export async function bundleClientScript(code, filePath, options = {}) {
|
|
|
257
326
|
}
|
|
258
327
|
}
|
|
259
328
|
async function buildBundle(code, filePath, options) {
|
|
260
|
-
const { projectRoot, minify, cacheDir, hash, cachePath, depsPath } = options, tmpDir = stateDir(projectRoot, "bundle-tmp"), tmpEntry = path.join(tmpDir, `${hash}.ts`), tmpOutDir = path.join(tmpDir, "out", hash);
|
|
329
|
+
const { projectRoot, minify, cacheDir, hash, cachePath, depsPath, externalizeUserModules } = options, tmpDir = stateDir(projectRoot, "bundle-tmp"), tmpEntry = path.join(tmpDir, `${hash}.ts`), tmpOutDir = path.join(tmpDir, "out", hash);
|
|
261
330
|
fs.mkdirSync(tmpDir, { recursive: !0 });
|
|
262
331
|
fs.mkdirSync(tmpOutDir, { recursive: !0 });
|
|
263
|
-
const templateDir = path.dirname(filePath), declNames = new Set, declRegex = /^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm, funcRegex = /^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm;
|
|
332
|
+
const templateDir = path.dirname(filePath), declNames = new Set, declRegex = /^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm, funcRegex = /^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm, strippedForScan = stripCommentsAndLiterals(code), { depths: scanDepths, balanced: scanBalanced } = bracketDepths(strippedForScan), isTopLevel = (index) => !scanBalanced || scanDepths[index] === 0;
|
|
264
333
|
let dm;
|
|
265
|
-
while ((dm = declRegex.exec(
|
|
334
|
+
while ((dm = declRegex.exec(strippedForScan)) !== null) {
|
|
266
335
|
if (dm[1])
|
|
267
336
|
continue;
|
|
337
|
+
if (!isTopLevel(dm.index))
|
|
338
|
+
continue;
|
|
268
339
|
if (dm[2])
|
|
269
340
|
dm[2].split(",").forEach((n) => {
|
|
270
341
|
const t = destructuredLocalName(n);
|
|
@@ -274,9 +345,11 @@ async function buildBundle(code, filePath, options) {
|
|
|
274
345
|
else if (dm[3])
|
|
275
346
|
declNames.add(dm[3]);
|
|
276
347
|
}
|
|
277
|
-
while ((dm = funcRegex.exec(
|
|
348
|
+
while ((dm = funcRegex.exec(strippedForScan)) !== null) {
|
|
278
349
|
if (dm[1])
|
|
279
350
|
continue;
|
|
351
|
+
if (!isTopLevel(dm.index))
|
|
352
|
+
continue;
|
|
280
353
|
declNames.add(dm[2]);
|
|
281
354
|
}
|
|
282
355
|
const exportLine = declNames.size > 0 ? `
|
|
@@ -291,7 +364,7 @@ export { ${[...declNames].join(", ")} }` : "";
|
|
|
291
364
|
target: "browser",
|
|
292
365
|
format: "esm",
|
|
293
366
|
minify,
|
|
294
|
-
plugins: [createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles)],
|
|
367
|
+
plugins: [createBundlePlugin(projectRoot, templateDir, tmpEntry, inputFiles, externalizeUserModules)],
|
|
295
368
|
define: {
|
|
296
369
|
"process.env.NODE_ENV": minify ? '"production"' : '"development"',
|
|
297
370
|
...getPublicEnvDefine()
|
|
@@ -323,6 +396,8 @@ export { ${[...declNames].join(", ")} }` : "";
|
|
|
323
396
|
if (/^[A-Za-z_$][\w$]*$/.test(name))
|
|
324
397
|
exposedBindings.push([name, name]);
|
|
325
398
|
}
|
|
399
|
+
const registryReads = [];
|
|
400
|
+
bundled = rewriteRegistryImports(bundled, registryReads);
|
|
326
401
|
const externalImports = bundled.match(/^\s*import\s+[^;]+;?\s*$/gm) || [];
|
|
327
402
|
bundled = bundled.replace(/^\s*import\s+[^;]+;?\s*$/gm, "").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm, "").replace(/^\s*export\s+default\s+.*$/gm, "").trim();
|
|
328
403
|
const namespace = `__stxBundle_${hash}`, returnedBindings = exposedBindings.map(([publicName, localName]) => `${JSON.stringify(publicName)}: ${localName}`).join(", "), publicDeclarations = exposedBindings.map(([publicName]) => `var ${publicName} = undefined;`).join(`
|
|
@@ -332,6 +407,8 @@ export { ${[...declNames].join(", ")} }` : "";
|
|
|
332
407
|
`)}
|
|
333
408
|
${publicDeclarations}
|
|
334
409
|
var ${namespace} = (function() {
|
|
410
|
+
${registryReads.join(`
|
|
411
|
+
`)}
|
|
335
412
|
${bundled}
|
|
336
413
|
return { ${returnedBindings} };
|
|
337
414
|
})();
|
package/dist/client-script.js
CHANGED
|
@@ -2,7 +2,7 @@ import path from "node:path";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import { asInvocableStatement } from "./events.js";
|
|
4
4
|
import { transformStoreImports } from "./store-imports.js";
|
|
5
|
-
import { findInterpolationEnd, stripCommentsAndLiterals } from "./strip-literals.js";
|
|
5
|
+
import { bracketDepths, findInterpolationEnd, stripCommentsAndLiterals } from "./strip-literals.js";
|
|
6
6
|
export { findInterpolationEnd, stripCommentsAndLiterals } from "./strip-literals.js";
|
|
7
7
|
import { shouldTranspileTypeScript, transpileTypeScript } from "./utils.js";
|
|
8
8
|
import { importOnce } from "./lazy-module.js";
|
|
@@ -405,13 +405,17 @@ function extractDestructuredBindings(pattern, objectPattern) {
|
|
|
405
405
|
return bindings;
|
|
406
406
|
}
|
|
407
407
|
function declaresClientIdentifier(code, name) {
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
if (
|
|
408
|
+
const stripped = stripCommentsAndLiterals(code), { depths, balanced } = bracketDepths(stripped), atTopLevel = (index) => !balanced || depths[index] === 0, keyword = new RegExp(`(?:^|[^\\w$.])((?:const|let|var|function|class)\\s+${name}\\b)`, "g");
|
|
409
|
+
for (const match of stripped.matchAll(keyword)) {
|
|
410
|
+
const keywordIndex = (match.index ?? 0) + match[0].length - match[1].length;
|
|
411
|
+
if (atTopLevel(keywordIndex))
|
|
412
412
|
return !0;
|
|
413
|
-
|
|
414
|
-
|
|
413
|
+
}
|
|
414
|
+
for (const match of stripped.matchAll(/(?:const|let|var)\s*\{([^}]*)\}/g))
|
|
415
|
+
if (atTopLevel(match.index ?? 0) && extractDestructuredBindings(match[1], !0).has(name))
|
|
416
|
+
return !0;
|
|
417
|
+
for (const match of stripped.matchAll(/(?:const|let|var)\s*\[([^\]]*)\]/g))
|
|
418
|
+
if (atTopLevel(match.index ?? 0) && extractDestructuredBindings(match[1], !1).has(name))
|
|
415
419
|
return !0;
|
|
416
420
|
return !1;
|
|
417
421
|
}
|
|
@@ -442,8 +446,11 @@ export function generateServerDataBridge(code, serverData) {
|
|
|
442
446
|
continue;
|
|
443
447
|
if (!declaredPayload && !referencesIdentifier(searchable, name))
|
|
444
448
|
continue;
|
|
445
|
-
if (declaresClientIdentifier(code, name))
|
|
449
|
+
if (declaresClientIdentifier(code, name)) {
|
|
450
|
+
if (declaredPayload)
|
|
451
|
+
console.warn(`[stx] defineClientPayload declares "${name}", but this client block also declares "${name}" at the top level, so the server value is not published (emitting it would be a duplicate binding). Rename the local, or drop "${name}" from defineClientPayload.`);
|
|
446
452
|
continue;
|
|
453
|
+
}
|
|
447
454
|
let json;
|
|
448
455
|
try {
|
|
449
456
|
json = JSON.stringify(value);
|
|
@@ -22,12 +22,17 @@ export function injectComponentClientFactories(html, context) {
|
|
|
22
22
|
const registry = registryFrom(context);
|
|
23
23
|
if (!registry?.size)
|
|
24
24
|
return html;
|
|
25
|
+
const inlinable = new Map;
|
|
26
|
+
for (const [id, factory] of registry)
|
|
27
|
+
if (factory.instances === 1)
|
|
28
|
+
inlinable.set(id, factory.body);
|
|
25
29
|
let output = html;
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
if (inlinable.size > 0) {
|
|
31
|
+
const alternation = [...inlinable.keys()].map((id) => JSON.stringify(id).replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")).join("|"), invocation = new RegExp(`window\\.__stxComponentFactories\\[(${alternation})\\]\\(("[^"]+")\\);`, "g");
|
|
32
|
+
output = output.replace(invocation, (match, idLiteral, scopeId) => {
|
|
33
|
+
const body = inlinable.get(JSON.parse(idLiteral));
|
|
34
|
+
return body === void 0 ? match : `(${body})(${scopeId});`;
|
|
35
|
+
});
|
|
31
36
|
}
|
|
32
37
|
const repeatedFactories = [...registry].filter(([, factory]) => factory.instances > 1);
|
|
33
38
|
if (repeatedFactories.length === 0)
|
|
@@ -156,6 +156,19 @@ export declare function decodeStxProp(attrValue: string, options?: {
|
|
|
156
156
|
* @param attributesStr - The attributes string (may be multiline)
|
|
157
157
|
* @returns Object mapping attribute names to values
|
|
158
158
|
*/
|
|
159
|
+
/**
|
|
160
|
+
* Read a `{...}` attribute value whole, from `start`, matching nested braces and
|
|
161
|
+
* ignoring braces inside quotes. Returns the text including both outer braces;
|
|
162
|
+
* an unterminated value returns the rest of the string rather than throwing,
|
|
163
|
+
* so a malformed tag degrades to one bad prop instead of a shattered tag.
|
|
164
|
+
*/
|
|
165
|
+
export declare function readBracedValue(source: string, start: number): string;
|
|
166
|
+
/**
|
|
167
|
+
* The expression inside a `prop={expr}` value, or null when `value` is not a
|
|
168
|
+
* braced expression. `{handler}` unwraps to `handler`; the JSX double-brace
|
|
169
|
+
* `{{ a: 1 }}` unwraps to the object literal `{ a: 1 }` (stacksjs/stx#1956).
|
|
170
|
+
*/
|
|
171
|
+
export declare function unwrapBracedExpression(value: string): string | null;
|
|
159
172
|
export declare function parseMultilineAttributes(attributesStr: string): Record<string, string>;
|
|
160
173
|
export declare function parseAttributes(attributesStr: string): ParsedAttribute[];
|
|
161
174
|
/**
|
|
@@ -152,6 +152,36 @@ export function decodeStxProp(attrValue, options) {
|
|
|
152
152
|
return attrValue;
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
|
+
export function readBracedValue(source, start) {
|
|
156
|
+
let depth = 0, quote = "", pos = start;
|
|
157
|
+
while (pos < source.length) {
|
|
158
|
+
const char = source[pos];
|
|
159
|
+
if (quote) {
|
|
160
|
+
if (char === "\\")
|
|
161
|
+
pos++;
|
|
162
|
+
else if (char === quote)
|
|
163
|
+
quote = "";
|
|
164
|
+
} else if (char === '"' || char === "'" || char === "`")
|
|
165
|
+
quote = char;
|
|
166
|
+
else if (char === "{")
|
|
167
|
+
depth++;
|
|
168
|
+
else if (char === "}") {
|
|
169
|
+
depth--;
|
|
170
|
+
if (depth === 0)
|
|
171
|
+
return source.slice(start, pos + 1);
|
|
172
|
+
}
|
|
173
|
+
pos++;
|
|
174
|
+
}
|
|
175
|
+
return source.slice(start);
|
|
176
|
+
}
|
|
177
|
+
export function unwrapBracedExpression(value) {
|
|
178
|
+
const trimmed = value.trim();
|
|
179
|
+
if (!trimmed.startsWith("{") || !trimmed.endsWith("}"))
|
|
180
|
+
return null;
|
|
181
|
+
if (readBracedValue(trimmed, 0).length !== trimmed.length)
|
|
182
|
+
return null;
|
|
183
|
+
return trimmed.slice(1, -1).trim();
|
|
184
|
+
}
|
|
155
185
|
export function parseMultilineAttributes(attributesStr) {
|
|
156
186
|
const props = {};
|
|
157
187
|
let pos = 0;
|
|
@@ -208,6 +238,9 @@ export function parseMultilineAttributes(attributesStr) {
|
|
|
208
238
|
value += char;
|
|
209
239
|
pos++;
|
|
210
240
|
}
|
|
241
|
+
} else if (attributesStr[pos] === "{") {
|
|
242
|
+
value = readBracedValue(attributesStr, pos);
|
|
243
|
+
pos += value.length;
|
|
211
244
|
} else
|
|
212
245
|
while (pos < len && !/\s/.test(attributesStr[pos])) {
|
|
213
246
|
value += attributesStr[pos];
|
|
@@ -255,6 +288,9 @@ export function parseAttributes(attributesStr) {
|
|
|
255
288
|
}
|
|
256
289
|
if (pos < len)
|
|
257
290
|
pos++;
|
|
291
|
+
} else if (attributesStr[pos] === "{") {
|
|
292
|
+
value = readBracedValue(attributesStr, pos);
|
|
293
|
+
pos += value.length;
|
|
258
294
|
} else
|
|
259
295
|
while (pos < len && !/\s/.test(attributesStr[pos])) {
|
|
260
296
|
value += attributesStr[pos];
|
|
@@ -556,7 +592,7 @@ export async function processCustomElements(template, context, filePath, compone
|
|
|
556
592
|
output = await processComponentsWithParser(output, /[a-z][a-z0-9]*-[a-z0-9-]*/, !1);
|
|
557
593
|
output = await processComponentsWithParser(output, /[A-Z][a-zA-Z0-9]*/, !0, uppercaseHtmlTagSkip(htmlTags));
|
|
558
594
|
output = await processComponentsWithParser(output, /[a-z][a-z0-9]*/, !1, htmlTags);
|
|
559
|
-
output =
|
|
595
|
+
output = stashed.restore(output);
|
|
560
596
|
return output;
|
|
561
597
|
async function processComponentsWithParser(html, tagPattern, isPascalCase, skipTags) {
|
|
562
598
|
let result = html;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { registry } from "./component-registry.js";
|
|
2
2
|
import { processConditionals } from "./conditionals.js";
|
|
3
3
|
import { registerBuiltins } from "./builtins/index.js";
|
|
4
|
-
import { decodeAttributeEntities, decodeStxProp, findComponentTags, parseMultilineAttributes, pascalToKebab, restoreStashedScripts, stashScriptElements, uppercaseHtmlTagSkip } from "./component-processing.js";
|
|
4
|
+
import { decodeAttributeEntities, decodeStxProp, findComponentTags, parseMultilineAttributes, pascalToKebab, readBracedValue, restoreStashedScripts, stashScriptElements, unwrapBracedExpression, uppercaseHtmlTagSkip } from "./component-processing.js";
|
|
5
5
|
import { maskAtElementPosition, matchHtmlComment } from "./html-masking.js";
|
|
6
6
|
import { renderComponentWithSlot, userComponentFileExists } from "./utils.js";
|
|
7
7
|
import { createSafeFunction, isExpressionSafe, safeEvaluateObject, freeIdentifiers } from "./safe-evaluator.js";
|
|
@@ -359,6 +359,14 @@ function parseAllAttributes(attributesStr) {
|
|
|
359
359
|
value += char;
|
|
360
360
|
pos++;
|
|
361
361
|
}
|
|
362
|
+
} else if (attributesStr[pos] === "{") {
|
|
363
|
+
value = readBracedValue(attributesStr, pos);
|
|
364
|
+
pos += value.length;
|
|
365
|
+
const expression = unwrapBracedExpression(value);
|
|
366
|
+
if (expression !== null) {
|
|
367
|
+
props[`:${name}`] = expression;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
362
370
|
} else
|
|
363
371
|
while (pos < len && !/\s/.test(attributesStr[pos])) {
|
|
364
372
|
value += attributesStr[pos];
|
|
@@ -447,15 +455,13 @@ function resolvePackageDir(spec, fromDir) {
|
|
|
447
455
|
|
|
448
456
|
export { freeIdentifiers };
|
|
449
457
|
export async function processESImports(template, context, filePath, options, dependencies) {
|
|
450
|
-
if (
|
|
458
|
+
if (!/import\s/.test(template))
|
|
451
459
|
return template;
|
|
452
460
|
if (!context.__importedComponents)
|
|
453
461
|
context.__importedComponents = new Map;
|
|
454
|
-
const registered = context.__importedComponents, fromDir = path.dirname(filePath);
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
output = output.replace(scriptRe, (full, attrs, body) => {
|
|
458
|
-
const importRe = /import\s+(?:(\{[^}]*\})|([A-Za-z_$][\w$]*))\s+from\s+['"]([^'"]+)['"]\s*;?\s*\n?/g;
|
|
462
|
+
const registered = context.__importedComponents, fromDir = path.dirname(filePath), replacements = [], scriptRe = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
|
463
|
+
for (const scriptMatch of template.matchAll(scriptRe)) {
|
|
464
|
+
const [full, attrs, body] = scriptMatch, importRe = /import\s+(?:(\{[^}]*\})|([A-Za-z_$][\w$]*))\s+from\s+['"]([^'"]+)['"]\s*;?\s*\n?/g;
|
|
459
465
|
let newBody = body, m;
|
|
460
466
|
const removals = [];
|
|
461
467
|
while ((m = importRe.exec(body)) !== null) {
|
|
@@ -515,12 +521,25 @@ export async function processESImports(template, context, filePath, options, dep
|
|
|
515
521
|
removals.push({ start: m.index, end: m.index + matchStr.length });
|
|
516
522
|
}
|
|
517
523
|
if (removals.length === 0)
|
|
518
|
-
|
|
524
|
+
continue;
|
|
519
525
|
for (let i = removals.length - 1;i >= 0; i--)
|
|
520
526
|
newBody = newBody.slice(0, removals[i].start) + newBody.slice(removals[i].end);
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
527
|
+
replacements.push({
|
|
528
|
+
start: scriptMatch.index,
|
|
529
|
+
end: scriptMatch.index + full.length,
|
|
530
|
+
value: `<script${attrs}>${newBody}</script>`
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
if (replacements.length === 0)
|
|
534
|
+
return template;
|
|
535
|
+
const chunks = [];
|
|
536
|
+
let cursor = 0;
|
|
537
|
+
for (const replacement of replacements) {
|
|
538
|
+
chunks.push(template.slice(cursor, replacement.start), replacement.value);
|
|
539
|
+
cursor = replacement.end;
|
|
540
|
+
}
|
|
541
|
+
chunks.push(template.slice(cursor));
|
|
542
|
+
return chunks.join("");
|
|
524
543
|
}
|
|
525
544
|
async function processImports(template, context, filePath, options, dependencies) {
|
|
526
545
|
let output = template;
|
|
@@ -630,7 +649,7 @@ async function processCustomElementTags(template, context, filePath, options, de
|
|
|
630
649
|
output = await processTagsWithParser(output, /[a-z][a-z0-9]*-[a-z0-9-]*/, !1);
|
|
631
650
|
output = await processTagsWithParser(output, /[A-Z][a-zA-Z0-9]*/, !0, uppercaseHtmlTagSkip(htmlTags));
|
|
632
651
|
output = await processTagsWithParser(output, /[a-z][a-z0-9]*/, !1, htmlTags);
|
|
633
|
-
output =
|
|
652
|
+
output = stashed.restore(output);
|
|
634
653
|
return output;
|
|
635
654
|
async function processTagsWithParser(html, tagPattern, isPascalCase, skipTags) {
|
|
636
655
|
if (!html)
|
|
@@ -663,7 +682,7 @@ async function processCustomElementTags(template, context, filePath, options, de
|
|
|
663
682
|
mergedProps[key] = value;
|
|
664
683
|
for (const [key, value] of Object.entries(resolvedProps.serverDynamic))
|
|
665
684
|
mergedProps[key] = value;
|
|
666
|
-
let finalContent = await renderComponentWithSlot(componentPath, mergedProps,
|
|
685
|
+
let finalContent = await renderComponentWithSlot(componentPath, mergedProps, stashed.restore(tag.content), componentsDir, context, filePath, options, processedComponents, dependencies);
|
|
667
686
|
if (Object.keys(resolvedProps.events).length > 0) {
|
|
668
687
|
const root = findRenderedComponentRoot(finalContent);
|
|
669
688
|
if (root) {
|
|
@@ -745,7 +764,7 @@ function findRenderedComponentRoot(html) {
|
|
|
745
764
|
}
|
|
746
765
|
export async function processComponents(template, context, filePath, options, dependencies) {
|
|
747
766
|
if (!builtinsRegistered) {
|
|
748
|
-
registerBuiltins();
|
|
767
|
+
registerBuiltins(registry);
|
|
749
768
|
builtinsRegistered = !0;
|
|
750
769
|
}
|
|
751
770
|
let output = await processESImports(template, context, filePath, options, dependencies);
|
|
@@ -753,7 +772,7 @@ export async function processComponents(template, context, filePath, options, de
|
|
|
753
772
|
output = await processComponentDirectives(output, context, filePath, options, dependencies);
|
|
754
773
|
const nestedComments = [];
|
|
755
774
|
for (let pass = 0;pass < 3; pass++) {
|
|
756
|
-
const masked = maskAtElementPosition(output, matchHtmlComment, (_token, index) => `\x00STX_COMPONENT_COMMENT_${
|
|
775
|
+
const commentOffset = nestedComments.length, masked = maskAtElementPosition(output, matchHtmlComment, (_token, index) => `\x00STX_COMPONENT_COMMENT_${commentOffset + index}\x00`, `STX_COMPONENT_COMMENT:${commentOffset}`);
|
|
757
776
|
nestedComments.push(...masked.tokens);
|
|
758
777
|
const before = output;
|
|
759
778
|
output = await processCustomElementTags(masked.output, context, filePath, options, dependencies);
|
package/dist/conditionals.js
CHANGED
|
@@ -143,6 +143,7 @@ function processConditionalsIn(template, context, filePath) {
|
|
|
143
143
|
const ifBlocks = findIfBlocks(output);
|
|
144
144
|
if (ifBlocks.length === 0)
|
|
145
145
|
return !1;
|
|
146
|
+
const replacements = Array(ifBlocks.length);
|
|
146
147
|
for (let i = ifBlocks.length - 1;i >= 0; i--) {
|
|
147
148
|
const block = ifBlocks[i];
|
|
148
149
|
try {
|
|
@@ -169,12 +170,22 @@ function processConditionalsIn(template, context, filePath) {
|
|
|
169
170
|
foundTrueBranch = !0;
|
|
170
171
|
}
|
|
171
172
|
}
|
|
172
|
-
|
|
173
|
+
replacements[i] = result;
|
|
173
174
|
} catch (error) {
|
|
174
|
-
const msg = error instanceof Error ? error.message : String(error)
|
|
175
|
-
|
|
175
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
176
|
+
replacements[i] = inlineError("If", `Error processing @if block: ${msg}`, ErrorCodes.EVALUATION_ERROR);
|
|
176
177
|
}
|
|
177
178
|
}
|
|
179
|
+
const chunks = Array(ifBlocks.length * 2 + 1);
|
|
180
|
+
let cursor = 0;
|
|
181
|
+
for (let i = 0;i < ifBlocks.length; i++) {
|
|
182
|
+
const block = ifBlocks[i];
|
|
183
|
+
chunks[i * 2] = output.slice(cursor, block.start);
|
|
184
|
+
chunks[i * 2 + 1] = replacements[i];
|
|
185
|
+
cursor = block.end;
|
|
186
|
+
}
|
|
187
|
+
chunks[ifBlocks.length * 2] = output.slice(cursor);
|
|
188
|
+
output = chunks.join("");
|
|
178
189
|
return !0;
|
|
179
190
|
};
|
|
180
191
|
while (!0) {
|
package/dist/craft-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$j as
|
|
2
|
+
import{$j as Yj,Zj as Uj,_j as Xj,ak as Zj,bk as _j,ck as $j,dk as qj,ek as Fj,fk as Oj,gk as Vj,hk as Ij,ik as Qj,jk as Wj,kk as Kj}from"./chunk-vwzqg4fh.js";import{mk as Nj,nk as wj,ok as Aj}from"./chunk-fvh9ca47.js";import"./chunk-ee2tfpec.js";import"./chunk-qj2s3r1w.js";import"./chunk-ymc99r5x.js";import"./chunk-dcxtrqfy.js";import"./chunk-jj6yp7gm.js";import"./chunk-qjkzpd68.js";import"./chunk-t5c7rk0h.js";import"./chunk-72c7gyqc.js";import"./chunk-fv923f7g.js";import"./chunk-2e6xafcm.js";import"./chunk-nygtwffe.js";import"./chunk-461br5nn.js";import"./chunk-h7v70dbp.js";import"./chunk-drbbt69f.js";import"./chunk-kb5j08tq.js";import"./chunk-2vza9m2x.js";var I=new Map,Q=new Map;function L(j,B){let G=B?.id||g(j),J=h(j),U=I.get(G);if(U&&U.hash===J)return U;let X=S(j),Z=y(j),Y=T(j),_=v(X),{staticParts:q,dynamicParts:$}=C(X),F=u(j),O={id:G,hash:J,tree:X,scripts:Z,styles:Y,staticParts:q,dynamicParts:$,dependencies:F,metadata:_};return I.set(G,O),O}async function r(j,B={},G={}){let J=performance.now();if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`,_=Q.get(Y);if(_&&Date.now()-_.timestamp<(G.cacheTTL||60000))return{html:_.html,styles:j.styles.join(`
|
|
3
3
|
`),scripts:j.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:_.html.length,componentCount:j.metadata.componentCount}}}let U;if(G.streaming)U=await H(j.tree,B);else U=W(j.tree,B);let X;if(G.hydrate){let Y=k(U,j,B);U=Y.html,X=Y.data}if(G.minify)U=x(U);if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`;Q.set(Y,{html:U,timestamp:Date.now()})}let Z=performance.now()-J;return{html:U,styles:j.styles.join(`
|
|
5
5
|
`),scripts:j.scripts.join(`
|
package/dist/craft.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$j as
|
|
2
|
+
import{$j as Yj,Zj as Uj,_j as Xj,ak as Zj,bk as _j,ck as $j,dk as qj,ek as Fj,fk as Oj,gk as Vj,hk as Ij,ik as Qj,jk as Wj,kk as Kj}from"./chunk-vwzqg4fh.js";import{mk as Nj,nk as wj,ok as Aj}from"./chunk-fvh9ca47.js";import"./chunk-ee2tfpec.js";import"./chunk-qj2s3r1w.js";import"./chunk-ymc99r5x.js";import"./chunk-dcxtrqfy.js";import"./chunk-jj6yp7gm.js";import"./chunk-qjkzpd68.js";import"./chunk-t5c7rk0h.js";import"./chunk-72c7gyqc.js";import"./chunk-fv923f7g.js";import"./chunk-2e6xafcm.js";import"./chunk-nygtwffe.js";import"./chunk-461br5nn.js";import"./chunk-h7v70dbp.js";import"./chunk-drbbt69f.js";import"./chunk-kb5j08tq.js";import"./chunk-2vza9m2x.js";var I=new Map,Q=new Map;function L(j,B){let G=B?.id||g(j),J=h(j),U=I.get(G);if(U&&U.hash===J)return U;let X=S(j),Z=y(j),Y=T(j),_=v(X),{staticParts:q,dynamicParts:$}=C(X),F=u(j),O={id:G,hash:J,tree:X,scripts:Z,styles:Y,staticParts:q,dynamicParts:$,dependencies:F,metadata:_};return I.set(G,O),O}async function r(j,B={},G={}){let J=performance.now();if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`,_=Q.get(Y);if(_&&Date.now()-_.timestamp<(G.cacheTTL||60000))return{html:_.html,styles:j.styles.join(`
|
|
3
3
|
`),scripts:j.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:_.html.length,componentCount:j.metadata.componentCount}}}let U;if(G.streaming)U=await H(j.tree,B);else U=W(j.tree,B);let X;if(G.hydrate){let Y=k(U,j,B);U=Y.html,X=Y.data}if(G.minify)U=x(U);if(G.cache){let Y=`${j.id}:${JSON.stringify(B)}`;Q.set(Y,{html:U,timestamp:Date.now()})}let Z=performance.now()-J;return{html:U,styles:j.styles.join(`
|
|
5
5
|
`),scripts:j.scripts.join(`
|
package/dist/database.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{dv as Q}from"./chunk-sskbegsz.js";var $={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},V={},A={},L=new Map,S=[];function i(z){$={...$,...z}}function o(){return{...$}}function r(){$={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let z of Object.keys(V))delete V[z];L.clear(),S.length=0}function a(z,H){V[z]=H}function F(z){let H=z||$.default;if(V[H])return V[H];let U=$.connections[H];if(!U)throw Error(`Database connection "${H}" not configured`);let W=h(U);return V[H]=W,W}function h(z){switch(z.driver){case"sqlite":return q(z);case"postgres":return y(z);case"mysql":return f(z);default:throw Error(`Unsupported database driver: ${z.driver}`)}}function q(z){let H=null,U=!1;return{async connect(){if(U)return;let{Database:W}=await import("bun:sqlite");H=new W(z.database,{create:!0,readwrite:!0}),U=!0},async disconnect(){if(H)H.close(),H=null,U=!1},async query(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).all(...J);if($.logging)B(W,J,performance.now()-X);return Y}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.lastInsertRowid}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.changes}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!U)await this.connect();H.run("BEGIN TRANSACTION")},async commit(){H.run("COMMIT")},async rollback(){H.run("ROLLBACK")},isConnected(){return U}}}function y(z){let H=!1,U=null;return{async connect(){if(H)return;try{let{Client:W}=await import("pg");U=new W({host:z.host||"localhost",port:z.port||5432,database:z.database,user:z.username,password:z.password,ssl:z.ssl}),await U.connect(),H=!0}catch(W){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rows}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(`${W} RETURNING id`,J);if($.logging)B(W,J,performance.now()-X);return Z.rows[0]?.id}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rowCount||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();await U.query("BEGIN")},async commit(){await U.query("COMMIT")},async rollback(){await U.query("ROLLBACK")},isConnected(){return H}}}function f(z){let H=!1,U=null;return{async connect(){if(H)return;try{U=(await import("mysql2/promise")).createPool({host:z.host||"localhost",port:z.port||3306,database:z.database,user:z.username,password:z.password,waitForConnections:!0,connectionLimit:z.poolSize||10,queueLimit:0}),H=!0}catch(W){throw Error(`MySQL connection failed. Install 'mysql2' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.insertId}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.affectedRows||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();let W=await U.getConnection();return await W.beginTransaction(),W},async commit(){await U.execute("COMMIT")},async rollback(){await U.execute("ROLLBACK")},isConnected(){return H}}}class D{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(z){if(z)this._table=z}table(z){return this._table=z,this}from(z){return this.table(z)}connection(z){return this._connection=z,this}select(...z){return this._columns=z.length>0?z:["*"],this}addSelect(...z){if(this._columns[0]==="*")this._columns=z;else this._columns.push(...z);return this}distinct(){return this._distinct=!0,this}where(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"and"}),this}orWhere(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"or"}),this}whereIn(z,H){return this._wheres.push({column:z,operator:"in",value:H,boolean:"and"}),this}whereNotIn(z,H){return this._wheres.push({column:z,operator:"not in",value:H,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(z,H,U){return this._wheres.push({column:z,operator:"between",value:[H,U],boolean:"and"}),this}whereLike(z,H){return this._wheres.push({column:z,operator:"like",value:H,boolean:"and"}),this}join(z,H,U,W){return this._joins.push({type:"inner",table:z,first:H,operator:U,second:W}),this}leftJoin(z,H,U,W){return this._joins.push({type:"left",table:z,first:H,operator:U,second:W}),this}rightJoin(z,H,U,W){return this._joins.push({type:"right",table:z,first:H,operator:U,second:W}),this}orderBy(z,H="asc"){return this._orders.push({column:z,direction:H}),this}orderByDesc(z){return this.orderBy(z,"desc")}groupBy(...z){return this._groupBy.push(...z),this}having(z,H,U){return this._having.push({column:z,operator:H,value:U,boolean:"and"}),this}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}forPage(z,H=15){return this.offset((z-1)*H).limit(H)}async get(){let{sql:z,bindings:H}=this.toSql();if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H),X=g(J);if(X!==void 0)return X}let W=await F(this._connection).query(z,H);if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H);m(J,W,$.cacheTTL)}return W}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let z=await this.first();if(!z)throw Error("No results found");return z}async find(z,H="id"){return this.where(H,z).first()}async value(z){let H=await this.select(z).first();return H?H[z]:null}async pluck(z){return(await this.select(z).get()).map((U)=>U[z])}async exists(){return(await this.select(E("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(z="*"){let H=await this.select(E(`COUNT(${z}) as count`)).first();return Number(H?.count||0)}async max(z){return(await this.select(E(`MAX(${z}) as max`)).first())?.max}async min(z){return(await this.select(E(`MIN(${z}) as min`)).first())?.min}async sum(z){let H=await this.select(E(`SUM(${z}) as sum`)).first();return Number(H?.sum||0)}async avg(z){return(await this.select(E(`AVG(${z}) as avg`)).first())?.avg}async insert(z){let H=Object.keys(z),U=H.map(()=>"?").join(", "),W=Object.values(z),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES (${U})`,X=F(this._connection);return P(this._table),X.insert(J,W)}async insertAll(z){if(z.length===0)return;let H=Object.keys(z[0]),U=z.map(()=>`(${H.map(()=>"?").join(", ")})`).join(", "),W=z.flatMap((Z)=>Object.values(Z)),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES ${U}`,X=F(this._connection);P(this._table),await X.execute(J,W)}async update(z){this._bindings=[];let H=this.buildWhereClause(),U=[...this._bindings],W=Object.keys(z).map((Y)=>`${Y} = ?`).join(", "),J=[...Object.values(z),...U],X=`UPDATE ${this._table} SET ${W}${H}`,Z=F(this._connection);return P(this._table),Z.execute(X,J)}async increment(z,H=1){this._bindings=[];let U=this.buildWhereClause(),W=`UPDATE ${this._table} SET ${z} = ${z} + ?${U}`,J=F(this._connection);return P(this._table),J.execute(W,[H,...this._bindings])}async decrement(z,H=1){return this.increment(z,-H)}async delete(){this._bindings=[];let z=this.buildWhereClause(),H=`DELETE FROM ${this._table}${z}`,U=F(this._connection);return P(this._table),U.execute(H,this._bindings)}async truncate(){let z=F(this._connection);P(this._table),await z.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let z="SELECT ";if(this._distinct)z+="DISTINCT ";z+=this._columns.map((H)=>{if(typeof H==="object"&&H.__raw)return H.sql;return H}).join(", "),z+=` FROM ${this._table}`;for(let H of this._joins)z+=` ${H.type.toUpperCase()} JOIN ${H.table} ON ${H.first} ${H.operator} ${H.second}`;if(z+=this.buildWhereClause(),this._groupBy.length>0)z+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let H=this._having.map((U,W)=>{let J=W===0?"":` ${U.boolean.toUpperCase()} `;return this._bindings.push(U.value),`${J}${U.column} ${U.operator} ?`});z+=` HAVING ${H.join("")}`}if(this._orders.length>0)z+=` ORDER BY ${this._orders.map((H)=>`${H.column} ${H.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)z+=` OFFSET ${this._offset}`;return{sql:z,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((H,U)=>{let W=U===0?" WHERE ":` ${H.boolean.toUpperCase()} `;switch(H.operator){case"in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} IN (${X})`}case"not in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} NOT IN (${X})`}case"between":{let[J,X]=H.value;return this._bindings.push(J,X),`${W}${H.column} BETWEEN ? AND ?`}case"is null":return`${W}${H.column} IS NULL`;case"is not null":return`${W}${H.column} IS NOT NULL`;default:return this._bindings.push(H.value),`${W}${H.column} ${H.operator} ?`}}).join("")}getCacheKey(z,H){return`${this._table}:${z}:${JSON.stringify(H)}`}clone(){let z=new D(this._table);return z._columns=[...this._columns],z._wheres=[...this._wheres],z._orders=[...this._orders],z._joins=[...this._joins],z._groupBy=[...this._groupBy],z._having=[...this._having],z._limit=this._limit,z._offset=this._offset,z._distinct=this._distinct,z._connection=this._connection,z}}function G(z){return new D(z)}function t(z){return G(z)}function E(z,H=[]){return{__raw:!0,sql:z,bindings:H}}function n(z,H){let U=H.primaryKey||"id",W={name:z,definition:H,async find(J){let X=await G(H.table).where(U,J).first();return X?N(W,X):null},async findOrFail(J){let X=await this.find(J);if(!X)throw Error(`${z} not found with ${U} = ${J}`);return X},async all(){return(await G(H.table).get()).map((X)=>N(W,X))},async create(J){let X={...H.defaults,...J},Z=H.fillable?Object.fromEntries(Object.entries(X).filter(([_])=>H.fillable.includes(_))):X;if(H.timestamps!==!1){let _=new Date().toISOString(),R=typeof H.timestamps==="object"?H.timestamps.createdAt||"created_at":"created_at",T=typeof H.timestamps==="object"?H.timestamps.updatedAt||"updated_at":"updated_at";Z[R]=_,Z[T]=_}let Y=await G(H.table).insert(Z);return this.findOrFail(Y)},async update(J){return G(H.table).update(J)},async destroy(J){let X=Array.isArray(J)?J:[J];return G(H.table).whereIn(U,X).delete()},query(){return G(H.table)},where(J,X,Z){return this.query().where(J,X,Z)},async first(){let J=await this.query().first();return J?N(W,J):null},async get(){return(await this.query().get()).map((X)=>N(W,X))},async count(){return this.query().count()}};return A[z]=W,W}function k(z){let H=A[z];if(!H)throw Error(`Model "${z}" not defined. Use defineModel() first.`);return H}function e(z){return z in A}function N(z,H){let{definition:U}=z,W=U.primaryKey||"id",J={...H},X={...H};if(U.casts){for(let[Y,_]of Object.entries(U.casts))if(Y in X)X[Y]=p(X[Y],_)}let Z={exists:!0,original:J,attributes:X,get(Y){return X[Y]},set(Y,_){X[Y]=_},toJSON(){let Y={...X};if(U.hidden)for(let _ of U.hidden)delete Y[_];return Y},async save(){let Y={};for(let _ of Object.keys(X))if(X[_]!==J[_])Y[_]=X[_];if(Object.keys(Y).length>0){if(U.timestamps!==!1){let _=typeof U.timestamps==="object"?U.timestamps.updatedAt||"updated_at":"updated_at";Y[_]=new Date().toISOString()}await G(U.table).where(W,J[W]).update(Y),Object.assign(J,Y)}},async delete(){if(U.softDeletes){let Y=typeof U.softDeletes==="string"?U.softDeletes:"deleted_at";await G(U.table).where(W,J[W]).update({[Y]:new Date().toISOString()})}else await G(U.table).where(W,J[W]).delete();Z.exists=!1},async refresh(){let Y=await G(U.table).where(W,J[W]).first();if(Y)Object.assign(J,Y),Object.assign(X,Y)},isDirty(Y){if(Y)return X[Y]!==J[Y];return Object.keys(X).some((_)=>X[_]!==J[_])}};if(U.relationships)for(let[Y,_]of Object.entries(U.relationships))Object.defineProperty(Z,Y,{value:async()=>{return b(Z,_,z)},enumerable:!1});return new Proxy(Z,{get(Y,_){if(_ in Y)return Y[_];return X[_]},set(Y,_,R){if(_ in Y)Y[_]=R;else X[_]=R;return!0}})}async function b(z,H,U){let W=k(H.model),J=U.definition.primaryKey||"id";switch(H.type){case"hasOne":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`,Z=await G(W.definition.table).where(X,z.get(J)).first();return Z?N(W,Z):null}case"hasMany":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`;return(await G(W.definition.table).where(X,z.get(J)).get()).map((Y)=>N(W,Y))}case"belongsTo":{let X=H.foreignKey||`${H.model.toLowerCase()}_id`,Z=H.localKey||"id",Y=await G(W.definition.table).where(Z,z.get(X)).first();return Y?N(W,Y):null}case"belongsToMany":{let X=H.pivotTable||[U.name,H.model].sort().join("_").toLowerCase(),Z=H.pivotForeignKey||`${U.name.toLowerCase()}_id`,Y=H.pivotRelatedKey||`${H.model.toLowerCase()}_id`,_=W.definition.primaryKey||"id";return(await G(W.definition.table).join(X,`${W.definition.table}.${_}`,"=",`${X}.${Y}`).where(`${X}.${Z}`,z.get(J)).get()).map((T)=>N(W,T))}default:return null}}function p(z,H){if(z===null||z===void 0)return z;switch(H){case"string":return String(z);case"number":return Number(z);case"boolean":return Boolean(z);case"date":return new Date(z);case"json":case"array":return typeof z==="string"?JSON.parse(z):z;default:return z}}async function zz(z,H){let U=F(H);await U.beginTransaction();try{let W=await z();return await U.commit(),W}catch(W){throw await U.rollback(),W}}function g(z){let H=L.get(z);if(!H)return;if(Date.now()-H.timestamp>H.ttl*1000){L.delete(z);return}return H.result}function m(z,H,U){if(L.size>=($.maxCacheSize||1000)){let W=L.keys().next().value;if(W)L.delete(W)}L.set(z,{result:H,timestamp:Date.now(),ttl:U})}function P(z){for(let H of L.keys())if(H.startsWith(`${z}:`))L.delete(H)}function Hz(){L.clear()}function Jz(){return{size:L.size,keys:[...L.keys()]}}function B(z,H,U){if(S.push({sql:z,bindings:H,duration:U,timestamp:new Date}),S.length>1000)S.shift()}function Uz(){return[...S]}function Wz(){S.length=0}function Xz(z=!0){$.logging=z}class O extends Error{sql;bindings;constructor(z,H,U){super(z);this.sql=H;this.bindings=U;this.name="DatabaseError"}}async function u(z,H,U,W){let J=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=await s(R,T),I=`$${R}`;H[I]=j,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- DB Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function d(z,H,U,W){let J=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=k(R),I=await l(j,T),K=`$${R.toLowerCase()}`;H[K]=I,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- Model Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function c(z,H,U,W){let J=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T,j]=Y;try{let I=T?JSON.parse(T):[],v=await F().query(R,I);H[`$${j}`]=v,X=X.replace(_,"")}catch(I){X=X.replace(_,`<!-- Query Error: ${I instanceof Error?I.message:String(I)} -->`)}}return X}async function s(z,H){let U=G(z),W=/->(\w+)\(([^)]*)\)/g,J=[...H.matchAll(W)],X=U;for(let[,Z,Y]of J){let _=M(Y);if(typeof X[Z]==="function"){if(X=X[Z](..._),X instanceof Promise){X=await X;break}}}if(X instanceof D)X=await X.get();return X}async function l(z,H){let U=/->(\w+)\(([^)]*)\)/g,W=[...H.matchAll(U)],J=z;for(let[,X,Z]of W){let Y=M(Z);if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}else if(J instanceof D){if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}}}if(J instanceof D)J=await J.get();return J}function M(z){if(!z.trim())return[];let H=[],U="",W=0,J=!1,X="";for(let Z=0;Z<z.length;Z++){let Y=z[Z];if(!J&&(Y==='"'||Y==="'"))J=!0,X=Y,U+=Y;else if(J&&Y===X)J=!1,U+=Y;else if(!J&&(Y==="["||Y==="{"||Y==="("))W++,U+=Y;else if(!J&&(Y==="]"||Y==="}"||Y===")"))W--,U+=Y;else if(!J&&W===0&&Y===",")H.push(x(U.trim())),U="";else U+=Y}if(U.trim())H.push(x(U.trim()));return H}function x(z){if(z.startsWith('"')&&z.endsWith('"')||z.startsWith("'")&&z.endsWith("'"))return z.slice(1,-1);if(z==="true")return!0;if(z==="false")return!1;if(z==="null")return null;let H=Number(z);if(!Number.isNaN(H))return H;try{return JSON.parse(z)}catch{return z}}async function Yz(z,H,U,W){let J=z;return J=await c(J,H,U,W),J=await d(J,H,U,W),J=await u(J,H,U,W),J}class w{_connection;connection(z){return this._connection=z,this}async create(z,H){let U=new C(z);H(U);let W=U.toCreateSQL();await F(this._connection).execute(W)}async drop(z){await F(this._connection).execute(`DROP TABLE IF EXISTS ${z}`)}async rename(z,H){await F(this._connection).execute(`ALTER TABLE ${z} RENAME TO ${H}`)}async hasTable(z){let H=F(this._connection);try{return await H.query(`SELECT 1 FROM ${z} LIMIT 1`),!0}catch{return!1}}}class C{table;columns=[];indices=[];constructor(z){this.table=z}id(z="id"){return this.columns.push(`${z} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(z,H=255){return this.columns.push(`${z} VARCHAR(${H})`),this}text(z){return this.columns.push(`${z} TEXT`),this}integer(z){return this.columns.push(`${z} INTEGER`),this}boolean(z){return this.columns.push(`${z} BOOLEAN DEFAULT 0`),this}datetime(z){return this.columns.push(`${z} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(z){return this.columns.push(`${z} TEXT`),this}foreignId(z){return this.columns.push(`${z} INTEGER`),this}index(z){let H=Array.isArray(z)?z:[z],U=`idx_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}unique(z){let H=Array.isArray(z)?z:[z],U=`uniq_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
2
|
+
import{kv as Q}from"./chunk-2vza9m2x.js";var $={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000},V={},A={},L=new Map,S=[];function i(z){$={...$,...z}}function o(){return{...$}}function r(){$={default:"sqlite",connections:{},logging:!1,cacheTTL:0,maxCacheSize:1000};for(let z of Object.keys(V))delete V[z];L.clear(),S.length=0}function a(z,H){V[z]=H}function F(z){let H=z||$.default;if(V[H])return V[H];let U=$.connections[H];if(!U)throw Error(`Database connection "${H}" not configured`);let W=h(U);return V[H]=W,W}function h(z){switch(z.driver){case"sqlite":return q(z);case"postgres":return y(z);case"mysql":return f(z);default:throw Error(`Unsupported database driver: ${z.driver}`)}}function q(z){let H=null,U=!1;return{async connect(){if(U)return;let{Database:W}=await import("bun:sqlite");H=new W(z.database,{create:!0,readwrite:!0}),U=!0},async disconnect(){if(H)H.close(),H=null,U=!1},async query(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).all(...J);if($.logging)B(W,J,performance.now()-X);return Y}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.lastInsertRowid}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!U)await this.connect();let X=performance.now();try{let Y=H.prepare(W).run(...J);if($.logging)B(W,J,performance.now()-X);return Y.changes}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!U)await this.connect();H.run("BEGIN TRANSACTION")},async commit(){H.run("COMMIT")},async rollback(){H.run("ROLLBACK")},isConnected(){return U}}}function y(z){let H=!1,U=null;return{async connect(){if(H)return;try{let{Client:W}=await import("pg");U=new W({host:z.host||"localhost",port:z.port||5432,database:z.database,user:z.username,password:z.password,ssl:z.ssl}),await U.connect(),H=!0}catch(W){throw Error(`PostgreSQL connection failed. Install 'pg' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rows}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(`${W} RETURNING id`,J);if($.logging)B(W,J,performance.now()-X);return Z.rows[0]?.id}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let Z=await U.query(W,J);if($.logging)B(W,J,performance.now()-X);return Z.rowCount||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();await U.query("BEGIN")},async commit(){await U.query("COMMIT")},async rollback(){await U.query("ROLLBACK")},isConnected(){return H}}}function f(z){let H=!1,U=null;return{async connect(){if(H)return;try{U=(await import("mysql2/promise")).createPool({host:z.host||"localhost",port:z.port||3306,database:z.database,user:z.username,password:z.password,waitForConnections:!0,connectionLimit:z.poolSize||10,queueLimit:0}),H=!0}catch(W){throw Error(`MySQL connection failed. Install 'mysql2' package: ${W}`)}},async disconnect(){if(U)await U.end(),U=null,H=!1},async query(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z}catch(Z){throw new O(`Query failed: ${Z}`,W,J)}},async insert(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.insertId}catch(Z){throw new O(`Insert failed: ${Z}`,W,J)}},async execute(W,J=[]){if(!H)await this.connect();let X=performance.now();try{let[Z]=await U.execute(W,J);if($.logging)B(W,J,performance.now()-X);return Z.affectedRows||0}catch(Z){throw new O(`Execute failed: ${Z}`,W,J)}},async beginTransaction(){if(!H)await this.connect();let W=await U.getConnection();return await W.beginTransaction(),W},async commit(){await U.execute("COMMIT")},async rollback(){await U.execute("ROLLBACK")},isConnected(){return H}}}class D{_table="";_columns=["*"];_wheres=[];_orders=[];_joins=[];_groupBy=[];_having=[];_limit;_offset;_distinct=!1;_connection;_bindings=[];_modelDefinition;constructor(z){if(z)this._table=z}table(z){return this._table=z,this}from(z){return this.table(z)}connection(z){return this._connection=z,this}select(...z){return this._columns=z.length>0?z:["*"],this}addSelect(...z){if(this._columns[0]==="*")this._columns=z;else this._columns.push(...z);return this}distinct(){return this._distinct=!0,this}where(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"and"}),this}orWhere(z,H,U){let W="=",J=H;if(U!==void 0)W=H,J=U;return this._wheres.push({column:z,operator:W,value:J,boolean:"or"}),this}whereIn(z,H){return this._wheres.push({column:z,operator:"in",value:H,boolean:"and"}),this}whereNotIn(z,H){return this._wheres.push({column:z,operator:"not in",value:H,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is null",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not null",value:null,boolean:"and"}),this}whereBetween(z,H,U){return this._wheres.push({column:z,operator:"between",value:[H,U],boolean:"and"}),this}whereLike(z,H){return this._wheres.push({column:z,operator:"like",value:H,boolean:"and"}),this}join(z,H,U,W){return this._joins.push({type:"inner",table:z,first:H,operator:U,second:W}),this}leftJoin(z,H,U,W){return this._joins.push({type:"left",table:z,first:H,operator:U,second:W}),this}rightJoin(z,H,U,W){return this._joins.push({type:"right",table:z,first:H,operator:U,second:W}),this}orderBy(z,H="asc"){return this._orders.push({column:z,direction:H}),this}orderByDesc(z){return this.orderBy(z,"desc")}groupBy(...z){return this._groupBy.push(...z),this}having(z,H,U){return this._having.push({column:z,operator:H,value:U,boolean:"and"}),this}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}forPage(z,H=15){return this.offset((z-1)*H).limit(H)}async get(){let{sql:z,bindings:H}=this.toSql();if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H),X=g(J);if(X!==void 0)return X}let W=await F(this._connection).query(z,H);if($.cacheTTL&&$.cacheTTL>0){let J=this.getCacheKey(z,H);m(J,W,$.cacheTTL)}return W}async first(){return(await this.limit(1).get())[0]||null}async firstOrFail(){let z=await this.first();if(!z)throw Error("No results found");return z}async find(z,H="id"){return this.where(H,z).first()}async value(z){let H=await this.select(z).first();return H?H[z]:null}async pluck(z){return(await this.select(z).get()).map((U)=>U[z])}async exists(){return(await this.select(E("1")).limit(1).get()).length>0}async doesntExist(){return!await this.exists()}async count(z="*"){let H=await this.select(E(`COUNT(${z}) as count`)).first();return Number(H?.count||0)}async max(z){return(await this.select(E(`MAX(${z}) as max`)).first())?.max}async min(z){return(await this.select(E(`MIN(${z}) as min`)).first())?.min}async sum(z){let H=await this.select(E(`SUM(${z}) as sum`)).first();return Number(H?.sum||0)}async avg(z){return(await this.select(E(`AVG(${z}) as avg`)).first())?.avg}async insert(z){let H=Object.keys(z),U=H.map(()=>"?").join(", "),W=Object.values(z),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES (${U})`,X=F(this._connection);return P(this._table),X.insert(J,W)}async insertAll(z){if(z.length===0)return;let H=Object.keys(z[0]),U=z.map(()=>`(${H.map(()=>"?").join(", ")})`).join(", "),W=z.flatMap((Z)=>Object.values(Z)),J=`INSERT INTO ${this._table} (${H.join(", ")}) VALUES ${U}`,X=F(this._connection);P(this._table),await X.execute(J,W)}async update(z){this._bindings=[];let H=this.buildWhereClause(),U=[...this._bindings],W=Object.keys(z).map((Y)=>`${Y} = ?`).join(", "),J=[...Object.values(z),...U],X=`UPDATE ${this._table} SET ${W}${H}`,Z=F(this._connection);return P(this._table),Z.execute(X,J)}async increment(z,H=1){this._bindings=[];let U=this.buildWhereClause(),W=`UPDATE ${this._table} SET ${z} = ${z} + ?${U}`,J=F(this._connection);return P(this._table),J.execute(W,[H,...this._bindings])}async decrement(z,H=1){return this.increment(z,-H)}async delete(){this._bindings=[];let z=this.buildWhereClause(),H=`DELETE FROM ${this._table}${z}`,U=F(this._connection);return P(this._table),U.execute(H,this._bindings)}async truncate(){let z=F(this._connection);P(this._table),await z.execute(`DELETE FROM ${this._table}`)}toSql(){this._bindings=[];let z="SELECT ";if(this._distinct)z+="DISTINCT ";z+=this._columns.map((H)=>{if(typeof H==="object"&&H.__raw)return H.sql;return H}).join(", "),z+=` FROM ${this._table}`;for(let H of this._joins)z+=` ${H.type.toUpperCase()} JOIN ${H.table} ON ${H.first} ${H.operator} ${H.second}`;if(z+=this.buildWhereClause(),this._groupBy.length>0)z+=` GROUP BY ${this._groupBy.join(", ")}`;if(this._having.length>0){let H=this._having.map((U,W)=>{let J=W===0?"":` ${U.boolean.toUpperCase()} `;return this._bindings.push(U.value),`${J}${U.column} ${U.operator} ?`});z+=` HAVING ${H.join("")}`}if(this._orders.length>0)z+=` ORDER BY ${this._orders.map((H)=>`${H.column} ${H.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)z+=` LIMIT ${this._limit}`;if(this._offset!==void 0)z+=` OFFSET ${this._offset}`;return{sql:z,bindings:this._bindings}}buildWhereClause(){if(this._wheres.length===0)return"";return this._wheres.map((H,U)=>{let W=U===0?" WHERE ":` ${H.boolean.toUpperCase()} `;switch(H.operator){case"in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} IN (${X})`}case"not in":{let J=H.value,X=J.map(()=>"?").join(", ");return this._bindings.push(...J),`${W}${H.column} NOT IN (${X})`}case"between":{let[J,X]=H.value;return this._bindings.push(J,X),`${W}${H.column} BETWEEN ? AND ?`}case"is null":return`${W}${H.column} IS NULL`;case"is not null":return`${W}${H.column} IS NOT NULL`;default:return this._bindings.push(H.value),`${W}${H.column} ${H.operator} ?`}}).join("")}getCacheKey(z,H){return`${this._table}:${z}:${JSON.stringify(H)}`}clone(){let z=new D(this._table);return z._columns=[...this._columns],z._wheres=[...this._wheres],z._orders=[...this._orders],z._joins=[...this._joins],z._groupBy=[...this._groupBy],z._having=[...this._having],z._limit=this._limit,z._offset=this._offset,z._distinct=this._distinct,z._connection=this._connection,z}}function G(z){return new D(z)}function t(z){return G(z)}function E(z,H=[]){return{__raw:!0,sql:z,bindings:H}}function n(z,H){let U=H.primaryKey||"id",W={name:z,definition:H,async find(J){let X=await G(H.table).where(U,J).first();return X?N(W,X):null},async findOrFail(J){let X=await this.find(J);if(!X)throw Error(`${z} not found with ${U} = ${J}`);return X},async all(){return(await G(H.table).get()).map((X)=>N(W,X))},async create(J){let X={...H.defaults,...J},Z=H.fillable?Object.fromEntries(Object.entries(X).filter(([_])=>H.fillable.includes(_))):X;if(H.timestamps!==!1){let _=new Date().toISOString(),R=typeof H.timestamps==="object"?H.timestamps.createdAt||"created_at":"created_at",T=typeof H.timestamps==="object"?H.timestamps.updatedAt||"updated_at":"updated_at";Z[R]=_,Z[T]=_}let Y=await G(H.table).insert(Z);return this.findOrFail(Y)},async update(J){return G(H.table).update(J)},async destroy(J){let X=Array.isArray(J)?J:[J];return G(H.table).whereIn(U,X).delete()},query(){return G(H.table)},where(J,X,Z){return this.query().where(J,X,Z)},async first(){let J=await this.query().first();return J?N(W,J):null},async get(){return(await this.query().get()).map((X)=>N(W,X))},async count(){return this.query().count()}};return A[z]=W,W}function k(z){let H=A[z];if(!H)throw Error(`Model "${z}" not defined. Use defineModel() first.`);return H}function e(z){return z in A}function N(z,H){let{definition:U}=z,W=U.primaryKey||"id",J={...H},X={...H};if(U.casts){for(let[Y,_]of Object.entries(U.casts))if(Y in X)X[Y]=p(X[Y],_)}let Z={exists:!0,original:J,attributes:X,get(Y){return X[Y]},set(Y,_){X[Y]=_},toJSON(){let Y={...X};if(U.hidden)for(let _ of U.hidden)delete Y[_];return Y},async save(){let Y={};for(let _ of Object.keys(X))if(X[_]!==J[_])Y[_]=X[_];if(Object.keys(Y).length>0){if(U.timestamps!==!1){let _=typeof U.timestamps==="object"?U.timestamps.updatedAt||"updated_at":"updated_at";Y[_]=new Date().toISOString()}await G(U.table).where(W,J[W]).update(Y),Object.assign(J,Y)}},async delete(){if(U.softDeletes){let Y=typeof U.softDeletes==="string"?U.softDeletes:"deleted_at";await G(U.table).where(W,J[W]).update({[Y]:new Date().toISOString()})}else await G(U.table).where(W,J[W]).delete();Z.exists=!1},async refresh(){let Y=await G(U.table).where(W,J[W]).first();if(Y)Object.assign(J,Y),Object.assign(X,Y)},isDirty(Y){if(Y)return X[Y]!==J[Y];return Object.keys(X).some((_)=>X[_]!==J[_])}};if(U.relationships)for(let[Y,_]of Object.entries(U.relationships))Object.defineProperty(Z,Y,{value:async()=>{return b(Z,_,z)},enumerable:!1});return new Proxy(Z,{get(Y,_){if(_ in Y)return Y[_];return X[_]},set(Y,_,R){if(_ in Y)Y[_]=R;else X[_]=R;return!0}})}async function b(z,H,U){let W=k(H.model),J=U.definition.primaryKey||"id";switch(H.type){case"hasOne":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`,Z=await G(W.definition.table).where(X,z.get(J)).first();return Z?N(W,Z):null}case"hasMany":{let X=H.foreignKey||`${U.name.toLowerCase()}_id`;return(await G(W.definition.table).where(X,z.get(J)).get()).map((Y)=>N(W,Y))}case"belongsTo":{let X=H.foreignKey||`${H.model.toLowerCase()}_id`,Z=H.localKey||"id",Y=await G(W.definition.table).where(Z,z.get(X)).first();return Y?N(W,Y):null}case"belongsToMany":{let X=H.pivotTable||[U.name,H.model].sort().join("_").toLowerCase(),Z=H.pivotForeignKey||`${U.name.toLowerCase()}_id`,Y=H.pivotRelatedKey||`${H.model.toLowerCase()}_id`,_=W.definition.primaryKey||"id";return(await G(W.definition.table).join(X,`${W.definition.table}.${_}`,"=",`${X}.${Y}`).where(`${X}.${Z}`,z.get(J)).get()).map((T)=>N(W,T))}default:return null}}function p(z,H){if(z===null||z===void 0)return z;switch(H){case"string":return String(z);case"number":return Number(z);case"boolean":return Boolean(z);case"date":return new Date(z);case"json":case"array":return typeof z==="string"?JSON.parse(z):z;default:return z}}async function zz(z,H){let U=F(H);await U.beginTransaction();try{let W=await z();return await U.commit(),W}catch(W){throw await U.rollback(),W}}function g(z){let H=L.get(z);if(!H)return;if(Date.now()-H.timestamp>H.ttl*1000){L.delete(z);return}return H.result}function m(z,H,U){if(L.size>=($.maxCacheSize||1000)){let W=L.keys().next().value;if(W)L.delete(W)}L.set(z,{result:H,timestamp:Date.now(),ttl:U})}function P(z){for(let H of L.keys())if(H.startsWith(`${z}:`))L.delete(H)}function Hz(){L.clear()}function Jz(){return{size:L.size,keys:[...L.keys()]}}function B(z,H,U){if(S.push({sql:z,bindings:H,duration:U,timestamp:new Date}),S.length>1000)S.shift()}function Uz(){return[...S]}function Wz(){S.length=0}function Xz(z=!0){$.logging=z}class O extends Error{sql;bindings;constructor(z,H,U){super(z);this.sql=H;this.bindings=U;this.name="DatabaseError"}}async function u(z,H,U,W){let J=/@db\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=await s(R,T),I=`$${R}`;H[I]=j,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- DB Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function d(z,H,U,W){let J=/@model\(\s*['"]([^'"]+)['"]\s*\)((?:->\w+\([^)]*\))*)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T]=Y;try{let j=k(R),I=await l(j,T),K=`$${R.toLowerCase()}`;H[K]=I,X=X.replace(_,"")}catch(j){X=X.replace(_,`<!-- Model Error: ${j instanceof Error?j.message:String(j)} -->`)}}return X}async function c(z,H,U,W){let J=/@query\(\s*['"]([^'"]+)['"]\s*(?:,\s*(\[[^\]]*\]))?\s*\)\s*as\s+\$(\w+)/g,X=z,Z=[...z.matchAll(J)];for(let Y of Z){let[_,R,T,j]=Y;try{let I=T?JSON.parse(T):[],v=await F().query(R,I);H[`$${j}`]=v,X=X.replace(_,"")}catch(I){X=X.replace(_,`<!-- Query Error: ${I instanceof Error?I.message:String(I)} -->`)}}return X}async function s(z,H){let U=G(z),W=/->(\w+)\(([^)]*)\)/g,J=[...H.matchAll(W)],X=U;for(let[,Z,Y]of J){let _=M(Y);if(typeof X[Z]==="function"){if(X=X[Z](..._),X instanceof Promise){X=await X;break}}}if(X instanceof D)X=await X.get();return X}async function l(z,H){let U=/->(\w+)\(([^)]*)\)/g,W=[...H.matchAll(U)],J=z;for(let[,X,Z]of W){let Y=M(Z);if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}else if(J instanceof D){if(typeof J[X]==="function"){if(J=J[X](...Y),J instanceof Promise)J=await J}}}if(J instanceof D)J=await J.get();return J}function M(z){if(!z.trim())return[];let H=[],U="",W=0,J=!1,X="";for(let Z=0;Z<z.length;Z++){let Y=z[Z];if(!J&&(Y==='"'||Y==="'"))J=!0,X=Y,U+=Y;else if(J&&Y===X)J=!1,U+=Y;else if(!J&&(Y==="["||Y==="{"||Y==="("))W++,U+=Y;else if(!J&&(Y==="]"||Y==="}"||Y===")"))W--,U+=Y;else if(!J&&W===0&&Y===",")H.push(x(U.trim())),U="";else U+=Y}if(U.trim())H.push(x(U.trim()));return H}function x(z){if(z.startsWith('"')&&z.endsWith('"')||z.startsWith("'")&&z.endsWith("'"))return z.slice(1,-1);if(z==="true")return!0;if(z==="false")return!1;if(z==="null")return null;let H=Number(z);if(!Number.isNaN(H))return H;try{return JSON.parse(z)}catch{return z}}async function Yz(z,H,U,W){let J=z;return J=await c(J,H,U,W),J=await d(J,H,U,W),J=await u(J,H,U,W),J}class w{_connection;connection(z){return this._connection=z,this}async create(z,H){let U=new C(z);H(U);let W=U.toCreateSQL();await F(this._connection).execute(W)}async drop(z){await F(this._connection).execute(`DROP TABLE IF EXISTS ${z}`)}async rename(z,H){await F(this._connection).execute(`ALTER TABLE ${z} RENAME TO ${H}`)}async hasTable(z){let H=F(this._connection);try{return await H.query(`SELECT 1 FROM ${z} LIMIT 1`),!0}catch{return!1}}}class C{table;columns=[];indices=[];constructor(z){this.table=z}id(z="id"){return this.columns.push(`${z} INTEGER PRIMARY KEY AUTOINCREMENT`),this}string(z,H=255){return this.columns.push(`${z} VARCHAR(${H})`),this}text(z){return this.columns.push(`${z} TEXT`),this}integer(z){return this.columns.push(`${z} INTEGER`),this}boolean(z){return this.columns.push(`${z} BOOLEAN DEFAULT 0`),this}datetime(z){return this.columns.push(`${z} DATETIME`),this}timestamps(){return this.columns.push("created_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this.columns.push("updated_at DATETIME DEFAULT CURRENT_TIMESTAMP"),this}softDeletes(){return this.columns.push("deleted_at DATETIME"),this}json(z){return this.columns.push(`${z} TEXT`),this}foreignId(z){return this.columns.push(`${z} INTEGER`),this}index(z){let H=Array.isArray(z)?z:[z],U=`idx_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}unique(z){let H=Array.isArray(z)?z:[z],U=`uniq_${this.table}_${H.join("_")}`;return this.indices.push(`CREATE UNIQUE INDEX ${U} ON ${this.table} (${H.join(", ")})`),this}toCreateSQL(){return`CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
3
3
|
${this.columns.join(`,
|
|
4
4
|
`)}
|
|
5
5
|
)`}getIndexSQL(){return this.indices}}function Zz(){return new w}export{zz as transaction,t as table,Zz as schema,r as resetDatabaseConfig,a as registerAdapter,E as raw,G as query,c as processQueryDirective,d as processModelDirective,u as processDbDirective,Yz as processDatabaseDirectives,e as hasModel,Uz as getQueryLog,Jz as getQueryCacheStats,k as getModel,o as getDatabaseConfig,F as getAdapter,Xz as enableQueryLogging,n as defineModel,i as configureDatabase,Wz as clearQueryLog,Hz as clearQueryCache,w as SchemaBuilder,D as QueryBuilder,O as DatabaseError,C as Blueprint};
|