@protobase/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +202 -0
  2. package/bin/protobase.mjs +4 -0
  3. package/dist/build/config-bundle.js +70 -0
  4. package/dist/build/deploy-bundle.js +42 -0
  5. package/dist/build/entry-code.js +23 -0
  6. package/dist/build/layout-check.js +50 -0
  7. package/dist/build/packages/binary-platform.js +81 -0
  8. package/dist/build/packages/copy-packages.js +59 -0
  9. package/dist/build/packages/host-packages.js +37 -0
  10. package/dist/build/packages/native-package.js +22 -0
  11. package/dist/build/packages/package-dir.js +32 -0
  12. package/dist/build/packages/package-tree.js +53 -0
  13. package/dist/build/packages/targets.js +38 -0
  14. package/dist/build/serve-runtime.js +16 -0
  15. package/dist/build/ui-bundle.js +33 -0
  16. package/dist/build/vite-bundle.js +36 -0
  17. package/dist/bundle/manifest.js +35 -0
  18. package/dist/db/connect.js +18 -0
  19. package/dist/db/introspect.js +47 -0
  20. package/dist/db/keys.js +15 -0
  21. package/dist/db/model.js +4 -0
  22. package/dist/db/queries.js +62 -0
  23. package/dist/dev/check-database.js +38 -0
  24. package/dist/dev/create-db.js +13 -0
  25. package/dist/dev/entry.d.ts +4 -0
  26. package/dist/dev/entry.js +32 -0
  27. package/dist/dev/env.js +15 -0
  28. package/dist/dev/hosts.js +4 -0
  29. package/dist/dev/project.js +39 -0
  30. package/dist/dev/run.js +88 -0
  31. package/dist/doctor/check.js +76 -0
  32. package/dist/doctor/load-config.js +10 -0
  33. package/dist/doctor/run.js +22 -0
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +2 -0
  36. package/dist/infer/check-values.js +14 -0
  37. package/dist/infer/compat.js +17 -0
  38. package/dist/infer/default-column.js +12 -0
  39. package/dist/infer/defaults.js +28 -0
  40. package/dist/infer/names.js +28 -0
  41. package/dist/infer/proposal.js +68 -0
  42. package/dist/infer/render-field.js +26 -0
  43. package/dist/infer/tenant.js +5 -0
  44. package/dist/infer/type-map.js +52 -0
  45. package/dist/main.d.ts +4 -0
  46. package/dist/main.js +84 -0
  47. package/dist/module-file.js +6 -0
  48. package/dist/package.js +4 -0
  49. package/dist/project/admin-app.js +9 -0
  50. package/dist/project/convention.js +8 -0
  51. package/dist/project/import-project-file.js +6 -0
  52. package/dist/project/pg-db.js +11 -0
  53. package/dist/project/project-ui.js +17 -0
  54. package/dist/scaffold/data-file.js +44 -0
  55. package/dist/scaffold/drift.js +30 -0
  56. package/dist/scaffold/existing-config.js +95 -0
  57. package/dist/scaffold/index-file.js +18 -0
  58. package/dist/scaffold/plan.js +128 -0
  59. package/dist/scaffold/project.js +13 -0
  60. package/dist/scaffold/prompt.js +70 -0
  61. package/dist/scaffold/resource-names.js +19 -0
  62. package/dist/scaffold/resource-plan.js +33 -0
  63. package/dist/scaffold/run.js +53 -0
  64. package/dist/scaffold/targets.js +15 -0
  65. package/dist/scaffold/ui-fields.js +30 -0
  66. package/dist/scaffold/ui-file.js +40 -0
  67. package/dist/serve/app.js +30 -0
  68. package/dist/serve/bundle-version.js +16 -0
  69. package/dist/serve/env.js +13 -0
  70. package/dist/serve/host-module-ids.js +21 -0
  71. package/dist/serve/host-modules.js +49 -0
  72. package/dist/serve/lifecycle.js +39 -0
  73. package/dist/serve/load-bundle.js +17 -0
  74. package/dist/serve/main.d.ts +1 -0
  75. package/dist/serve/main.js +13 -0
  76. package/dist/serve/serve-bundle.js +21 -0
  77. package/dist/serve/serve-dir.js +15 -0
  78. package/dist/serve/signals.js +11 -0
  79. package/dist/serve/static-site.js +46 -0
  80. package/dist/users/commands.js +31 -0
  81. package/dist/users/load-auth.js +15 -0
  82. package/dist/users/manage.js +21 -0
  83. package/dist/users/password.js +64 -0
  84. package/dist/users/register.js +94 -0
  85. package/dist/users/ttl.js +16 -0
  86. package/dist/version/compatibility.js +31 -0
  87. package/dist/version/version.js +5 -0
  88. package/package.json +55 -3
  89. package/README.md +0 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../dist/index.js'
