@ng-native/analog 0.0.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ashley Hunter
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/README.md CHANGED
@@ -1,3 +1,111 @@
1
1
  # @ng-native/analog
2
2
 
3
- Reserved for ng-native. The first release follows.
3
+ [Analog](https://analogjs.org)'s file-based pages for an Angular Native app: the pages in
4
+ `src/app/pages`, routed by `createRoutes` from `@analogjs/router` itself, on a native stack, and the
5
+ Markdown in `src/content`, read with the API `@analogjs/content` has.
6
+
7
+ Alpha: APIs may change before 1.0.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @ng-native/analog @analogjs/router @ng-native/router @angular/router
13
+ npx expo install react-native-screens
14
+ ```
15
+
16
+ ## Example
17
+
18
+ ```js
19
+ // metro.config.js
20
+ const { getDefaultConfig } = require('expo/metro-config');
21
+ const { withAngularNative } = require('@ng-native/metro/config.cjs');
22
+ const { withAnalog } = require('@ng-native/analog/metro');
23
+
24
+ module.exports = withAnalog(withAngularNative(getDefaultConfig(__dirname)));
25
+ ```
26
+
27
+ ```ts
28
+ // src/app/pages.ts
29
+ import type { PageContext } from '@ng-native/analog';
30
+
31
+ declare const require: {
32
+ context(directory: string, recursive: boolean, filter: RegExp, mode: 'lazy'): PageContext;
33
+ };
34
+
35
+ export const pages = require.context('./pages', true, /\.page\.ts$/, 'lazy');
36
+ ```
37
+
38
+ ```ts
39
+ // src/app/app.config.ts
40
+ import { withComponentInputBinding } from '@angular/router';
41
+ import { pageRoutes } from '@ng-native/analog';
42
+ import { provideNativeRouter } from '@ng-native/router';
43
+ import { pages } from './pages.ts';
44
+
45
+ export const appConfig = {
46
+ providers: [provideNativeRouter(pageRoutes(pages), withComponentInputBinding())],
47
+ };
48
+ ```
49
+
50
+ ## What's in the package
51
+
52
+ - `pageRoutes(pages, { markdownPage })`: Analog's routes for a `require.context` of the pages, or
53
+ for the files of an `import.meta.glob` in a Vitest test. A `.md` page is drawn by `markdownPage`,
54
+ which reads its file with `injectMarkdownPage()`: `@ng-native/router`'s, so the same component
55
+ draws a `.md` page under its `fileRoutes` too.
56
+ - `provideContentFiles(content)`, `injectContent`, `injectContentFiles`, `contentFilesResource` and
57
+ `contentFileResource`: `@analogjs/content`'s API over a `require.context` of `src/content`, each
58
+ file lexed by Metro, for `<markdown [tokens]>` from `@ng-native/components/markdown`.
59
+ - `withAnalog(config)` in `@ng-native/analog/metro`: turns on `require.context`, and resolves
60
+ `@analogjs/router`'s import of `@analogjs/content`, which only a Markdown page needs, to an empty
61
+ module, installed or not. The app's own import of it resolves to the package, and fails the build
62
+ when it is not installed.
63
+
64
+ Markdown pages and content files need `marked`, which Metro lexes them with:
65
+
66
+ ```sh
67
+ npx expo install marked @ng-native/components
68
+ ```
69
+
70
+ ```ts
71
+ // src/app/content.ts
72
+ import type { ContentContext } from '@ng-native/analog';
73
+
74
+ declare const require: {
75
+ context(directory: string, recursive: boolean, filter: RegExp): ContentContext;
76
+ };
77
+
78
+ export const content = require.context('../content', true, /\.md$/);
79
+ ```
80
+
81
+ ```ts
82
+ // src/app/pages/blog/[slug].page.ts
83
+ import { Component } from '@angular/core';
84
+ import { toSignal } from '@angular/core/rxjs-interop';
85
+ import { injectContent } from '@ng-native/analog';
86
+ import { Markdown } from '@ng-native/components/markdown';
87
+
88
+ @Component({
89
+ imports: [Markdown],
90
+ template: `
91
+ @if (post(); as post) {
92
+ <markdown [tokens]="post.tokens" [source]="post.content" />
93
+ }
94
+ `,
95
+ })
96
+ export default class PostPage {
97
+ protected readonly post = toSignal(injectContent());
98
+ }
99
+ ```
100
+
101
+ Add `provideContentFiles(content)` to the app's providers.
102
+
103
+ ## Docs
104
+
105
+ - [Analog](https://ng-native.com/packages/analog)
106
+ - [Root README](https://github.com/ng-native/ng-native/blob/main/README.md) and
107
+ [ARCHITECTURE.md](https://github.com/ng-native/ng-native/blob/main/docs/ARCHITECTURE.md)
108
+
109
+ ## License
110
+
111
+ MIT
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `@analogjs/content`'s API on native, over the `.md` files in `src/content`: `injectContent`,
3
+ * `injectContentFiles`, `contentFilesResource` and `contentFileResource`, with the names, the
4
+ * arguments and the `ContentFile` shape Analog has, so a blog's pages read the same on both.
5
+ *
6
+ * Analog finds the files with Vite as it builds. On native the app finds them with a
7
+ * `require.context` and hands it to `provideContentFiles`, and Metro has made each file
8
+ * `{ attributes, content, tokens }` already: see `@ng-native/metro`'s `markdown-module.cjs`. So
9
+ * there is no renderer to provide and no parser on the device: a page draws `tokens` with
10
+ * `<markdown>` from `@ng-native/components/markdown`.
11
+ */
12
+ import { type ResourceRef, type Signal, type Provider } from '@angular/core';
13
+ import { type Observable } from 'rxjs';
14
+ /**
15
+ * A token `marked.lexer` made, as `<markdown [tokens]>` takes it. Typed here rather than imported
16
+ * from `marked`, so an app's types never need it.
17
+ */
18
+ export interface ContentToken {
19
+ type: string;
20
+ raw: string;
21
+ [key: string]: any;
22
+ }
23
+ /** A heading of a content file, as Analog lists them. */
24
+ export interface TableOfContentItem {
25
+ /** The heading's text made a slug, as Analog makes it: `Getting started` is `getting-started`. */
26
+ id: string;
27
+ /** 1 for `#`, up to 6. */
28
+ level: number;
29
+ /** The heading as written, without its `#`s. */
30
+ text: string;
31
+ }
32
+ /** A content file, as `@analogjs/content` gives it, with the tokens it was lexed into. */
33
+ export interface ContentFile<Attributes extends Record<string, any> = Record<string, any>> {
34
+ /** Its path from the project, `/src/content/post.md`; without `.md` from `injectContent`. */
35
+ filename: string;
36
+ /** Its front matter `slug`, or its file name without `.md`; `index.md` is `''`. */
37
+ slug: string;
38
+ /** The Markdown after the front matter; the fallback text for a file that is not there. */
39
+ content?: string;
40
+ /** The front matter. A date in it is its ISO string. */
41
+ attributes: Attributes;
42
+ /** `content` lexed by `marked`, for `<markdown [tokens]>`. Not set on the fallback. */
43
+ tokens?: ContentToken[];
44
+ /** The headings, from `injectContent` and `contentFileResource`. */
45
+ toc?: TableOfContentItem[];
46
+ }
47
+ /** What a `.md` file is as a module, made by `@ng-native/metro` as the app is bundled. */
48
+ export interface MarkdownModule {
49
+ readonly attributes: Readonly<Record<string, unknown>>;
50
+ readonly content: string;
51
+ readonly tokens: ContentToken[];
52
+ }
53
+ /**
54
+ * What Metro's `require.context('../content', true, /\.md$/)` returns: the files it found, each
55
+ * keyed by its path from that directory (`./blog/post.md`), and a call that loads one.
56
+ */
57
+ export interface ContentContext {
58
+ keys(): string[];
59
+ (key: string): unknown;
60
+ }
61
+ /**
62
+ * The files of an eager `import.meta.glob`, such as
63
+ * `import.meta.glob('/src/content/**\/*.md', { eager: true })`, for a Vitest test.
64
+ */
65
+ export type ContentModules = Readonly<Record<string, unknown>>;
66
+ export type InjectContentFilesFilterFunction<T extends Record<string, any>> = (value: ContentFile<T>, index: number, array: ContentFile<T>[]) => boolean;
67
+ /** The parameter `injectContent` and `contentFileResource` find a file by. */
68
+ export type ContentParam = string | {
69
+ param: string;
70
+ subdirectory: string;
71
+ } | {
72
+ customFilename: string;
73
+ };
74
+ /**
75
+ * The content files `injectContent` and `injectContentFiles` read, from a `require.context` of
76
+ * `src/content` in an app:
77
+ *
78
+ * ```ts
79
+ * provideContentFiles(require.context('../content', true, /\.md$/))
80
+ * ```
81
+ *
82
+ * or from an eager `import.meta.glob` of the same files in a Vitest test. The context is read each
83
+ * time a file or the list is asked for, so a file Metro adds or removes is in the next one.
84
+ */
85
+ export declare function provideContentFiles(content: ContentContext | ContentModules): Provider[];
86
+ /**
87
+ * One content file, by the route parameter that names it, as in Analog:
88
+ *
89
+ * - `injectContent()` reads the `slug` parameter: `/blog/:slug` finds `src/content/<slug>.md`.
90
+ * - `injectContent('id')` reads the `id` parameter instead.
91
+ * - `injectContent({ param: 'slug', subdirectory: 'blog' })` finds `src/content/blog/<slug>.md`.
92
+ * - `injectContent({ customFilename: 'about' })` finds `src/content/about.md`, with no parameter.
93
+ *
94
+ * A file that is not there, or a parameter that is not set, gives `{ attributes: {}, content:
95
+ * fallback }`, which a page can tell by its empty `slug`.
96
+ */
97
+ export declare function injectContent<Attributes extends Record<string, any> = Record<string, any>>(param?: ContentParam, fallback?: string): Observable<ContentFile<Attributes | Record<string, never>>>;
98
+ /**
99
+ * Every content file, without its content, as in Analog: `filename`, `slug` and `attributes`, in
100
+ * the order the context lists them. `filterFn` keeps the ones it returns true for.
101
+ */
102
+ export declare function injectContentFiles<Attributes extends Record<string, any>>(filterFn?: InjectContentFilesFilterFunction<Attributes>): ContentFile<Attributes>[];
103
+ /** `injectContentFiles`, as a resource, as `@analogjs/content/resources` has it. */
104
+ export declare function contentFilesResource<Attributes extends Record<string, any>>(filterFn?: InjectContentFilesFilterFunction<Attributes>): ResourceRef<ContentFile<Attributes>[] | undefined>;
105
+ /**
106
+ * One content file, as a resource, as `@analogjs/content/resources` has it: by `params`, a slug or
107
+ * `{ customFilename }`, or by the route's `slug` parameter when there is none.
108
+ */
109
+ export declare function contentFileResource<Attributes extends Record<string, any> = Record<string, any>>(params?: Signal<string | {
110
+ customFilename: string;
111
+ }>, fallback?: string): ResourceRef<ContentFile<Attributes | Record<string, never>> | undefined>;
@@ -0,0 +1,207 @@
1
+ /**
2
+ * `@analogjs/content`'s API on native, over the `.md` files in `src/content`: `injectContent`,
3
+ * `injectContentFiles`, `contentFilesResource` and `contentFileResource`, with the names, the
4
+ * arguments and the `ContentFile` shape Analog has, so a blog's pages read the same on both.
5
+ *
6
+ * Analog finds the files with Vite as it builds. On native the app finds them with a
7
+ * `require.context` and hands it to `provideContentFiles`, and Metro has made each file
8
+ * `{ attributes, content, tokens }` already: see `@ng-native/metro`'s `markdown-module.cjs`. So
9
+ * there is no renderer to provide and no parser on the device: a page draws `tokens` with
10
+ * `<markdown>` from `@ng-native/components/markdown`.
11
+ */
12
+ import { InjectionToken, computed, inject, resource, } from '@angular/core';
13
+ import { toSignal } from '@angular/core/rxjs-interop';
14
+ import { ActivatedRoute } from '@angular/router';
15
+ import { markdownPageFile } from '@ng-native/router';
16
+ import { defer, map, of } from 'rxjs';
17
+ const CONTENT_FILES = new InjectionToken('@ng-native/analog content files');
18
+ /** The content files, or an error saying how to provide them. */
19
+ function injectFiles(caller) {
20
+ const files = inject(CONTENT_FILES, { optional: true });
21
+ if (!files) {
22
+ throw new Error(`${caller} reads the files provideContentFiles was given, and the app has none. Add ` +
23
+ "provideContentFiles(require.context('../content', true, /\\.md$/)) to its providers.");
24
+ }
25
+ return files;
26
+ }
27
+ const DEFAULT_FALLBACK = 'No Content Found';
28
+ /**
29
+ * The content files `injectContent` and `injectContentFiles` read, from a `require.context` of
30
+ * `src/content` in an app:
31
+ *
32
+ * ```ts
33
+ * provideContentFiles(require.context('../content', true, /\.md$/))
34
+ * ```
35
+ *
36
+ * or from an eager `import.meta.glob` of the same files in a Vitest test. The context is read each
37
+ * time a file or the list is asked for, so a file Metro adds or removes is in the next one.
38
+ */
39
+ export function provideContentFiles(content) {
40
+ return [{ provide: CONTENT_FILES, useValue: () => foundFiles(content) }];
41
+ }
42
+ function foundFiles(content) {
43
+ const entries = typeof content === 'function'
44
+ ? content
45
+ .keys()
46
+ .map((key) => [`/src/content/${key.replace(/^\.\//, '')}`, () => content(key)])
47
+ : Object.keys(content).map((key) => [contentPath(key), () => content[key]]);
48
+ return entries
49
+ .filter(([filename]) => filename.endsWith('.md'))
50
+ .map(([filename, load]) => ({ filename, module: markdownModuleOf(load(), filename) }));
51
+ }
52
+ /** A glob's key as Analog names a content file, from `/src/content`. */
53
+ function contentPath(key) {
54
+ const named = key.replace(/^(?:.*?)\/content(?=\/)/, '/src/content');
55
+ return (named.startsWith('/src/content/') ? named : `/src/content/${key.replace(/^\.?\//, '')}`).replace(/\/{2,}/g, '/');
56
+ }
57
+ /**
58
+ * The `{ attributes, content, tokens }` a loaded `.md` module holds, from its namespace or as it
59
+ * is, checked as `fileRoutes` checks a Markdown page.
60
+ */
61
+ function markdownModuleOf(loaded, filename) {
62
+ if (loaded instanceof Promise || typeof loaded?.then === 'function') {
63
+ throw new Error(`${filename} loaded as a promise. provideContentFiles reads every file as the list is ` +
64
+ "asked for: make its require.context without 'lazy', and an import.meta.glob with " +
65
+ '{ eager: true }.');
66
+ }
67
+ const { attributes, content, tokens } = markdownPageFile(filename, loaded);
68
+ return { attributes, content, tokens };
69
+ }
70
+ /** A file's slug from its name, as Analog takes it: `post.md` is `post`, `index.md` is `''`. */
71
+ function slugOf(filename) {
72
+ const base = (filename.split(/[/\\]/).pop() ?? '').trim().replace(/\.[^./\\]+$/, '');
73
+ return base === 'index' ? '' : base;
74
+ }
75
+ /** A file's front matter `slug`, or its name's, as written. */
76
+ function rawSlugOf(found) {
77
+ const slug = found.module.attributes['slug'];
78
+ return typeof slug === 'string' && slug ? slug : slugOf(found.filename);
79
+ }
80
+ /** A file in the list: its slug encoded for a URL, as Analog lists it. */
81
+ function listed(found) {
82
+ return {
83
+ filename: found.filename,
84
+ attributes: found.module.attributes,
85
+ slug: encodeURI(rawSlugOf(found)),
86
+ };
87
+ }
88
+ /**
89
+ * Where `injectContent` finds each file, as Analog finds it: by its slug, in its own folder, so a
90
+ * front matter `slug` renames the file. A slug with a `/` in it is from the folder under
91
+ * `src/content` it is in, or from `src/content` itself.
92
+ */
93
+ function filesBySlug(files) {
94
+ const bySlug = new Map();
95
+ for (const found of files) {
96
+ const parts = found.filename.split('/');
97
+ const folder = parts.slice(0, -1).join('/');
98
+ const slug = rawSlugOf(found) || 'index';
99
+ const root = parts.length > 4 ? parts.slice(0, 4).join('/') : '/src/content';
100
+ bySlug.set(`${slug.includes('/') ? root : folder}/${slug}.md`.replace(/\/{2,}/g, '/'), found);
101
+ }
102
+ return bySlug;
103
+ }
104
+ /** The headings of `tokens`, with ids made as Analog makes them. */
105
+ function tableOfContents(tokens) {
106
+ const counts = new Map();
107
+ const toc = [];
108
+ for (const token of tokens) {
109
+ if (token.type !== 'heading')
110
+ continue;
111
+ const text = String(token['text'] ?? '').trim();
112
+ if (!text)
113
+ continue;
114
+ const base = text
115
+ .toLowerCase()
116
+ .replace(/[^\w\s-]/g, '')
117
+ .trim()
118
+ .replace(/\s+/g, '-');
119
+ const count = counts.get(base) ?? 0;
120
+ counts.set(base, count + 1);
121
+ toc.push({ id: count === 0 ? base : `${base}-${count}`, level: Number(token['depth']), text });
122
+ }
123
+ return toc;
124
+ }
125
+ /**
126
+ * The file at `/src/content/<prefix><slug>.md`, or `<slug>/index.md` under it, as `injectContent`
127
+ * gives it; the fallback when there is none, as Analog gives it.
128
+ */
129
+ function contentFile(files, prefix, slug, fallback) {
130
+ const bySlug = filesBySlug(files);
131
+ const base = `/src/content/${prefix}${slug}`.replace(/\/{2,}/g, '/');
132
+ const key = [`${base}.md`, `${base}/index.md`].find((candidate) => bySlug.has(candidate));
133
+ const found = key === undefined ? undefined : bySlug.get(key);
134
+ if (!key || !found) {
135
+ return { filename: base, attributes: {}, slug: '', content: fallback, toc: [] };
136
+ }
137
+ const { attributes, content, tokens } = found.module;
138
+ return {
139
+ filename: key.replace(/\.md$/, ''),
140
+ slug,
141
+ attributes: attributes,
142
+ content,
143
+ tokens,
144
+ toc: tableOfContents(tokens),
145
+ };
146
+ }
147
+ const NO_SLUG = (fallback) => ({
148
+ filename: '',
149
+ slug: '',
150
+ attributes: {},
151
+ content: fallback,
152
+ toc: [],
153
+ });
154
+ /**
155
+ * One content file, by the route parameter that names it, as in Analog:
156
+ *
157
+ * - `injectContent()` reads the `slug` parameter: `/blog/:slug` finds `src/content/<slug>.md`.
158
+ * - `injectContent('id')` reads the `id` parameter instead.
159
+ * - `injectContent({ param: 'slug', subdirectory: 'blog' })` finds `src/content/blog/<slug>.md`.
160
+ * - `injectContent({ customFilename: 'about' })` finds `src/content/about.md`, with no parameter.
161
+ *
162
+ * A file that is not there, or a parameter that is not set, gives `{ attributes: {}, content:
163
+ * fallback }`, which a page can tell by its empty `slug`.
164
+ */
165
+ export function injectContent(param = 'slug', fallback = DEFAULT_FALLBACK) {
166
+ const files = injectFiles('injectContent()');
167
+ if (typeof param !== 'string' && 'customFilename' in param) {
168
+ return defer(() => of(contentFile(files(), '', param.customFilename, fallback)));
169
+ }
170
+ const prefix = typeof param === 'string' ? '' : `${param.subdirectory}/`;
171
+ const key = typeof param === 'string' ? param : param.param;
172
+ return inject(ActivatedRoute).paramMap.pipe(map((params) => params.get(key)), map((slug) => slug ? contentFile(files(), prefix, slug, fallback) : NO_SLUG(fallback)));
173
+ }
174
+ /**
175
+ * Every content file, without its content, as in Analog: `filename`, `slug` and `attributes`, in
176
+ * the order the context lists them. `filterFn` keeps the ones it returns true for.
177
+ */
178
+ export function injectContentFiles(filterFn) {
179
+ const files = injectFiles('injectContentFiles()')().map((found) => listed(found));
180
+ return filterFn ? files.filter(filterFn) : files;
181
+ }
182
+ /** `injectContentFiles`, as a resource, as `@analogjs/content/resources` has it. */
183
+ export function contentFilesResource(filterFn) {
184
+ const files = injectContentFiles(filterFn);
185
+ return resource({ loader: async () => files });
186
+ }
187
+ /**
188
+ * One content file, as a resource, as `@analogjs/content/resources` has it: by `params`, a slug or
189
+ * `{ customFilename }`, or by the route's `slug` parameter when there is none.
190
+ */
191
+ export function contentFileResource(params, fallback = DEFAULT_FALLBACK) {
192
+ const files = injectFiles('contentFileResource()');
193
+ const input = params ??
194
+ toSignal(inject(ActivatedRoute).paramMap.pipe(map((route) => route.get('slug') ?? '')), {
195
+ requireSync: true,
196
+ });
197
+ return resource({
198
+ params: computed(() => ({ input: input() })),
199
+ loader: async ({ params: { input: param } }) => {
200
+ if (typeof param !== 'string') {
201
+ return contentFile(files(), '', param.customFilename, fallback);
202
+ }
203
+ return param ? contentFile(files(), '', param, fallback) : NO_SLUG(fallback);
204
+ },
205
+ });
206
+ }
207
+ //# sourceMappingURL=content.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content.js","sourceRoot":"","sources":["../src/content.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EACL,cAAc,EACd,QAAQ,EACR,MAAM,EACN,QAAQ,GAIT,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,EAAmB,MAAM,MAAM,CAAC;AA4EvD,MAAM,aAAa,GAAG,IAAI,cAAc,CAAoB,iCAAiC,CAAC,CAAC;AAE/F,iEAAiE;AACjE,SAAS,WAAW,CAAC,MAAc;IACjC,MAAM,KAAK,GAAG,MAAM,CAAC,aAAa,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IACxD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,GAAG,MAAM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AG,WAAW,CAAC,uBAAuB,CAAC,CAAC;IACnD,MAAM,KAAK,GACT,MAAM;QACN,QAAQ,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE;YACtF,WAAW,EAAE,IAAI;SAClB,CAAC,CAAC;IACL,OAAO,QAAQ,CAAC;QACd,MAAM,EAAE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5C,MAAM,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;YAC7C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC9B,OAAO,WAAW,CAAa,KAAK,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;YAC9E,CAAC;YACD,OAAO,KAAK,CAAC,CAAC,CAAC,WAAW,CAAa,KAAK,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC3F,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `@analogjs/content`'s API on native, over the `.md` files in `src/content`: `injectContent`,\n * `injectContentFiles`, `contentFilesResource` and `contentFileResource`, with the names, the\n * arguments and the `ContentFile` shape Analog has, so a blog's pages read the same on both.\n *\n * Analog finds the files with Vite as it builds. On native the app finds them with a\n * `require.context` and hands it to `provideContentFiles`, and Metro has made each file\n * `{ attributes, content, tokens }` already: see `@ng-native/metro`'s `markdown-module.cjs`. So\n * there is no renderer to provide and no parser on the device: a page draws `tokens` with\n * `<markdown>` from `@ng-native/components/markdown`.\n */\nimport {\n InjectionToken,\n computed,\n inject,\n resource,\n type ResourceRef,\n type Signal,\n type Provider,\n} from '@angular/core';\nimport { toSignal } from '@angular/core/rxjs-interop';\nimport { ActivatedRoute } from '@angular/router';\nimport { markdownPageFile } from '@ng-native/router';\nimport { defer, map, of, type Observable } from 'rxjs';\n\n/**\n * A token `marked.lexer` made, as `<markdown [tokens]>` takes it. Typed here rather than imported\n * from `marked`, so an app's types never need it.\n */\nexport interface ContentToken {\n type: string;\n raw: string;\n [key: string]: any;\n}\n\n/** A heading of a content file, as Analog lists them. */\nexport interface TableOfContentItem {\n /** The heading's text made a slug, as Analog makes it: `Getting started` is `getting-started`. */\n id: string;\n /** 1 for `#`, up to 6. */\n level: number;\n /** The heading as written, without its `#`s. */\n text: string;\n}\n\n/** A content file, as `@analogjs/content` gives it, with the tokens it was lexed into. */\nexport interface ContentFile<Attributes extends Record<string, any> = Record<string, any>> {\n /** Its path from the project, `/src/content/post.md`; without `.md` from `injectContent`. */\n filename: string;\n /** Its front matter `slug`, or its file name without `.md`; `index.md` is `''`. */\n slug: string;\n /** The Markdown after the front matter; the fallback text for a file that is not there. */\n content?: string;\n /** The front matter. A date in it is its ISO string. */\n attributes: Attributes;\n /** `content` lexed by `marked`, for `<markdown [tokens]>`. Not set on the fallback. */\n tokens?: ContentToken[];\n /** The headings, from `injectContent` and `contentFileResource`. */\n toc?: TableOfContentItem[];\n}\n\n/** What a `.md` file is as a module, made by `@ng-native/metro` as the app is bundled. */\nexport interface MarkdownModule {\n readonly attributes: Readonly<Record<string, unknown>>;\n readonly content: string;\n readonly tokens: ContentToken[];\n}\n\n/**\n * What Metro's `require.context('../content', true, /\\.md$/)` returns: the files it found, each\n * keyed by its path from that directory (`./blog/post.md`), and a call that loads one.\n */\nexport interface ContentContext {\n keys(): string[];\n (key: string): unknown;\n}\n\n/**\n * The files of an eager `import.meta.glob`, such as\n * `import.meta.glob('/src/content/**\\/*.md', { eager: true })`, for a Vitest test.\n */\nexport type ContentModules = Readonly<Record<string, unknown>>;\n\nexport type InjectContentFilesFilterFunction<T extends Record<string, any>> = (\n value: ContentFile<T>,\n index: number,\n array: ContentFile<T>[],\n) => boolean;\n\n/** The parameter `injectContent` and `contentFileResource` find a file by. */\nexport type ContentParam =\n string | { param: string; subdirectory: string } | { customFilename: string };\n\n/** One file found, by its path from the project and the module Metro made of it. */\ninterface FoundFile {\n readonly filename: string;\n readonly module: MarkdownModule;\n}\n\nconst CONTENT_FILES = new InjectionToken<() => FoundFile[]>('@ng-native/analog content files');\n\n/** The content files, or an error saying how to provide them. */\nfunction injectFiles(caller: string): () => FoundFile[] {\n const files = inject(CONTENT_FILES, { optional: true });\n if (!files) {\n throw new Error(\n `${caller} reads the files provideContentFiles was given, and the app has none. Add ` +\n \"provideContentFiles(require.context('../content', true, /\\\\.md$/)) to its providers.\",\n );\n }\n return files;\n}\n\nconst DEFAULT_FALLBACK = 'No Content Found';\n\n/**\n * The content files `injectContent` and `injectContentFiles` read, from a `require.context` of\n * `src/content` in an app:\n *\n * ```ts\n * provideContentFiles(require.context('../content', true, /\\.md$/))\n * ```\n *\n * or from an eager `import.meta.glob` of the same files in a Vitest test. The context is read each\n * time a file or the list is asked for, so a file Metro adds or removes is in the next one.\n */\nexport function provideContentFiles(content: ContentContext | ContentModules): Provider[] {\n return [{ provide: CONTENT_FILES, useValue: () => foundFiles(content) }];\n}\n\nfunction foundFiles(content: ContentContext | ContentModules): FoundFile[] {\n const entries: [string, () => unknown][] =\n typeof content === 'function'\n ? content\n .keys()\n .map((key) => [`/src/content/${key.replace(/^\\.\\//, '')}`, () => content(key)])\n : Object.keys(content).map((key) => [contentPath(key), () => content[key]]);\n return entries\n .filter(([filename]) => filename.endsWith('.md'))\n .map(([filename, load]) => ({ filename, module: markdownModuleOf(load(), filename) }));\n}\n\n/** A glob's key as Analog names a content file, from `/src/content`. */\nfunction contentPath(key: string): string {\n const named = key.replace(/^(?:.*?)\\/content(?=\\/)/, '/src/content');\n return (\n named.startsWith('/src/content/') ? named : `/src/content/${key.replace(/^\\.?\\//, '')}`\n ).replace(/\\/{2,}/g, '/');\n}\n\n/**\n * The `{ attributes, content, tokens }` a loaded `.md` module holds, from its namespace or as it\n * is, checked as `fileRoutes` checks a Markdown page.\n */\nfunction markdownModuleOf(loaded: unknown, filename: string): MarkdownModule {\n if (loaded instanceof Promise || typeof (loaded as { then?: unknown })?.then === 'function') {\n throw new Error(\n `${filename} loaded as a promise. provideContentFiles reads every file as the list is ` +\n \"asked for: make its require.context without 'lazy', and an import.meta.glob with \" +\n '{ eager: true }.',\n );\n }\n const { attributes, content, tokens } = markdownPageFile(filename, loaded);\n return { attributes, content, tokens };\n}\n\n/** A file's slug from its name, as Analog takes it: `post.md` is `post`, `index.md` is `''`. */\nfunction slugOf(filename: string): string {\n const base = (filename.split(/[/\\\\]/).pop() ?? '').trim().replace(/\\.[^./\\\\]+$/, '');\n return base === 'index' ? '' : base;\n}\n\n/** A file's front matter `slug`, or its name's, as written. */\nfunction rawSlugOf(found: FoundFile): string {\n const slug = (found.module.attributes as Record<string, unknown>)['slug'];\n return typeof slug === 'string' && slug ? slug : slugOf(found.filename);\n}\n\n/** A file in the list: its slug encoded for a URL, as Analog lists it. */\nfunction listed<Attributes extends Record<string, any>>(found: FoundFile): ContentFile<Attributes> {\n return {\n filename: found.filename,\n attributes: found.module.attributes as Attributes,\n slug: encodeURI(rawSlugOf(found)),\n };\n}\n\n/**\n * Where `injectContent` finds each file, as Analog finds it: by its slug, in its own folder, so a\n * front matter `slug` renames the file. A slug with a `/` in it is from the folder under\n * `src/content` it is in, or from `src/content` itself.\n */\nfunction filesBySlug(files: readonly FoundFile[]): Map<string, FoundFile> {\n const bySlug = new Map<string, FoundFile>();\n for (const found of files) {\n const parts = found.filename.split('/');\n const folder = parts.slice(0, -1).join('/');\n const slug = rawSlugOf(found) || 'index';\n const root = parts.length > 4 ? parts.slice(0, 4).join('/') : '/src/content';\n bySlug.set(`${slug.includes('/') ? root : folder}/${slug}.md`.replace(/\\/{2,}/g, '/'), found);\n }\n return bySlug;\n}\n\n/** The headings of `tokens`, with ids made as Analog makes them. */\nfunction tableOfContents(tokens: readonly ContentToken[]): TableOfContentItem[] {\n const counts = new Map<string, number>();\n const toc: TableOfContentItem[] = [];\n for (const token of tokens) {\n if (token.type !== 'heading') continue;\n const text = String(token['text'] ?? '').trim();\n if (!text) continue;\n const base = text\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-');\n const count = counts.get(base) ?? 0;\n counts.set(base, count + 1);\n toc.push({ id: count === 0 ? base : `${base}-${count}`, level: Number(token['depth']), text });\n }\n return toc;\n}\n\n/**\n * The file at `/src/content/<prefix><slug>.md`, or `<slug>/index.md` under it, as `injectContent`\n * gives it; the fallback when there is none, as Analog gives it.\n */\nfunction contentFile<Attributes extends Record<string, any>>(\n files: readonly FoundFile[],\n prefix: string,\n slug: string,\n fallback: string,\n): ContentFile<Attributes | Record<string, never>> {\n const bySlug = filesBySlug(files);\n const base = `/src/content/${prefix}${slug}`.replace(/\\/{2,}/g, '/');\n const key = [`${base}.md`, `${base}/index.md`].find((candidate) => bySlug.has(candidate));\n const found = key === undefined ? undefined : bySlug.get(key);\n if (!key || !found) {\n return { filename: base, attributes: {}, slug: '', content: fallback, toc: [] };\n }\n const { attributes, content, tokens } = found.module;\n return {\n filename: key.replace(/\\.md$/, ''),\n slug,\n attributes: attributes as Attributes,\n content,\n tokens,\n toc: tableOfContents(tokens),\n };\n}\n\nconst NO_SLUG = (fallback: string): ContentFile<Record<string, never>> => ({\n filename: '',\n slug: '',\n attributes: {},\n content: fallback,\n toc: [],\n});\n\n/**\n * One content file, by the route parameter that names it, as in Analog:\n *\n * - `injectContent()` reads the `slug` parameter: `/blog/:slug` finds `src/content/<slug>.md`.\n * - `injectContent('id')` reads the `id` parameter instead.\n * - `injectContent({ param: 'slug', subdirectory: 'blog' })` finds `src/content/blog/<slug>.md`.\n * - `injectContent({ customFilename: 'about' })` finds `src/content/about.md`, with no parameter.\n *\n * A file that is not there, or a parameter that is not set, gives `{ attributes: {}, content:\n * fallback }`, which a page can tell by its empty `slug`.\n */\nexport function injectContent<Attributes extends Record<string, any> = Record<string, any>>(\n param: ContentParam = 'slug',\n fallback = DEFAULT_FALLBACK,\n): Observable<ContentFile<Attributes | Record<string, never>>> {\n const files = injectFiles('injectContent()');\n if (typeof param !== 'string' && 'customFilename' in param) {\n return defer(() => of(contentFile<Attributes>(files(), '', param.customFilename, fallback)));\n }\n const prefix = typeof param === 'string' ? '' : `${param.subdirectory}/`;\n const key = typeof param === 'string' ? param : param.param;\n return inject(ActivatedRoute).paramMap.pipe(\n map((params) => params.get(key)),\n map((slug) =>\n slug ? contentFile<Attributes>(files(), prefix, slug, fallback) : NO_SLUG(fallback),\n ),\n );\n}\n\n/**\n * Every content file, without its content, as in Analog: `filename`, `slug` and `attributes`, in\n * the order the context lists them. `filterFn` keeps the ones it returns true for.\n */\nexport function injectContentFiles<Attributes extends Record<string, any>>(\n filterFn?: InjectContentFilesFilterFunction<Attributes>,\n): ContentFile<Attributes>[] {\n const files = injectFiles('injectContentFiles()')().map((found) => listed<Attributes>(found));\n return filterFn ? files.filter(filterFn) : files;\n}\n\n/** `injectContentFiles`, as a resource, as `@analogjs/content/resources` has it. */\nexport function contentFilesResource<Attributes extends Record<string, any>>(\n filterFn?: InjectContentFilesFilterFunction<Attributes>,\n): ResourceRef<ContentFile<Attributes>[] | undefined> {\n const files = injectContentFiles(filterFn);\n return resource({ loader: async () => files });\n}\n\n/**\n * One content file, as a resource, as `@analogjs/content/resources` has it: by `params`, a slug or\n * `{ customFilename }`, or by the route's `slug` parameter when there is none.\n */\nexport function contentFileResource<Attributes extends Record<string, any> = Record<string, any>>(\n params?: Signal<string | { customFilename: string }>,\n fallback = DEFAULT_FALLBACK,\n): ResourceRef<ContentFile<Attributes | Record<string, never>> | undefined> {\n const files = injectFiles('contentFileResource()');\n const input =\n params ??\n toSignal(inject(ActivatedRoute).paramMap.pipe(map((route) => route.get('slug') ?? '')), {\n requireSync: true,\n });\n return resource({\n params: computed(() => ({ input: input() })),\n loader: async ({ params: { input: param } }) => {\n if (typeof param !== 'string') {\n return contentFile<Attributes>(files(), '', param.customFilename, fallback);\n }\n return param ? contentFile<Attributes>(files(), '', param, fallback) : NO_SLUG(fallback);\n },\n });\n}\n"]}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Analog's file-based pages, routed by `@analogjs/router` on a native stack, and the content files
3
+ * `@analogjs/content` reads, from `src/content`. The Metro half is `@ng-native/analog/metro`.
4
+ *
5
+ * A Markdown page is the one `@ng-native/router`'s `fileRoutes` routes, so its `injectMarkdownPage`
6
+ * is the router's, and one `markdownPage` component draws a page under either.
7
+ */
8
+ export { pageRoutes, type PageFiles, type PageRoutesOptions } from './page-routes.ts';
9
+ export { injectMarkdownPage, type MarkdownPageFile, type PageContext } from '@ng-native/router';
10
+ export { contentFileResource, contentFilesResource, injectContent, injectContentFiles, provideContentFiles, type ContentContext, type ContentFile, type ContentModules, type ContentParam, type ContentToken, type InjectContentFilesFilterFunction, type MarkdownModule, type TableOfContentItem, } from './content.ts';
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Analog's file-based pages, routed by `@analogjs/router` on a native stack, and the content files
3
+ * `@analogjs/content` reads, from `src/content`. The Metro half is `@ng-native/analog/metro`.
4
+ *
5
+ * A Markdown page is the one `@ng-native/router`'s `fileRoutes` routes, so its `injectMarkdownPage`
6
+ * is the router's, and one `markdownPage` component draws a page under either.
7
+ */
8
+ export { pageRoutes } from "./page-routes.js";
9
+ export { injectMarkdownPage } from '@ng-native/router';
10
+ export { contentFileResource, contentFilesResource, injectContent, injectContentFiles, provideContentFiles, } from "./content.js";
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAA0C,MAAM,kBAAkB,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAA2C,MAAM,mBAAmB,CAAC;AAChG,OAAO,EACL,mBAAmB,EACnB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,mBAAmB,GASpB,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Analog's file-based pages, routed by `@analogjs/router` on a native stack, and the content files\n * `@analogjs/content` reads, from `src/content`. The Metro half is `@ng-native/analog/metro`.\n *\n * A Markdown page is the one `@ng-native/router`'s `fileRoutes` routes, so its `injectMarkdownPage`\n * is the router's, and one `markdownPage` component draws a page under either.\n */\nexport { pageRoutes, type PageFiles, type PageRoutesOptions } from './page-routes.ts';\nexport { injectMarkdownPage, type MarkdownPageFile, type PageContext } from '@ng-native/router';\nexport {\n contentFileResource,\n contentFilesResource,\n injectContent,\n injectContentFiles,\n provideContentFiles,\n type ContentContext,\n type ContentFile,\n type ContentModules,\n type ContentParam,\n type ContentToken,\n type InjectContentFilesFilterFunction,\n type MarkdownModule,\n type TableOfContentItem,\n} from './content.ts';\n"]}
@@ -0,0 +1,28 @@
1
+ import type { Type } from '@angular/core';
2
+ import type { Routes } from '@angular/router';
3
+ import { type PageContext } from '@ng-native/router';
4
+ /**
5
+ * Each page's file name, with a call that loads it: what `import.meta.glob` returns, and what
6
+ * `createRoutes` takes.
7
+ */
8
+ export type PageFiles = Record<string, () => Promise<unknown>>;
9
+ export interface PageRoutesOptions {
10
+ /**
11
+ * The component a `.md` page is drawn with. It reads its file with `injectMarkdownPage()` and
12
+ * draws `tokens` with `<markdown>` from `@ng-native/components/markdown`. Required when the
13
+ * pages include a `.md` file. The same component draws one under `fileRoutes`.
14
+ */
15
+ markdownPage?: Type<unknown>;
16
+ }
17
+ /**
18
+ * The routes for an app's pages, as `createRoutes` makes them in an Analog app.
19
+ *
20
+ * `pages` is the `require.context` of the pages directory in an app, or in a Vitest test, which
21
+ * has no `require.context`, the files of an `import.meta.glob` such as
22
+ * `import.meta.glob('./pages/**\/*.page.ts')`.
23
+ *
24
+ * A `.md` file among them is a page too, at the URL its name gives it, as in Analog: its front
25
+ * matter `title` is the route's title and `meta` its `routeMeta.meta`, and it is drawn by
26
+ * `options.markdownPage`.
27
+ */
28
+ export declare function pageRoutes(pages: PageContext | PageFiles, options?: PageRoutesOptions): Routes;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Analog's file-based pages on a native stack: `pageRoutes` hands the files under
3
+ * `src/app/pages` to `createRoutes` from `@analogjs/router`, so `index.page.ts`, `[id].page.ts`,
4
+ * `(group)` folders, layouts and each page's `routeMeta` route as they do in an Analog app, and
5
+ * `provideNativeRouter` takes the routes it returns.
6
+ *
7
+ * ```ts
8
+ * const pages = require.context('./pages', true, /\.page\.ts$/, 'lazy');
9
+ *
10
+ * mount(rootTag, App, fabric, { providers: [provideNativeRouter(pageRoutes(pages))] });
11
+ * ```
12
+ *
13
+ * The routing is Analog's own, not a copy of it. What this adds is the two things Metro does not
14
+ * do as Vite does: it finds the pages with `require.context` rather than `import.meta.glob`, and
15
+ * it leaves `import.meta.env` undefined.
16
+ */
17
+ import { createRoutes } from '@analogjs/router';
18
+ import { MARKDOWN_PAGE, markdownPageFile } from '@ng-native/router';
19
+ /**
20
+ * The routes for an app's pages, as `createRoutes` makes them in an Analog app.
21
+ *
22
+ * `pages` is the `require.context` of the pages directory in an app, or in a Vitest test, which
23
+ * has no `require.context`, the files of an `import.meta.glob` such as
24
+ * `import.meta.glob('./pages/**\/*.page.ts')`.
25
+ *
26
+ * A `.md` file among them is a page too, at the URL its name gives it, as in Analog: its front
27
+ * matter `title` is the route's title and `meta` its `routeMeta.meta`, and it is drawn by
28
+ * `options.markdownPage`.
29
+ */
30
+ export function pageRoutes(pages, options = {}) {
31
+ defineImportMetaEnv();
32
+ const files = typeof pages === 'function' ? filesOf(pages) : pages;
33
+ return createRoutes(withMarkdownPages(files, options.markdownPage));
34
+ }
35
+ /**
36
+ * The files with each `.md` page renamed to the `.page.ts` it routes as, loading `markdownPage`
37
+ * with the file in its route data. Analog's own Markdown pages render with `@analogjs/content`,
38
+ * which draws HTML, so `createRoutes` is never handed one.
39
+ */
40
+ function withMarkdownPages(files, markdownPage) {
41
+ const markdown = Object.keys(files).filter((name) => name.endsWith('.md'));
42
+ if (!markdown.length)
43
+ return files;
44
+ if (!markdownPage) {
45
+ throw new Error(`${markdown[0]} is a Markdown page, and pageRoutes has no component to draw it with. Pass ` +
46
+ 'one: pageRoutes(pages, { markdownPage }). See injectMarkdownPage.');
47
+ }
48
+ const routed = {};
49
+ for (const [name, load] of Object.entries(files)) {
50
+ if (!name.endsWith('.md')) {
51
+ routed[name] = load;
52
+ continue;
53
+ }
54
+ const page = name.replace(/\.md$/, '.page.ts');
55
+ if (page in files) {
56
+ throw new Error(`${name} and ${page} are the same page. Keep one of them.`);
57
+ }
58
+ routed[page] = async () => {
59
+ const file = markdownPageFile(name.replace(/^.*?\/pages\//, ''), await load());
60
+ const { title, meta } = file.attributes;
61
+ return {
62
+ default: markdownPage,
63
+ routeMeta: {
64
+ ...(typeof title === 'string' ? { title } : {}),
65
+ ...(Array.isArray(meta) ? { meta } : {}),
66
+ data: { [MARKDOWN_PAGE]: file },
67
+ },
68
+ };
69
+ };
70
+ }
71
+ return routed;
72
+ }
73
+ /**
74
+ * The context's files as Analog's own glob names them, from the project root: `createRoutes`
75
+ * finds each page's route from what follows `/pages/` in its name.
76
+ */
77
+ function filesOf(pages) {
78
+ return Object.fromEntries(pages
79
+ .keys()
80
+ .map((key) => [`/src/app/pages/${key.replace(/^\.\//, '')}`, async () => pages(key)]));
81
+ }
82
+ /**
83
+ * `import.meta.env` as Vite defines it, on the object Expo's Babel preset turns `import.meta` into.
84
+ *
85
+ * Analog reads `import.meta.env.DEV` as it loads every page, and Expo defines only
86
+ * `import.meta.url`, so without this the first navigation fails with a TypeError. The registry
87
+ * exists once `expo` is imported, which an app's `main.ts` does first, and nothing reads `env`
88
+ * until a page loads, which is after this has run. An `env` already there is left as it is.
89
+ */
90
+ function defineImportMetaEnv() {
91
+ const registry = globalThis
92
+ .__ExpoImportMetaRegistry;
93
+ if (!registry || registry.env)
94
+ return;
95
+ const dev = typeof __DEV__ === 'boolean' && __DEV__;
96
+ registry.env = {
97
+ DEV: dev,
98
+ PROD: !dev,
99
+ SSR: false,
100
+ MODE: dev ? 'development' : 'production',
101
+ BASE_URL: '/',
102
+ };
103
+ }
104
+ //# sourceMappingURL=page-routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-routes.js","sourceRoot":"","sources":["../src/page-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,YAAY,EAAc,MAAM,kBAAkB,CAAC;AAG5D,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAoB,MAAM,mBAAmB,CAAC;AAiBtF;;;;;;;;;;GAUG;AACH,MAAM,UAAU,UAAU,CACxB,KAA8B,EAC9B,UAA6B,EAAE;IAE/B,mBAAmB,EAAE,CAAC;IACtB,MAAM,KAAK,GAAG,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IACnE,OAAO,YAAY,CAAC,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,YAAY,CAAU,CAAC,CAAC;AAC/E,CAAC;AAED;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,KAAgB,EAAE,YAAuC;IAClF,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3E,IAAI,CAAC,QAAQ,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACnC,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CACb,GAAG,QAAQ,CAAC,CAAC,CAAC,6EAA6E;YACzF,mEAAmE,CACtE,CAAC;IACJ,CAAC;IACD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WAAW,CACvB,KAAK;SACF,IAAI,EAAE;SACN,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,kBAAkB,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CACxF,CAAC;AACJ,CAAC;AAQD;;;;;;;GAOG;AACH,SAAS,mBAAmB;IAC1B,MAAM,QAAQ,GAAI,UAAgE;SAC/E,wBAAwB,CAAC;IAC5B,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,GAAG;QAAE,OAAO;IACtC,MAAM,GAAG,GAAG,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC;IACpD,QAAQ,CAAC,GAAG,GAAG;QACb,GAAG,EAAE,GAAG;QACR,IAAI,EAAE,CAAC,GAAG;QACV,GAAG,EAAE,KAAK;QACV,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,YAAY;QACxC,QAAQ,EAAE,GAAG;KACd,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Analog's file-based pages on a native stack: `pageRoutes` hands the files under\n * `src/app/pages` to `createRoutes` from `@analogjs/router`, so `index.page.ts`, `[id].page.ts`,\n * `(group)` folders, layouts and each page's `routeMeta` route as they do in an Analog app, and\n * `provideNativeRouter` takes the routes it returns.\n *\n * ```ts\n * const pages = require.context('./pages', true, /\\.page\\.ts$/, 'lazy');\n *\n * mount(rootTag, App, fabric, { providers: [provideNativeRouter(pageRoutes(pages))] });\n * ```\n *\n * The routing is Analog's own, not a copy of it. What this adds is the two things Metro does not\n * do as Vite does: it finds the pages with `require.context` rather than `import.meta.glob`, and\n * it leaves `import.meta.env` undefined.\n */\nimport { createRoutes, type Files } from '@analogjs/router';\nimport type { Type } from '@angular/core';\nimport type { Routes } from '@angular/router';\nimport { MARKDOWN_PAGE, markdownPageFile, type PageContext } from '@ng-native/router';\n\n/**\n * Each page's file name, with a call that loads it: what `import.meta.glob` returns, and what\n * `createRoutes` takes.\n */\nexport type PageFiles = Record<string, () => Promise<unknown>>;\n\nexport interface PageRoutesOptions {\n /**\n * The component a `.md` page is drawn with. It reads its file with `injectMarkdownPage()` and\n * draws `tokens` with `<markdown>` from `@ng-native/components/markdown`. Required when the\n * pages include a `.md` file. The same component draws one under `fileRoutes`.\n */\n markdownPage?: Type<unknown>;\n}\n\n/**\n * The routes for an app's pages, as `createRoutes` makes them in an Analog app.\n *\n * `pages` is the `require.context` of the pages directory in an app, or in a Vitest test, which\n * has no `require.context`, the files of an `import.meta.glob` such as\n * `import.meta.glob('./pages/**\\/*.page.ts')`.\n *\n * A `.md` file among them is a page too, at the URL its name gives it, as in Analog: its front\n * matter `title` is the route's title and `meta` its `routeMeta.meta`, and it is drawn by\n * `options.markdownPage`.\n */\nexport function pageRoutes(\n pages: PageContext | PageFiles,\n options: PageRoutesOptions = {},\n): Routes {\n defineImportMetaEnv();\n const files = typeof pages === 'function' ? filesOf(pages) : pages;\n return createRoutes(withMarkdownPages(files, options.markdownPage) as Files);\n}\n\n/**\n * The files with each `.md` page renamed to the `.page.ts` it routes as, loading `markdownPage`\n * with the file in its route data. Analog's own Markdown pages render with `@analogjs/content`,\n * which draws HTML, so `createRoutes` is never handed one.\n */\nfunction withMarkdownPages(files: PageFiles, markdownPage: Type<unknown> | undefined): PageFiles {\n const markdown = Object.keys(files).filter((name) => name.endsWith('.md'));\n if (!markdown.length) return files;\n if (!markdownPage) {\n throw new Error(\n `${markdown[0]} is a Markdown page, and pageRoutes has no component to draw it with. Pass ` +\n 'one: pageRoutes(pages, { markdownPage }). See injectMarkdownPage.',\n );\n }\n const routed: PageFiles = {};\n for (const [name, load] of Object.entries(files)) {\n if (!name.endsWith('.md')) {\n routed[name] = load;\n continue;\n }\n const page = name.replace(/\\.md$/, '.page.ts');\n if (page in files) {\n throw new Error(`${name} and ${page} are the same page. Keep one of them.`);\n }\n routed[page] = async () => {\n const file = markdownPageFile(name.replace(/^.*?\\/pages\\//, ''), await load());\n const { title, meta } = file.attributes;\n return {\n default: markdownPage,\n routeMeta: {\n ...(typeof title === 'string' ? { title } : {}),\n ...(Array.isArray(meta) ? { meta } : {}),\n data: { [MARKDOWN_PAGE]: file },\n },\n };\n };\n }\n return routed;\n}\n\n/**\n * The context's files as Analog's own glob names them, from the project root: `createRoutes`\n * finds each page's route from what follows `/pages/` in its name.\n */\nfunction filesOf(pages: PageContext): PageFiles {\n return Object.fromEntries(\n pages\n .keys()\n .map((key) => [`/src/app/pages/${key.replace(/^\\.\\//, '')}`, async () => pages(key)]),\n );\n}\n\ndeclare const __DEV__: boolean | undefined;\n\ninterface ImportMetaRegistry {\n env?: Record<string, unknown>;\n}\n\n/**\n * `import.meta.env` as Vite defines it, on the object Expo's Babel preset turns `import.meta` into.\n *\n * Analog reads `import.meta.env.DEV` as it loads every page, and Expo defines only\n * `import.meta.url`, so without this the first navigation fails with a TypeError. The registry\n * exists once `expo` is imported, which an app's `main.ts` does first, and nothing reads `env`\n * until a page loads, which is after this has run. An `env` already there is left as it is.\n */\nfunction defineImportMetaEnv(): void {\n const registry = (globalThis as { __ExpoImportMetaRegistry?: ImportMetaRegistry })\n .__ExpoImportMetaRegistry;\n if (!registry || registry.env) return;\n const dev = typeof __DEV__ === 'boolean' && __DEV__;\n registry.env = {\n DEV: dev,\n PROD: !dev,\n SSR: false,\n MODE: dev ? 'development' : 'production',\n BASE_URL: '/',\n };\n}\n"]}
package/metro.cjs ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The Metro config Analog's pages need, on top of `withAngularNative`.
3
+ *
4
+ * ```js
5
+ * const { getDefaultConfig } = require('expo/metro-config');
6
+ * const { withAngularNative } = require('@ng-native/metro/config.cjs');
7
+ * const { withAnalog } = require('@ng-native/analog/metro');
8
+ *
9
+ * module.exports = withAnalog(withAngularNative(getDefaultConfig(__dirname)));
10
+ * ```
11
+ *
12
+ * Two things. `require.context`, which finds the pages, is on: Expo turns it on already, and a
13
+ * config that does not start from Expo's has it off. And `@analogjs/router`'s import of
14
+ * `@analogjs/content` resolves to an empty module. It imports it for a Markdown page alone, with
15
+ * an `import()` Metro resolves at build time whether or not a page is Markdown, so without it no
16
+ * bundle builds where the package is not installed, and where it is, as npm installs it for being
17
+ * a peer of the router, the bundle carries it and the Markdown parser behind it for nothing. The
18
+ * app's own imports of it resolve as they do, and fail to resolve when it is not installed, so the
19
+ * build names the missing package rather than the app failing at runtime.
20
+ */
21
+
22
+ /** Marks a resolver this already wrapped, so applying it twice wraps it once. */
23
+ const WRAPPED = Symbol.for('ng-native.analog.resolveRequest');
24
+
25
+ /** A file of `@analogjs/router`, wherever the package manager put it. */
26
+ const ANALOG_ROUTER = /[\\/]@analogjs[\\/]router[\\/]/;
27
+
28
+ /**
29
+ * @param {object} config a Metro config, usually `withAngularNative`'s
30
+ * @returns {object} the same config
31
+ */
32
+ function withAnalog(config) {
33
+ config.transformer = { ...config.transformer, unstable_allowRequireContext: true };
34
+ const next = config.resolver.resolveRequest;
35
+ if (next?.[WRAPPED]) return config;
36
+ const resolveRequest = (context, name, platform) => {
37
+ const resolve = next ?? context.resolveRequest;
38
+ if (name === '@analogjs/content' && ANALOG_ROUTER.test(context.originModulePath ?? '')) {
39
+ return { type: 'empty' };
40
+ }
41
+ return resolve(context, name, platform);
42
+ };
43
+ resolveRequest[WRAPPED] = true;
44
+ config.resolver.resolveRequest = resolveRequest;
45
+ return config;
46
+ }
47
+
48
+ module.exports = { withAnalog };
package/package.json CHANGED
@@ -1,12 +1,74 @@
1
1
  {
2
2
  "name": "@ng-native/analog",
3
- "version": "0.0.1",
4
- "description": "Reserved for ng-native. The first release follows.",
3
+ "version": "0.6.0",
4
+ "description": "Analog's file-based pages and content files for Angular Native: src/app/pages, routed by @analogjs/router on a native stack, and src/content read as @analogjs/content reads it.",
5
+ "keywords": [
6
+ "angular",
7
+ "react-native",
8
+ "angular-native",
9
+ "ios",
10
+ "android",
11
+ "fabric",
12
+ "native",
13
+ "analog",
14
+ "analogjs",
15
+ "router",
16
+ "file-based-routing",
17
+ "markdown",
18
+ "content"
19
+ ],
20
+ "type": "module",
21
+ "main": "dist/index.js",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./metro": "./metro.cjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "peerDependencies": {
34
+ "@analogjs/router": "^2.8.0",
35
+ "@angular/core": "^22.0.0",
36
+ "@angular/router": "^22.0.0",
37
+ "@ng-native/router": "0.6.0",
38
+ "rxjs": "^7.4.0"
39
+ },
40
+ "devDependencies": {
41
+ "@analogjs/router": "~2.8.0",
42
+ "@angular/common": "22.2.0",
43
+ "@angular/core": "22.2.0",
44
+ "@angular/platform-browser": "22.2.0",
45
+ "@angular/router": "22.2.0",
46
+ "@ng-native/router": "0.6.0",
47
+ "rxjs": "^7.8.2"
48
+ },
49
+ "nx": {
50
+ "tags": [
51
+ "scope:analog",
52
+ "layer:angular-addon"
53
+ ]
54
+ },
5
55
  "license": "MIT",
56
+ "homepage": "https://ng-native.com/packages/analog",
57
+ "bugs": {
58
+ "url": "https://github.com/ng-native/ng-native/issues"
59
+ },
6
60
  "repository": {
7
61
  "type": "git",
8
62
  "url": "git+https://github.com/ng-native/ng-native.git",
9
63
  "directory": "packages/analog"
10
64
  },
11
- "publishConfig": { "access": "public" }
12
- }
65
+ "files": [
66
+ "dist",
67
+ "metro.cjs"
68
+ ],
69
+ "scripts": {
70
+ "build": "ngc -p tsconfig.build.json",
71
+ "typecheck": "tsc -p tsconfig.json --noEmit"
72
+ },
73
+ "types": "dist/index.d.ts"
74
+ }