@hybridly/vite 0.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const path = require('node:path');
6
+ const vite = require('vite');
7
+ const makeDebugger = require('debug');
8
+ const fs = require('node:fs');
9
+ const throttleDebounce = require('throttle-debounce');
10
+ const node_child_process = require('node:child_process');
11
+ const node_util = require('node:util');
12
+
13
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
14
+
15
+ const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
16
+ const makeDebugger__default = /*#__PURE__*/_interopDefaultLegacy(makeDebugger);
17
+ const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
18
+
19
+ const ROUTER_PLUGIN_NAME = "vite:hybridly:router";
20
+ const ROUTER_HMR_UPDATE_ROUTE = "hybridly:routes:update";
21
+ const ROUTER_VIRTUAL_MODULE_ID = "virtual:hybridly/router";
22
+ const RESOLVED_ROUTER_VIRTUAL_MODULE_ID = `\0${ROUTER_VIRTUAL_MODULE_ID}`;
23
+ const LAYOUT_PLUGIN_NAME = "vite:hybridly:layout";
24
+
25
+ const debug = {
26
+ router: makeDebugger__default(ROUTER_PLUGIN_NAME),
27
+ layout: makeDebugger__default(LAYOUT_PLUGIN_NAME)
28
+ };
29
+
30
+ const TEMPLATE_LAYOUT_REGEX = /<template +layout(?: *= *['"](?:(?:(\w+):)?(\w+))['"] *)?>/;
31
+ const TYPESCRIPT_REGEX = /lang=['"]ts['"]/;
32
+ const layout = (options = {}) => {
33
+ const base = options?.directory ? options?.directory : path__default.resolve(process.cwd(), "resources", "views", "layouts");
34
+ const layoutPath = options?.resolve ? options.resolve : (layoutName) => vite.normalizePath(path__default.resolve(base, `${layoutName ?? "default"}.vue`)).replaceAll("\\", "/");
35
+ debug.layout("Registered layout path:", base);
36
+ return {
37
+ name: LAYOUT_PLUGIN_NAME,
38
+ transform: (code, id) => {
39
+ if (!TEMPLATE_LAYOUT_REGEX.test(code)) {
40
+ return;
41
+ }
42
+ return code.replace(TEMPLATE_LAYOUT_REGEX, (_, __, layoutName) => {
43
+ const isTypeScript = TYPESCRIPT_REGEX.test(code);
44
+ const importPath = layoutPath(layoutName);
45
+ debug.layout(`Resolved layout "${layoutName}":`, {
46
+ sourceFile: id,
47
+ importPath
48
+ });
49
+ return `
50
+ <script${isTypeScript ? ' lang="ts"' : ""}>
51
+ import layout from '${importPath}'
52
+ export default { layout }
53
+ <\/script>
54
+ <template>
55
+ `;
56
+ });
57
+ }
58
+ };
59
+ };
60
+
61
+ function getClientCode(routes) {
62
+ return `
63
+ if (typeof window !== 'undefined') {
64
+ window.hybridly = {
65
+ routes: ${JSON.stringify(routes)}
66
+ }
67
+
68
+ if (import.meta.hot) {
69
+ import.meta.hot.on('${ROUTER_HMR_UPDATE_ROUTE}', (routes) => {
70
+ window.dispatchEvent(
71
+ new CustomEvent('hybridly:routes', { detail: routes })
72
+ )
73
+ })
74
+ }
75
+ }
76
+ `;
77
+ }
78
+
79
+ const shell = node_util.promisify(node_child_process.exec);
80
+ async function fetchRoutesFromArtisan(options) {
81
+ const php = options.php ?? "php";
82
+ const result = await shell(`${php} artisan hybridly:routes`);
83
+ const routes = JSON.parse(result.stdout);
84
+ write(options, routes);
85
+ return routes;
86
+ }
87
+
88
+ const write = throttleDebounce.debounce(1e3, writeDefinitions, { atBegin: true });
89
+ async function writeDefinitions(options, collection) {
90
+ collection ?? (collection = await fetchRoutesFromArtisan(options));
91
+ if (options.dts === false) {
92
+ return;
93
+ }
94
+ debug.router("Writing types for route collection:", collection);
95
+ const target = path__default.resolve(options.dts ?? "resources/types/routes.d.ts");
96
+ const routes = Object.fromEntries(Object.entries(collection.routes).map(([key, route]) => {
97
+ const bindings = route.bindings ? Object.fromEntries(Object.entries(route.bindings).map(([key2]) => [key2, "__key_placeholder__"])) : void 0;
98
+ return [key, {
99
+ ...route.uri ? { uri: route.uri } : {},
100
+ ...route.domain ? { domain: route.domain } : {},
101
+ ...route.wheres ? { wheres: route.wheres } : {},
102
+ ...route.bindings ? { bindings } : {}
103
+ }];
104
+ }));
105
+ const definitions = generateDefinitions().replace("__URL__", collection?.url ?? "").replace("__ROUTES__", JSON.stringify(routes).replaceAll('"__key_placeholder__"', "any"));
106
+ fs__default.writeFileSync(target, definitions, { encoding: "utf-8" });
107
+ }
108
+ function generateDefinitions() {
109
+ return `
110
+ // This file has been automatically generated by Hybridly
111
+ // Modifications will be discarded
112
+ // It is recommended to add it in your .gitignore
113
+
114
+ declare module 'hybridly/vue' {
115
+ export interface GlobalRouteCollection {
116
+ url: '__URL__'
117
+ routes: __ROUTES__
118
+ }
119
+ }
120
+
121
+ export {}`;
122
+ }
123
+
124
+ const router = (options = {}) => {
125
+ const resolved = {
126
+ php: "php",
127
+ dts: "resources/types/routes.d.ts",
128
+ watch: [
129
+ /routes\/.*\.php/
130
+ ],
131
+ ...options
132
+ };
133
+ let previousRoutes;
134
+ return {
135
+ name: ROUTER_PLUGIN_NAME,
136
+ configureServer(server) {
137
+ write(resolved);
138
+ server.watcher.on("change", async (path) => {
139
+ if (!resolved.watch.some((regex) => regex.test(path))) {
140
+ return;
141
+ }
142
+ const routes = await fetchRoutesFromArtisan(resolved);
143
+ if (JSON.stringify(routes) !== JSON.stringify(previousRoutes)) {
144
+ debug.router("Updating routes via HMR:", routes);
145
+ server.ws.send({
146
+ type: "custom",
147
+ event: ROUTER_HMR_UPDATE_ROUTE,
148
+ data: routes
149
+ });
150
+ write(resolved);
151
+ previousRoutes = routes;
152
+ }
153
+ });
154
+ },
155
+ resolveId(id) {
156
+ if (id === ROUTER_VIRTUAL_MODULE_ID) {
157
+ return RESOLVED_ROUTER_VIRTUAL_MODULE_ID;
158
+ }
159
+ },
160
+ async load(id) {
161
+ if (id === RESOLVED_ROUTER_VIRTUAL_MODULE_ID) {
162
+ const routes = await fetchRoutesFromArtisan(resolved);
163
+ return getClientCode(routes);
164
+ }
165
+ },
166
+ async handleHotUpdate(ctx) {
167
+ if (typeof resolved.dts === "string" && ctx.file.endsWith(resolved.dts)) {
168
+ return [];
169
+ }
170
+ },
171
+ transform() {
172
+ write(resolved);
173
+ }
174
+ };
175
+ };
176
+
177
+ function plugin(options = {}) {
178
+ return [
179
+ options.layout !== false && layout(options.layout),
180
+ options.router !== false && router(options.router)
181
+ ];
182
+ }
183
+
184
+ exports["default"] = plugin;
185
+ exports.layout = layout;
186
+ exports.router = router;
@@ -0,0 +1,39 @@
1
+ import { Plugin, PluginOption } from 'vite';
2
+
3
+ interface Options {
4
+ /** Options for the layout plugin. */
5
+ layout?: false | LayoutOptions;
6
+ /** Options for the router plugin. */
7
+ router?: false | RouterOptions;
8
+ }
9
+ interface LayoutOptions {
10
+ /** The directory in which layouts are stored. */
11
+ directory?: string;
12
+ /** Function that resolves the layout path given its name. */
13
+ resolve?: (layout: string) => string;
14
+ }
15
+ interface RouterOptions {
16
+ /** Path to the PHP executable. */
17
+ php?: string;
18
+ /** Path to definition file. */
19
+ dts?: false | string;
20
+ /** File patterns to watch. */
21
+ watch?: RegExp[];
22
+ }
23
+
24
+ /**
25
+ * A basic Vite plugin that adds a <template layout="name"> syntax to Vite SFCs.
26
+ * It must be used before the Vue plugin.
27
+ */
28
+ declare const _default$1: (options?: LayoutOptions) => Plugin;
29
+
30
+ /**
31
+ * A basic Vite plugin that adds a <template layout="name"> syntax to Vite SFCs.
32
+ * It must be used before the Vue plugin.
33
+ */
34
+ declare const _default: (options?: RouterOptions) => Plugin;
35
+
36
+ /** Registers `unplugin-vue-define-options`. */
37
+ declare function plugin(options?: Options): PluginOption[];
38
+
39
+ export { Options, plugin as default, _default$1 as layout, _default as router };
package/dist/index.mjs ADDED
@@ -0,0 +1,174 @@
1
+ import path from 'node:path';
2
+ import { normalizePath } from 'vite';
3
+ import makeDebugger from 'debug';
4
+ import fs from 'node:fs';
5
+ import { debounce } from 'throttle-debounce';
6
+ import { exec } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+
9
+ const ROUTER_PLUGIN_NAME = "vite:hybridly:router";
10
+ const ROUTER_HMR_UPDATE_ROUTE = "hybridly:routes:update";
11
+ const ROUTER_VIRTUAL_MODULE_ID = "virtual:hybridly/router";
12
+ const RESOLVED_ROUTER_VIRTUAL_MODULE_ID = `\0${ROUTER_VIRTUAL_MODULE_ID}`;
13
+ const LAYOUT_PLUGIN_NAME = "vite:hybridly:layout";
14
+
15
+ const debug = {
16
+ router: makeDebugger(ROUTER_PLUGIN_NAME),
17
+ layout: makeDebugger(LAYOUT_PLUGIN_NAME)
18
+ };
19
+
20
+ const TEMPLATE_LAYOUT_REGEX = /<template +layout(?: *= *['"](?:(?:(\w+):)?(\w+))['"] *)?>/;
21
+ const TYPESCRIPT_REGEX = /lang=['"]ts['"]/;
22
+ const layout = (options = {}) => {
23
+ const base = options?.directory ? options?.directory : path.resolve(process.cwd(), "resources", "views", "layouts");
24
+ const layoutPath = options?.resolve ? options.resolve : (layoutName) => normalizePath(path.resolve(base, `${layoutName ?? "default"}.vue`)).replaceAll("\\", "/");
25
+ debug.layout("Registered layout path:", base);
26
+ return {
27
+ name: LAYOUT_PLUGIN_NAME,
28
+ transform: (code, id) => {
29
+ if (!TEMPLATE_LAYOUT_REGEX.test(code)) {
30
+ return;
31
+ }
32
+ return code.replace(TEMPLATE_LAYOUT_REGEX, (_, __, layoutName) => {
33
+ const isTypeScript = TYPESCRIPT_REGEX.test(code);
34
+ const importPath = layoutPath(layoutName);
35
+ debug.layout(`Resolved layout "${layoutName}":`, {
36
+ sourceFile: id,
37
+ importPath
38
+ });
39
+ return `
40
+ <script${isTypeScript ? ' lang="ts"' : ""}>
41
+ import layout from '${importPath}'
42
+ export default { layout }
43
+ <\/script>
44
+ <template>
45
+ `;
46
+ });
47
+ }
48
+ };
49
+ };
50
+
51
+ function getClientCode(routes) {
52
+ return `
53
+ if (typeof window !== 'undefined') {
54
+ window.hybridly = {
55
+ routes: ${JSON.stringify(routes)}
56
+ }
57
+
58
+ if (import.meta.hot) {
59
+ import.meta.hot.on('${ROUTER_HMR_UPDATE_ROUTE}', (routes) => {
60
+ window.dispatchEvent(
61
+ new CustomEvent('hybridly:routes', { detail: routes })
62
+ )
63
+ })
64
+ }
65
+ }
66
+ `;
67
+ }
68
+
69
+ const shell = promisify(exec);
70
+ async function fetchRoutesFromArtisan(options) {
71
+ const php = options.php ?? "php";
72
+ const result = await shell(`${php} artisan hybridly:routes`);
73
+ const routes = JSON.parse(result.stdout);
74
+ write(options, routes);
75
+ return routes;
76
+ }
77
+
78
+ const write = debounce(1e3, writeDefinitions, { atBegin: true });
79
+ async function writeDefinitions(options, collection) {
80
+ collection ?? (collection = await fetchRoutesFromArtisan(options));
81
+ if (options.dts === false) {
82
+ return;
83
+ }
84
+ debug.router("Writing types for route collection:", collection);
85
+ const target = path.resolve(options.dts ?? "resources/types/routes.d.ts");
86
+ const routes = Object.fromEntries(Object.entries(collection.routes).map(([key, route]) => {
87
+ const bindings = route.bindings ? Object.fromEntries(Object.entries(route.bindings).map(([key2]) => [key2, "__key_placeholder__"])) : void 0;
88
+ return [key, {
89
+ ...route.uri ? { uri: route.uri } : {},
90
+ ...route.domain ? { domain: route.domain } : {},
91
+ ...route.wheres ? { wheres: route.wheres } : {},
92
+ ...route.bindings ? { bindings } : {}
93
+ }];
94
+ }));
95
+ const definitions = generateDefinitions().replace("__URL__", collection?.url ?? "").replace("__ROUTES__", JSON.stringify(routes).replaceAll('"__key_placeholder__"', "any"));
96
+ fs.writeFileSync(target, definitions, { encoding: "utf-8" });
97
+ }
98
+ function generateDefinitions() {
99
+ return `
100
+ // This file has been automatically generated by Hybridly
101
+ // Modifications will be discarded
102
+ // It is recommended to add it in your .gitignore
103
+
104
+ declare module 'hybridly/vue' {
105
+ export interface GlobalRouteCollection {
106
+ url: '__URL__'
107
+ routes: __ROUTES__
108
+ }
109
+ }
110
+
111
+ export {}`;
112
+ }
113
+
114
+ const router = (options = {}) => {
115
+ const resolved = {
116
+ php: "php",
117
+ dts: "resources/types/routes.d.ts",
118
+ watch: [
119
+ /routes\/.*\.php/
120
+ ],
121
+ ...options
122
+ };
123
+ let previousRoutes;
124
+ return {
125
+ name: ROUTER_PLUGIN_NAME,
126
+ configureServer(server) {
127
+ write(resolved);
128
+ server.watcher.on("change", async (path) => {
129
+ if (!resolved.watch.some((regex) => regex.test(path))) {
130
+ return;
131
+ }
132
+ const routes = await fetchRoutesFromArtisan(resolved);
133
+ if (JSON.stringify(routes) !== JSON.stringify(previousRoutes)) {
134
+ debug.router("Updating routes via HMR:", routes);
135
+ server.ws.send({
136
+ type: "custom",
137
+ event: ROUTER_HMR_UPDATE_ROUTE,
138
+ data: routes
139
+ });
140
+ write(resolved);
141
+ previousRoutes = routes;
142
+ }
143
+ });
144
+ },
145
+ resolveId(id) {
146
+ if (id === ROUTER_VIRTUAL_MODULE_ID) {
147
+ return RESOLVED_ROUTER_VIRTUAL_MODULE_ID;
148
+ }
149
+ },
150
+ async load(id) {
151
+ if (id === RESOLVED_ROUTER_VIRTUAL_MODULE_ID) {
152
+ const routes = await fetchRoutesFromArtisan(resolved);
153
+ return getClientCode(routes);
154
+ }
155
+ },
156
+ async handleHotUpdate(ctx) {
157
+ if (typeof resolved.dts === "string" && ctx.file.endsWith(resolved.dts)) {
158
+ return [];
159
+ }
160
+ },
161
+ transform() {
162
+ write(resolved);
163
+ }
164
+ };
165
+ };
166
+
167
+ function plugin(options = {}) {
168
+ return [
169
+ options.layout !== false && layout(options.layout),
170
+ options.router !== false && router(options.router)
171
+ ];
172
+ }
173
+
174
+ export { plugin as default, layout, router };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@hybridly/vite",
3
+ "version": "0.0.1-alpha.1",
4
+ "description": "A solution to develop server-driven, client-rendered applications",
5
+ "keywords": [
6
+ "hybridly",
7
+ "inertiajs",
8
+ "vite",
9
+ "vite-plugin"
10
+ ],
11
+ "homepage": "https://github.com/hybridly/hybridly/tree/main/packages/vite#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/hybridly/hybridly/issues"
14
+ },
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/hybridly/hybridly.git",
19
+ "directory": "packages/vite"
20
+ },
21
+ "funding": "https://github.com/sponsors/innocenzi",
22
+ "author": "Enzo Innocenzi <enzo@innocenzi.dev>",
23
+ "sideEffects": false,
24
+ "files": [
25
+ "dist",
26
+ "*.d.ts"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "require": "./dist/index.cjs",
31
+ "import": "./dist/index.mjs",
32
+ "types": "./dist/index.d.ts"
33
+ }
34
+ },
35
+ "main": "dist/index.cjs",
36
+ "module": "dist/index.mjs",
37
+ "types": "dist/index.d.ts",
38
+ "peerDependencies": {
39
+ "vue": "^3.2.33"
40
+ },
41
+ "dependencies": {
42
+ "@hybridly/core": "0.0.1-alpha.1",
43
+ "throttle-debounce": "^5.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "rollup": "^2.79.1",
47
+ "vite": "^3.1.7",
48
+ "vue": "^3.2.40"
49
+ },
50
+ "scripts": {
51
+ "build": "unbuild",
52
+ "stub": "unbuild --stub"
53
+ }
54
+ }