3
+
4
+ await run(process.argv)
@@ -0,0 +1,70 @@
1
+ import { hostModuleIds } from "../serve/host-module-ids.js";
2
+ import { bundleEntryCode } from "./entry-code.js";
3
+ import { layoutCheck } from "./layout-check.js";
4
+ import { findPackageDir, packageName } from "./packages/package-dir.js";
5
+ import { hostPackages, hostVersionProblem } from "./packages/host-packages.js";
6
+ import { isNativePackage } from "./packages/native-package.js";
7
+ import { viteBundle } from "./vite-bundle.js";
8
+ import path from "node:path";
9
+ //#region src/build/config-bundle.ts
10
+ const isHostModule = (id) => hostModuleIds.includes(id);
11
+ const entry = (file, code) => ({
12
+ name: "protobase-config-entry",
13
+ resolveId: (id) => id === file ? `\0${file}` : void 0,
14
+ load: (id) => id === `\0${file}` ? code : void 0
15
+ });
16
+ const importerDir = (importer) => path.dirname(importer.replace(/^\0/, "").replace(/\?.*$/, ""));
17
+ const servedImports = (native) => {
18
+ const checked = /* @__PURE__ */ new Map();
19
+ const isNative = (dir) => {
20
+ if (!checked.has(dir)) checked.set(dir, isNativePackage(dir));
21
+ return checked.get(dir);
22
+ };
23
+ return {
24
+ name: "protobase-served-imports",
25
+ enforce: "pre",
26
+ async resolveId(id, importer) {
27
+ const name = packageName(id);
28
+ if (name === void 0 || importer === void 0) return void 0;
29
+ const from = importerDir(importer);
30
+ if (hostPackages.has(name)) {
31
+ if (!isHostModule(id)) this.error(`${id} is not available to a served config; of the @protobase packages and their dependencies it may import ${hostModuleIds.join(", ")}`);
32
+ const problem = await hostVersionProblem(name, from);
33
+ if (problem) this.error(problem);
34
+ return {
35
+ id,
36
+ external: true
37
+ };
38
+ }
39
+ const dir = await findPackageDir(name, from);
40
+ if (dir === void 0 || !await isNative(dir)) return void 0;
41
+ const other = native.get(name);
42
+ if (other && other.dir !== dir) this.error(`The config imports two installs of ${name}, a native package: ${other.dir} and ${dir}`);
43
+ native.set(name, {
44
+ name,
45
+ dir
46
+ });
47
+ return {
48
+ id,
49
+ external: true
50
+ };
51
+ }
52
+ };
53
+ };
54
+ const buildConfigBundle = async ({ projectDir, outFile }) => {
55
+ const file = path.join(projectDir, "protobase-bundle-entry.js");
56
+ const native = /* @__PURE__ */ new Map();
57
+ await viteBundle({
58
+ root: projectDir,
59
+ entry: file,
60
+ outFile,
61
+ plugins: [
62
+ layoutCheck(),
63
+ servedImports(native),
64
+ entry(file, bundleEntryCode(projectDir))
65
+ ]
66
+ });
67
+ return [...native.values()];
68
+ };
69
+ //#endregion
70
+ export { buildConfigBundle };
@@ -0,0 +1,42 @@
1
+ import { bundleLayout, bundleNodeModules, manifestFile } from "../bundle/manifest.js";
2
+ import { buildConfigBundle } from "./config-bundle.js";
3
+ import { protobaseVersion } from "../version/version.js";
4
+ import { copyPackages } from "./packages/copy-packages.js";
5
+ import { buildUiBundle } from "./ui-bundle.js";
6
+ import { existsSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { readFile, rm, writeFile } from "node:fs/promises";
9
+ //#region src/build/deploy-bundle.ts
10
+ const removeOwnNodeModules = async (outDir) => {
11
+ const dir = path.join(outDir, bundleNodeModules);
12
+ if (!existsSync(dir)) return;
13
+ const manifest = path.join(outDir, manifestFile);
14
+ if ((existsSync(manifest) ? JSON.parse(await readFile(manifest, "utf8")) : void 0)?.nodeModules !== "node_modules") throw new Error(`${dir} was not written by \`protobase build\`; build into another folder (--out)`);
15
+ await rm(dir, {
16
+ recursive: true,
17
+ force: true
18
+ });
19
+ };
20
+ const buildDeployBundle = async ({ projectDir, outDir }) => {
21
+ await removeOwnNodeModules(outDir);
22
+ const native = await buildConfigBundle({
23
+ projectDir,
24
+ outFile: path.join(outDir, bundleLayout.server)
25
+ });
26
+ const packages = native.length > 0 ? await copyPackages(native, path.join(outDir, bundleNodeModules)) : [];
27
+ await buildUiBundle({
28
+ outDir: path.join(outDir, bundleLayout.public),
29
+ projectDir
30
+ });
31
+ const manifest = {
32
+ version: 2,
33
+ protobase: protobaseVersion,
34
+ ...bundleLayout,
35
+ api: [...bundleLayout.api],
36
+ ...packages.length > 0 ? { nodeModules: bundleNodeModules } : {}
37
+ };
38
+ await writeFile(path.join(outDir, manifestFile), `${JSON.stringify(manifest, null, 2)}\n`);
39
+ return manifest;
40
+ };
41
+ //#endregion
42
+ export { buildDeployBundle };
@@ -0,0 +1,23 @@
1
+ import { moduleFile } from "../module-file.js";
2
+ import { existsSync, readdirSync } from "node:fs";
3
+ import path from "node:path";
4
+ //#region src/build/entry-code.ts
5
+ const conventionModule = moduleFile("../project/convention", import.meta.url);
6
+ const uiDirs = (configDir) => readdirSync(configDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(configDir, entry.name, "ui.ts"))).map((entry) => entry.name).sort();
7
+ const bundleEntryCode = (projectDir) => {
8
+ const custom = path.join(projectDir, "protobase.config.ts");
9
+ const configDir = path.join(projectDir, "config");
10
+ const index = path.join(configDir, "index.ts");
11
+ const hasCustom = existsSync(custom);
12
+ const hasIndex = existsSync(index);
13
+ if (!hasCustom && !hasIndex) throw new Error(`No protobase.config.ts or config/index.ts in ${projectDir}`);
14
+ const lines = hasCustom ? [`import * as custom from ${JSON.stringify(custom)}`, "const project = custom.default ?? {}"] : ["const project = {}"];
15
+ if (hasIndex) {
16
+ const dirs = uiDirs(configDir);
17
+ lines.push(`import { conventionConfig } from ${JSON.stringify(conventionModule)}`, `import * as index from ${JSON.stringify(index)}`, ...dirs.map((dir, i) => `import * as ui${i} from ${JSON.stringify(path.join(configDir, dir, "ui.ts"))}`), `const convention = conventionConfig(index, [${dirs.map((dir, i) => `[${JSON.stringify(dir)}, ui${i}]`).join(", ")}])`);
18
+ } else lines.push("const convention = undefined");
19
+ lines.push("export default { ...project, config: project.config ?? convention }");
20
+ return `${lines.join("\n")}\n`;
21
+ };
22
+ //#endregion
23
+ export { bundleEntryCode };
@@ -0,0 +1,50 @@
1
+ import { ts } from "ts-morph";
2
+ //#region src/build/layout-check.ts
3
+ const pragma = /@jsxImportSource\s+@protobase\/layout\b/;
4
+ const isLayoutSource = (code) => pragma.test(code);
5
+ const elementName = (node) => {
6
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) return node.tagName.getText();
7
+ return node.parent ? elementName(node.parent) : "element";
8
+ };
9
+ const what = (expression) => {
10
+ const inner = ts.isParenthesizedExpression(expression) ? expression.expression : expression;
11
+ if (ts.isArrowFunction(inner) || ts.isFunctionExpression(inner)) return "a function";
12
+ if (ts.isClassExpression(inner)) return "a class";
13
+ if (ts.isNewExpression(inner)) return `a new ${inner.expression.getText()}`;
14
+ };
15
+ const isHookCall = (node) => ts.isCallExpression(node) && /^use[A-Z]/.test(ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : node.expression.getText());
16
+ /** Every place in a layout file where JSX gets a value that cannot be static, and every hook call. */
17
+ const layoutProblems = (code, file) => {
18
+ const source = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
19
+ const problems = [];
20
+ const at = (node) => {
21
+ const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source));
22
+ return `${file}:${line + 1}:${character + 1}`;
23
+ };
24
+ const visit = (node) => {
25
+ if (ts.isJsxAttribute(node) && node.initializer && ts.isJsxExpression(node.initializer) && node.initializer.expression) {
26
+ const kind = what(node.initializer.expression);
27
+ if (kind) problems.push(`${at(node)}: <${elementName(node)} ${node.name.getText()}> is ${kind}; layout props must be static data. Use <Action name="..."> for behaviour, or a custom component for React code.`);
28
+ }
29
+ if (ts.isJsxExpression(node) && node.expression && (ts.isJsxElement(node.parent) || ts.isJsxFragment(node.parent))) {
30
+ const kind = what(node.expression);
31
+ if (kind) problems.push(`${at(node)}: a child of <${ts.isJsxElement(node.parent) ? node.parent.openingElement.tagName.getText() : ""}> is ${kind}; layout children must be elements or text.`);
32
+ }
33
+ if (isHookCall(node)) problems.push(`${at(node)}: ${node.expression.getText()}() is a hook; layouts have no state. Put stateful UI in a custom component.`);
34
+ ts.forEachChild(node, visit);
35
+ };
36
+ visit(source);
37
+ return problems;
38
+ };
39
+ /** Fails the config bundle on the first layout file with problems, listing all of them. */
40
+ const layoutCheck = () => ({
41
+ name: "protobase-layout-check",
42
+ enforce: "pre",
43
+ transform(code, id) {
44
+ if (!/\.[jt]sx$/.test(id) || id.includes("/node_modules/") || !isLayoutSource(code)) return void 0;
45
+ const problems = layoutProblems(code, id);
46
+ if (problems.length > 0) this.error(`Layout ${id} is not static:\n${problems.map((problem) => ` - ${problem}`).join("\n")}`);
47
+ }
48
+ });
49
+ //#endregion
50
+ export { isLayoutSource, layoutCheck, layoutProblems };
@@ -0,0 +1,81 @@
1
+ //#region src/build/packages/binary-platform.ts
2
+ const elfMachines = {
3
+ 3: "ia32",
4
+ 40: "arm",
5
+ 62: "x64",
6
+ 183: "arm64",
7
+ 243: "riscv64"
8
+ };
9
+ const machoCpus = {
10
+ 16777223: "x64",
11
+ 16777228: "arm64"
12
+ };
13
+ const peMachines = {
14
+ 332: "ia32",
15
+ 34404: "x64",
16
+ 43620: "arm64"
17
+ };
18
+ const ptLoad = 1;
19
+ const ptDynamic = 2;
20
+ const dtNeeded = 1;
21
+ const dtStrtab = 5;
22
+ const fits = (bytes, offset, length) => offset >= 0 && offset + length <= bytes.length;
23
+ const cString = (bytes, offset) => {
24
+ const end = bytes.indexOf(0, offset);
25
+ return bytes.toString("latin1", offset, end < 0 ? bytes.length : end);
26
+ };
27
+ const elfNeeded = (bytes) => {
28
+ const phoff = Number(bytes.readBigUInt64LE(32));
29
+ const phentsize = bytes.readUInt16LE(54);
30
+ const phnum = bytes.readUInt16LE(56);
31
+ if (phentsize < 40 || !fits(bytes, phoff, phentsize * phnum)) return [];
32
+ const segments = Array.from({ length: phnum }, (_, i) => {
33
+ const at = phoff + i * phentsize;
34
+ return {
35
+ type: bytes.readUInt32LE(at),
36
+ offset: Number(bytes.readBigUInt64LE(at + 8)),
37
+ vaddr: Number(bytes.readBigUInt64LE(at + 16)),
38
+ size: Number(bytes.readBigUInt64LE(at + 32))
39
+ };
40
+ });
41
+ const dynamic = segments.find((segment) => segment.type === ptDynamic);
42
+ if (!dynamic || !fits(bytes, dynamic.offset, dynamic.size)) return [];
43
+ const entries = Array.from({ length: Math.floor(dynamic.size / 16) }, (_, i) => ({
44
+ tag: bytes.readBigUInt64LE(dynamic.offset + i * 16),
45
+ value: Number(bytes.readBigUInt64LE(dynamic.offset + i * 16 + 8))
46
+ }));
47
+ const strtab = entries.find((entry) => entry.tag === BigInt(dtStrtab))?.value;
48
+ const load = segments.find((segment) => segment.type === ptLoad && strtab !== void 0 && strtab >= segment.vaddr && strtab < segment.vaddr + segment.size);
49
+ if (strtab === void 0 || !load) return [];
50
+ const strings = strtab - load.vaddr + load.offset;
51
+ return entries.filter((entry) => entry.tag === BigInt(dtNeeded) && fits(bytes, strings + entry.value, 1)).map((entry) => cString(bytes, strings + entry.value));
52
+ };
53
+ const isElf64le = (bytes) => bytes.length >= 64 && bytes.toString("latin1", 0, 4) === "ELF" && bytes[4] === 2 && bytes[5] === 1;
54
+ const binaryLibraries = (bytes) => isElf64le(bytes) ? elfNeeded(bytes) : [];
55
+ const elfPlatform = (bytes) => {
56
+ const os = bytes[7] === 9 ? "freebsd" : "linux";
57
+ const bigEndian = bytes[5] === 2;
58
+ const machine = bytes.length < 20 ? void 0 : bigEndian ? bytes.readUInt16BE(18) : bytes.readUInt16LE(18);
59
+ const arch = machine !== void 0 && elfMachines[machine] || "other";
60
+ if (!isElf64le(bytes)) return `${os}-${arch}`;
61
+ return `${os}-${arch}${elfNeeded(bytes).some((library) => library === "libc.so" || library.includes("musl")) ? "-musl" : ""}`;
62
+ };
63
+ const machoPlatform = (bytes) => {
64
+ const magic = bytes.readUInt32BE(0);
65
+ if ((magic === 3405691582 || magic === 3405691583) && bytes.readUInt32BE(4) < 20) return "darwin-universal";
66
+ if (magic === 3489328638 || magic === 3472551422) return `darwin-${machoCpus[bytes.readUInt32LE(4)] ?? "other"}`;
67
+ if (magic === 4277009103 || magic === 4277009102) return `darwin-${machoCpus[bytes.readUInt32BE(4)] ?? "other"}`;
68
+ };
69
+ const pePlatform = (bytes) => {
70
+ if (bytes.length < 64 || bytes.toString("latin1", 0, 2) !== "MZ") return void 0;
71
+ const header = bytes.readUInt32LE(60);
72
+ if (!fits(bytes, header, 6) || bytes.toString("latin1", header, header + 4) !== "PE\0\0") return void 0;
73
+ return `win32-${peMachines[bytes.readUInt16LE(header + 4)] ?? "other"}`;
74
+ };
75
+ const binaryPlatform = (bytes) => {
76
+ if (bytes.length < 8) return void 0;
77
+ if (bytes.toString("latin1", 0, 4) === "ELF") return elfPlatform(bytes);
78
+ return machoPlatform(bytes) ?? pePlatform(bytes);
79
+ };
80
+ //#endregion
81
+ export { binaryLibraries, binaryPlatform };
@@ -0,0 +1,59 @@
1
+ import { packageFiles } from "./package-dir.js";
2
+ import { bundleTargets, isPlatformPackage, isTarget, runImageLibraries } from "./targets.js";
3
+ import { hasAddonFile, platformPackages } from "./native-package.js";
4
+ import { binaryLibraries, binaryPlatform } from "./binary-platform.js";
5
+ import { packageTree } from "./package-tree.js";
6
+ import path from "node:path";
7
+ import { copyFile, mkdir, readFile } from "node:fs/promises";
8
+ //#region src/build/packages/copy-packages.ts
9
+ const readFiles = async (dir) => Promise.all((await packageFiles(dir)).map(async (file) => {
10
+ const bytes = await readFile(path.join(dir, file));
11
+ return {
12
+ file,
13
+ platform: binaryPlatform(bytes),
14
+ libraries: binaryLibraries(bytes)
15
+ };
16
+ }));
17
+ const shipped = (files) => files.filter(({ platform }) => platform === void 0 || isTarget(platform));
18
+ const label = (pkg) => `${pkg.json.name ?? pkg.name} ${pkg.json.version ?? ""}`.trim();
19
+ const addonProblem = async (pkg, filesOf) => {
20
+ if (isPlatformPackage(pkg.json)) return void 0;
21
+ const own = await filesOf(pkg.dir);
22
+ const platforms = await platformPackages(pkg.dir, pkg.json);
23
+ if (!hasAddonFile(own.map(({ file }) => file)) && platforms.length === 0) return void 0;
24
+ const files = [own, ...await Promise.all(platforms.map((dep) => filesOf(dep.dir)))].flat();
25
+ const found = new Set(files.flatMap(({ file, platform }) => file.endsWith(".node") && platform ? [platform] : []));
26
+ const missing = bundleTargets.filter((target) => !found.has(target));
27
+ if (missing.length === 0) return void 0;
28
+ return `${label(pkg)}: no add-on for ${missing.join(" or ")} (found ${[...found].sort().join(", ") || "none"})`;
29
+ };
30
+ const libraryProblems = (pkg, files, bundled) => shipped(files).flatMap(({ file, libraries }) => {
31
+ const missing = libraries.filter((library) => !runImageLibraries.has(library) && !bundled.has(library));
32
+ return missing.length === 0 ? [] : [`${label(pkg)}: ${file} needs ${missing.join(", ")}, which neither the run image nor the bundle has`];
33
+ });
34
+ const refusal = (problems) => [
35
+ `Native add-ons need binaries for ${bundleTargets.join(" and ")} (glibc), linking only what the run image or the bundle has:`,
36
+ ...problems.map((problem) => ` ${problem}`),
37
+ "A package that builds or downloads its add-on on install (node-gyp, prebuild-install) only has the build machine's;",
38
+ "one with per-platform packages needs the linux ones installed (pnpm: supportedArchitectures). See https://docs.protobase.net/reference/cli/#native-packages."
39
+ ].join("\n");
40
+ const copyPackages = async (imports, nodeModulesDir) => {
41
+ const tree = await packageTree(imports);
42
+ const read = /* @__PURE__ */ new Map();
43
+ const filesOf = (dir) => {
44
+ if (!read.has(dir)) read.set(dir, readFiles(dir));
45
+ return read.get(dir);
46
+ };
47
+ const files = await Promise.all(tree.map((pkg) => filesOf(pkg.dir)));
48
+ const bundled = new Set(files.flatMap((list) => shipped(list).map(({ file }) => path.basename(file))));
49
+ const problems = [...(await Promise.all(tree.map((pkg) => addonProblem(pkg, filesOf)))).filter((problem) => problem !== void 0), ...tree.flatMap((pkg, i) => libraryProblems(pkg, files[i], bundled))];
50
+ if (problems.length > 0) throw new Error(refusal(problems));
51
+ for (const [i, pkg] of tree.entries()) for (const { file } of shipped(files[i])) {
52
+ const target = path.join(nodeModulesDir, pkg.dest, file);
53
+ await mkdir(path.dirname(target), { recursive: true });
54
+ await copyFile(path.join(pkg.dir, file), target);
55
+ }
56
+ return tree;
57
+ };
58
+ //#endregion
59
+ export { copyPackages };
@@ -0,0 +1,37 @@
1
+ import { findPackageDir, findPackageDirSync, readPackageJson } from "./package-dir.js";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ //#region src/build/packages/host-packages.ts
6
+ const cliRoot = fileURLToPath(new URL("../../..", import.meta.url));
7
+ const collectHostPackages = () => {
8
+ const declaredIn = /* @__PURE__ */ new Map([["@protobase/cli", cliRoot]]);
9
+ const visit = (dir) => {
10
+ const manifest = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
11
+ for (const name of Object.keys(manifest.dependencies ?? {})) {
12
+ if (declaredIn.has(name)) continue;
13
+ declaredIn.set(name, dir);
14
+ if (!name.startsWith("@protobase/")) continue;
15
+ const found = findPackageDirSync(name, dir);
16
+ if (!found) throw new Error(`${name} is not installed; reinstall @protobase/cli`);
17
+ visit(found);
18
+ }
19
+ };
20
+ visit(cliRoot);
21
+ return declaredIn;
22
+ };
23
+ const declaredIn = collectHostPackages();
24
+ const hostPackages = new Set(declaredIn.keys());
25
+ const releaseLine = (version = "") => {
26
+ const [major, minor] = version.split(".");
27
+ return major === "0" ? `0.${minor}` : major;
28
+ };
29
+ const hostVersionProblem = async (name, importerDir) => {
30
+ const [projectDir, ownDir] = await Promise.all([findPackageDir(name, importerDir), findPackageDir(name, declaredIn.get(name) ?? cliRoot)]);
31
+ if (!projectDir || !ownDir || projectDir === ownDir) return void 0;
32
+ const [project, own] = await Promise.all([readPackageJson(projectDir), readPackageJson(ownDir)]);
33
+ if (releaseLine(project.version) === releaseLine(own.version)) return void 0;
34
+ return `${name} ${project.version} is installed here, but the serve runtime supplies ${name} ${own.version}; use a version compatible with it`;
35
+ };
36
+ //#endregion
37
+ export { hostPackages, hostVersionProblem };
@@ -0,0 +1,22 @@
1
+ import { findPackageDir, packageFiles, readPackageJson } from "./package-dir.js";
2
+ import { isPlatformPackage } from "./targets.js";
3
+ //#region src/build/packages/native-package.ts
4
+ const hasAddonFile = (files) => files.some((file) => file.endsWith(".node") || file === "binding.gyp");
5
+ const platformPackages = async (dir, json) => {
6
+ const names = Object.keys(json.optionalDependencies ?? {});
7
+ if (!names.some((name) => name.includes("linux"))) return [];
8
+ return (await Promise.all(names.map(async (name) => {
9
+ const found = await findPackageDir(name, dir);
10
+ return found ? [{
11
+ name,
12
+ dir: found,
13
+ json: await readPackageJson(found)
14
+ }] : [];
15
+ }))).flat().filter((dep) => isPlatformPackage(dep.json));
16
+ };
17
+ const isNativePackage = async (dir) => {
18
+ if (hasAddonFile(await packageFiles(dir))) return true;
19
+ return (await platformPackages(dir, await readPackageJson(dir))).length > 0;
20
+ };
21
+ //#endregion
22
+ export { hasAddonFile, isNativePackage, platformPackages };
@@ -0,0 +1,32 @@
1
+ import { isBuiltin } from "node:module";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { readFile, readdir, stat } from "node:fs/promises";
5
+ //#region src/build/packages/package-dir.ts
6
+ const packageName = (id) => {
7
+ if (isBuiltin(id) || /^[./\\\0]|^[a-z]+:/i.test(id)) return void 0;
8
+ const [first, second] = id.split("/");
9
+ if (!first.startsWith("@")) return first;
10
+ return second ? `${first}/${second}` : void 0;
11
+ };
12
+ const findPackageDirSync = (name, fromDir) => {
13
+ for (let dir = fromDir;; dir = path.dirname(dir)) {
14
+ const candidate = path.join(dir, "node_modules", name);
15
+ if (path.basename(dir) !== "node_modules" && existsSync(path.join(candidate, "package.json"))) return realpathSync(candidate);
16
+ if (path.dirname(dir) === dir) return void 0;
17
+ }
18
+ };
19
+ const findPackageDir = async (name, fromDir) => findPackageDirSync(name, fromDir);
20
+ const readPackageJson = async (dir) => JSON.parse(await readFile(path.join(dir, "package.json"), "utf8"));
21
+ const packageFiles = async (dir, sub = "") => {
22
+ const entries = await readdir(path.join(dir, sub), { withFileTypes: true });
23
+ return (await Promise.all(entries.map(async (entry) => {
24
+ const file = path.join(sub, entry.name);
25
+ if (entry.name === "node_modules") return [];
26
+ const kind = entry.isSymbolicLink() ? await stat(path.join(dir, file)) : entry;
27
+ if (kind.isDirectory()) return packageFiles(dir, file);
28
+ return kind.isFile() ? [file] : [];
29
+ }))).flat();
30
+ };
31
+ //#endregion
32
+ export { findPackageDir, findPackageDirSync, packageFiles, packageName, readPackageJson };